Financial Calculations Practical Guide with Python and R by Demirel Engin

Financial Calculations Practical Guide with Python and R by Demirel Engin

Author:Demirel, Engin
Language: eng
Format: epub
Published: 2023-11-26T00:00:00+00:00


CHAPTER 4

20 commonly used code examples for making investment decisions in both R and Python:

1. Net Present Value (NPV)

Net present value (NPV) is used to assess how profitable a project or investment is. It calculates the difference over time between the present value of cash inflows and outflows.

# R

npv <- function(cash_flows, discount_rate) {

npv_value <- sum(cash_flows / (1 + discount_rate)^(1:length(cash_flows)))

return(npv_value)

}

# Python

def npv(cash_flows, discount_rate):

npv_value = np.sum(cash_flows / (1 + discount_rate) ** np.arange(1, len(cash_flows) + 1))

return npv_value

Example

# R

cash_flows <- c(100, 200, 300, 400, 500)

discount_rate <- 0.05

npv <- function(cash_flows, discount_rate) {

npv_value <- sum(cash_flows / (1 + discount_rate)^(1:length(cash_flows)))

return(npv_value)

}

result <- npv(cash_flows, discount_rate)

print(result)

# Python

import numpy as np

cash_flows = np.array([100, 200, 300, 400, 500])

discount_rate = 0.05

def npv(cash_flows, discount_rate):

npv_value = np.sum(cash_flows / (1 + discount_rate) ** np.arange(1, len(cash_flows) + 1))

return npv_value

result = npv(cash_flows, discount_rate)

print(result)

Output

R

[1] 1256.639

Python

1256.63934364013



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.