1

I need to create a function which calculates NPV of Cash flows from a list, using different one-year discount rates at different points in time. Such that r is a list of floats of length len(cash flows)-1, where the value at position 'i' is discount rate to use between periods i and i + 1. Cannot use numpy as this is the requirement of an assignment.

cash_flows = [1000, 5000, 3000] r = [0.05, 0.08, 0.1]

I am new to python and have written below after understanding from here and my class. If you can please help. Thanks!

def npv(cash_flows, r):

for t, cf in enumerate(cash_flows, 1): 
    for t, r in enumerate(r, 1):
        result = 0
        result += (cf/(1 + r) ** t)

return result

How to get a changing discount rate as enumerate only takes 2 parameters?

Sarja
  • 11
  • 2
  • during the loop you set the value of `result` each time to `0` . Is that by design? – balderman Sep 04 '21 at 09:24
  • No, that was a mistake. I just wanted the NPV to have 0 value at start and should have added it before the for loop. – Sarja Sep 04 '21 at 10:10

1 Answers1

0

You can use enumerate along with zip.

Here is the description on zip function. zip function

cash_flows = [1000, 5000, 3000]
r = [0.05, 0.08, 0.1]


def npv(cash_flows, rate):
    result = 0
    for t,(cf,r) in enumerate(zip(cash_flows,rate),1):
        result += (cf / (1 + r) ** t)
    return result


print(npv(cash_flows,r))
cigien
  • 57,834
  • 11
  • 73
  • 112
  • Thanks @Sarvesh Shetty. The r is discounting from the first cf value itself, but the first cf remains what it is and r discounts from the 2nd cf (cash flow) onwards. That is, division of r should happen from 2nd cf. How to achieve that? In excel it would look like this, CF r Discounted CF 1000 1000 2000 0.05 1333.333333 3000 0.08 2572.016461 SUM 4905.349794 – Sarja Sep 04 '21 at 10:36