小编Ben*_*rin的帖子

通过向量化提高 np.irr 函数的性能

是否有可能提高 np.irr 函数的性能,使其可以在不使用 for 循环的情况下应用于二维现金流数组 - 通过向量化 np.irr 函数或通过替代算法?

numpy 库中的 irr 函数计算周期性复合回报率,为现金流数组提供 0 的净现值。该函数只能应用于一维数组:

x = np.array([-100,50,50,50])
r = np.irr(x)
Run Code Online (Sandbox Code Playgroud)

np.irr 不适用于二维现金流数组,例如:

cfs = np.zeros((10000,4))
cfs[:,0] = -100
cfs[:,1:] = 50
Run Code Online (Sandbox Code Playgroud)

其中每行代表一系列现金流,列代表时间段。因此,缓慢的实现是循环每一行并将 np.irr 应用于各个行:

out = []
for x in cfs:
    out.append(np.irr(x))
Run Code Online (Sandbox Code Playgroud)

对于大型数组,这是一个优化障碍。查看 np.irr 函数的源代码,我认为主要障碍是向量化 np.roots 函数:

def irr(values):
    res = np.roots(values[::-1])
    mask = (res.imag == 0) & (res.real > 0)
    if res.size == 0:
        return np.nan
    res = res[mask].real
    # NPV(rate) = 0 can have more than one …
Run Code Online (Sandbox Code Playgroud)

python numpy

5
推荐指数
1
解决办法
2456
查看次数

标签 统计

numpy ×1

python ×1