AP2*_*228 8 python finance time-series pandas
我在pandas DataFrame中有一系列的回归,滚动测试和滚动alpha.如何计算DataFrame的alpha列的滚动年化alpha?(我想做相当于= PRODUCT(1+ [尾随12个月]) - excel中的1)
SPX Index BBOEGEUS Index Beta Alpha
2006-07-31 0.005086 0.001910 1.177977 -0.004081
2006-08-31 0.021274 0.028854 1.167670 0.004012
2006-09-30 0.024566 0.009769 1.101618 -0.017293
2006-10-31 0.031508 0.030692 1.060355 -0.002717
2006-11-30 0.016467 0.031720 1.127585 0.013153
Run Code Online (Sandbox Code Playgroud)
我很惊讶地看到pandas中没有内置"滚动"功能,但是我希望有人可以帮助我使用pd.rolling_apply然后应用于df ['Alpha']列的函数.
在此先感谢您提供的任何帮助.
her*_*rfz 18
这会吗?
import pandas as pd
import numpy as np
# your DataFrame; df = ...
pd.rolling_apply(df, 12, lambda x: np.prod(1 + x) - 1)
Run Code Online (Sandbox Code Playgroud)
小智 8
如果将 +/-1 移出 ,速度会快一点df,如下所示:
cumprod = (1.+df).rolling(window=12).agg(lambda x : x.prod()) -1
Run Code Online (Sandbox Code Playgroud)
rolling_apply已被丢弃在大熊猫中,并被更通用的窗口方法(例如,rolling()等)取代
# Both agg and apply will give you the same answer
(1+df).rolling(window=12).agg(np.prod) - 1
# BUT apply(raw=True) will be much FASTER!
(1+df).rolling(window=12).apply(np.prod, raw=True) - 1
Run Code Online (Sandbox Code Playgroud)