Numpy的npv计算

时间:2012-08-12 16:48:38

标签: python numpy finance

我正在用numpy和我自己的代码计算NPV,结果不同。我必须在某处犯错。任何指针?

// Solution 1
r = .06
flows = {0:1200, 3:-450, 6:-450, 15:-450}
print  sum([C/(1+r)**i for i,C in flows.iteritems()])
// => 317

// Solution using numpy's npv function
flows = zeros(16)
flows[0] = 1200
flows[3] = -450
flows[6] = -450
flows[15]= -450
print np.npv(r, flows)
// => 299

2 个答案:

答案 0 :(得分:5)

看起来(尽管它说in the docsnp.npv开始用t = 1求和,而不是t = 0:

In [56]: r = 0.06

In [57]: R = r+1

In [58]: (1200/R**0 - 450/R**3 - 450/R**6 - 450/R**15)
Out[58]: 317.16980210661666

In [59]: (1200/R**0 - 450/R**3 - 450/R**6 - 450/R**15)/R
Out[59]: 299.21679444020435

In [64]: np.npv(r, flows)*(1+r)
Out[64]: 317.16980210661683

确实,np.npvdefined this way

def npv(rate, values):
    values = np.asarray(values)
    return (values / (1+rate)**np.arange(1,len(values)+1)).sum(axis=0)

答案 1 :(得分:0)

这已在numpy 1.8

中修复
  

修复financial.npv

     

npv函数有一个bug。与文件所述相反,   它从索引1到M而不是0到M - 1求和。修复   更改返回的值。 mirr函数称为npv函数,   但解决了这个问题,所以这也是固定和返回   mirr函数的值保持不变。

NumPy 1.8.0 Release Notes

如果我在np.npv中使用numpy 1.8,我会:

import numpy as np

r = .06

flows = np.zeros(16)
flows[0] = 1200
flows[3] = -450
flows[6] = -450
flows[15]= -450

result = np.npv(r, flows)

结果:

>>> result
317.16980210661666