如何计算 Pandas DataFrame 上的滚动累积积
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15295434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate rolling cumulative product on Pandas DataFrame
提问by AP228
I have a time series of returns, rolling beta, and rolling alpha in a pandas DataFrame. How can I calculate a rolling annualized alpha for the alpha column of the DataFrame? (I want to do the equivalent to =PRODUCT(1+[trailing 12 months])-1 in excel)
我在 Pandas DataFrame 中有一个时间序列的回报、滚动 beta 和滚动 alpha。如何计算 DataFrame 的 alpha 列的滚动年化 alpha?(我想在 excel 中做等效于 =PRODUCT(1+[trailing 12 months])-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
I was surprised to see that there was no "rolling" function built into pandas for this, but I was hoping somebody could help with a function that I can then apply to the df['Alpha'] column using pd.rolling_apply.
我很惊讶地看到 Pandas 中没有为此内置“滚动”函数,但我希望有人可以帮助我提供一个函数,然后我可以使用 pd.rolling_apply 将其应用于 df['Alpha'] 列。
Thanks in advance for any help you have to offer.
预先感谢您提供的任何帮助。
回答by herrfz
will this do?
这行吗?
import pandas as pd
import numpy as np
# your DataFrame; df = ...
pd.rolling_apply(df, 12, lambda x: np.prod(1 + x) - 1)
回答by YaOzI
rolling_applyhas been dropped in pandas and replaced by more versatile
window methods(e.g. rolling()etc.)
rolling_apply已在 Pandas 中删除并被更通用的窗口方法取代
(例如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
回答by Zellint
It will be a bit faster, if you move those +/-1 out of df, like this:
如果您将 +/-1 移出 ,它会更快一点df,如下所示:
cumprod = (1.+df).rolling(window=12).agg(lambda x : x.prod()) -1

