The Functions Part 2
Solution
class Cashflow:
def __init__(self, val,t,r):
self.val = val
self.t = t
self.r = r
self.PV = self.valAt(0)
def valAt(self,time):
return self.val*(1+self.r)**(time-self.t)
def tryR(self,r):
return self.val*(1+r)**(0-self.t)
The only difference from the valAt() function is that we take r as a parameter, and also we use r for self.r and 0 for time. Now let’s create our IRR function. We make an NPV2 function first that returns the NPV for a given r.
def NPV2(r,arr):
return sum([x.tryR(r) for x in arr])
The only thing we change here is that we get the value for x.tryR(r) now. And we create our IRR function as so:
from scipy.optimize import fsolve
def findIRR(arr):
return fsolve(NPV2, 0,(arr))
We import fsolve from numpy, which allows for solving for the point where our equation equals 0. The three parameters of fsolve are the function we want to make equal to 0 (NPV2), a guess at what value of the first function parameter would be when the equation equals 0 (we guess r=0 to begin), and the extra parameters (the array is the extra parameter in this case that the function needs.)
print(findIRR([Cashflow(-1500.0,0.0,.05),Cashflow(1000.0,1.0,.05),Cashflow(1000.0,2.0,.05)]))
print(NPV2(.215250437022,[Cashflow(-1500.0,0,.05),Cashflow(1000.0,1,.05),Cashflow(1000.0,2,.05)]))
As you can see, our function works! We get an answer virtually equal to 0 for the NPV.