计算NPV和IRR,可以直接调用numpy或是numpy-financial模块的npv()和irr()函数,具体请移步https://hityne.com/390.html。本文介绍的是如何直接自己写计算npv和irr代码。
NPV
计算npv比较简单,原理就是将每个现金流的现值累加在一起。
def npv_f(rate,cashflows):
total=0.0
for i, cashflow in enumerate(cashflows):
total+=cashflow/(1+rate)**i
return total
IRR
这里提供计算irr的两种方法。方法1在一些情况下算不出来,方法2更普遍使用。
方法1
def irr_f(cashflows,interations=100):
if len(cashflows)==0:
print('number of cash flows is zero')
return np.nan
else:
tmp = [1 if each>=0 else 0 for each in cashflows]
if tmp.count(1)==0 or tmp.count(0)==0:
print("全大于等于0,或全小于0")
return np.nan
else:
rate=1.0
investment=cashflows[0]
for i in range(1,interations+1):
rate*=(1-npv_f(rate,cashflows)/investment)
return rate
方法2
def irr_f2(cashflows,interations=100):
if len(cashflows)==0:
print('number of cash flows is zero')
return np.nan
else:
tmp = [1 if each>=0 else 0 for each in cashflows]
if tmp.count(1)==0 or tmp.count(0)==0:
print("全大于等于0,或全小于0")
return np.nan
else:
rate=0.1
minDistance = 1e-15
wasHi = False
if np.sum(cashflows)>=0:
irr = rate
else:
rate = 0.5
irr = -1*rate
investment=cashflows[0]
for i in range(1,interations+1):
npv = npv_f(irr,cashflows)
if abs(npv) <=0.01:
return irr
if npv > 0:
if wasHi == True:
rate = rate/2
irr = irr + rate
if wasHi == True:
rate -= minDistance
wasHi = False
if npv < 0:
rate = rate/2
irr = irr - rate
wasHi = True
if rate <= minDistance:
return irr
return rate