如何根据Python数据框内的每月观察结果计算12个月的回报?

时间:2019-07-15 06:14:55

标签: python dataframe time-series

如何在Pandas DataFrame上计算滚动累积产品。

我在pandas DataFrame中有一个时间序列的回报。如何计算DataFrame中相关列的滚动年度化alpha值?我通常会使用Excel并执行:=PRODUCT(1+[trailing 12 months])-1

我的DataFrame如下所示(一小部分):

                Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4  \

2009-08-31 00:00:00 --- --- 0.1489 0.072377
2009-09-30 00:00:00 --- --- 0.0662 0.069608
2009-10-31 00:00:00 --- --- -0.0288 -0.016967
2009-11-30 00:00:00 --- --- -0.0089 0.0009
2009-12-31 00:00:00 --- --- 0.044 0.044388
2010-01-31 00:00:00 --- --- -0.0301 -0.054953
2010-02-28 00:00:00 --- --- -0.0014 0.00821
2010-03-31 00:00:00 --- --- 0.0405 0.049959
2010-04-30 00:00:00 --- --- 0.0396 -0.007146
2010-05-31 00:00:00 --- --- -0.0736 -0.079834
2010-06-30 00:00:00 --- --- -0.0658 -0.028655
2010-07-31 00:00:00 --- --- 0.0535 0.038826
2010-08-31 00:00:00 --- --- -0.0031 -0.013885
2010-09-30 00:00:00 --- --- 0.0503 0.045781
2010-10-31 00:00:00 --- --- 0.0499 0.025335
2010-11-30 00:00:00 --- --- 0.012 -0.007495

我已经尝试了下面提供的类似问题的代码,但看来它不再起作用了……

import pandas as pd
import numpy as np

# your DataFrame; df = ...

pd.rolling_apply(df, 12, lambda x: np.prod(1 + x) - 1)

...和我重定向的页面似乎不相关。

理想情况下,我想重现DataFrame,但要有12个月的回报,而不是每月,所以我可以根据月份找到相关的12个月的回报。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,则可以尝试以下操作:

import pandas as pd
import numpy as np

#define dummy dataframe with monthly returns
df = pd.DataFrame(1 + np.random.rand(20), columns=['returns'])

#compute 12-month rolling returns
df_roll = df.rolling(window=12).apply(np.prod) - 1