当利率和付款随时间变化时,如何用 Pandas 计算投资的未来价值?

How to calculate future value of investment with Pandas when interest rates and payments vary over time?

假设我想知道我的投资价值如何随时间变化。我在 Pandas DataFrame 中有以下数据:

            contribution    monthly_return
2020-01-01  91.91           np.Nan
2020-02-01  102.18          0.037026
2020-03-01  95.90          -0.012792
2020-04-01  117.89         -0.009188    
2020-05-01  100.44          0.011203
2020-06-01  98.89           0.053917
2020-07-01  106.10         -0.049397
2020-08-01  112.55          0.062375
2020-09-01  103.16         -0.063198

...等等。每个月我都会额外投资 "fund"(捐款)。每月 return 显示上个月我的钱的价值如何变化。

我想添加额外的列,我可以在其中找到有关每个月投资当前价值的信息(这样我就可以将其绘制在图表上)。据我所知,我不能使用任何 numpy 财务函数(例如 np.fv()),因为捐款和费率会随时间变化。可以累加出资,但不知道投资盈亏相加

这可能是一个微不足道的问题,但我完全被困住了,我在这个问题上浪费的时间比我承认的还要多。如有任何帮助,我们将不胜感激!

假设你有一个 df:

print(df)
            contribution  monthly_return
2020-01-01         91.91             NaN
2020-02-01        102.18        0.037026
2020-03-01         95.90       -0.012792
2020-04-01        117.89       -0.009188
2020-05-01        100.44        0.011203
2020-06-01         98.89        0.053917
2020-07-01        106.10       -0.049397
2020-08-01        112.55        0.062375
2020-09-01        103.16       -0.063198

然后让我们找出您的资金每月增长的乘数:

df['monthly_multiplier'] = 1 + df['monthly_return'].shift(-1)
print(df)
            contribution  monthly_return  monthly_multiplier
2020-01-01         91.91             NaN            1.037026
2020-02-01        102.18        0.037026            0.987208
2020-03-01         95.90       -0.012792            0.990812
2020-04-01        117.89       -0.009188            1.011203
2020-05-01        100.44        0.011203            1.053917
2020-06-01         98.89        0.053917            0.950603
2020-07-01        106.10       -0.049397            1.062375
2020-08-01        112.55        0.062375            0.936802
2020-09-01        103.16       -0.063198                 NaN

最后我们可以遍历行并查看您的财富增长情况:

df['fv'] = 0
fv = 0
for index, row in df.iterrows():
    fv = (fv+row['contribution'])*row['monthly_multiplier']
    df.loc[index,'fv']=fv
print(df)
            contribution  monthly_return  monthly_multiplier          fv
2020-01-01         91.91             NaN            1.037026   95.313060
2020-02-01        102.18        0.037026            0.987208  194.966728
2020-03-01         95.90       -0.012792            0.990812  288.194245
2020-04-01        117.89       -0.009188            1.011203  410.633607
2020-05-01        100.44        0.011203            1.053917  538.629162
2020-06-01         98.89        0.053917            0.950603  606.027628
2020-07-01        106.10       -0.049397            1.062375  756.546589
2020-08-01        112.55        0.062375            0.936802  814.171423
2020-09-01        103.16       -0.063198                 NaN         NaN

df['fv'] 是您在指定月份月底或下一次捐款之前的财富。