用Python计算IRR

UGu*_*lli 2 python numpy pandas irr

我遇到了障碍,希望得到一些帮助。

问题陈述

我正在尝试用 Python 计算 30 多年现金流的 XIRR。

到目前为止我尝试过什么

然而,现有的库(如 numpy 和 pandas)似乎都不支持这一点。经过一些研究,我通过这个来源(https://vindeep.com/Corporate/XIRRCalculation.aspx)了解到,通过一些简单的操作,XIRR 可以从 IRR 计算出来。

So, all I need is an IRR function that is implemented well. The functionality used to exist in numpy but has moved to this other package (https://github.com/numpy/numpy-financial). While, this package works, it is very very slow. Here is a small test:

import pandas as pd
import numpy as np
import numpy_financial as npf
from time import time


# Generate some example data
t = pd.date_range('2022-01-01', '2037-01-01', freq='D')

cash_flows = np.random.randint(10000, size=len(t)-1)
cash_flows = np.insert(cash_flows, 0, -10000)

# Calculate IRR
start_timer = time()
npf.irr(cash_flows, guess)
stop_timer = time()
print(f"""Time taken to calculate IRR over 30 years of daily data: {round((stop_timer-start_timer)/60, 2)}""")
Run Code Online (Sandbox Code Playgroud)

One other alternative seems to be https://github.com/better/irr - however, this has an edge case bug that has not been addressed in over 4 years.

Can anyone kindly offer to a more stable implementation. It feels like such simple and very commonly used functionality and the lack of a good stable implementation surprises me. Can someone point to any good resources.

Thanks

Uday

Ale*_*sky 7

pyxirr创建者在这里。该库已经在一个金融项目中使用了一年多,但我最近才找到时间发布它。我们的任务是快速计算各种投资组合的 XIRR,而现有的实施很快就成为了瓶颈。pyxirr还模仿一些 numpy-financial 函数并且工作速度更快。

Excel 中的 XIRR 实现并不总是正确的。在边缘情况下,算法不会收敛并显示不正确的结果,而不是错误或 NA。可以使用函数检查结果xnpvxnpv(xirr_rate, dates, values)并且应该接近于零。同样,您可以irr使用npv函数进行检查:npv(irr_rate, values),但请注意Excel 和 numpy-financial 之间计算的差异npv


igr*_*nis 6

尝试使用pyxirr包。它是用 Rust 实现的,速度非常快。30 年的时间段大约需要 0.001 秒。