微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将代码从 PandasRollingOLS 更改为 RollingOLS?

如何解决如何将代码从 PandasRollingOLS 更改为 RollingOLS?

我正在读这本书 - https://github.com/stefan-jansen/machine-learning-for-trading/blob/c7e508dbe98e064887faeca65a45966e85af1c96/04_alpha_factor_research/01_feature_engineering.ipynb

看起来它在这代码中使用了弃用的 PandasRollingOLS 版本 - from statsmodels.regression.rolling import PandasRollingOLS

后来在这里引用- T = 24 betas = (factor_data .groupby(level='ticker',group_keys=False) .apply(lambda x: RollingOLS(window=min(T,x.shape[0]-1),y=x.return_1m,x=x.drop('return_1m',axis=1)).beta))

我希望有人能告诉我如何将这行代码转换为使用。 —— statsmodels.regression.rolling.RollingOLS

解决方法

不需要太多更改。您可以使用它代替原始笔记本中的相应单元格:

from statsmodels.api import add_constant
from statsmodels.regression.rolling import RollingOLS

T = 24
# Variables excluding "const"
keep=["Mkt-RF","SMB","HML","RMW","CMA"]

betas = (add_constant(factor_data)  # Add the constant
         .groupby(level='ticker',group_keys=False)
         .apply(lambda x: RollingOLS(window=min(T,x.shape[0]-1),endog=x.return_1m,exog=x.drop('return_1m',axis=1)).fit().params[keep]))

变化:

  1. 导入 RollingOLSadd_constant
  2. 获取要保留的测试版列表。我们不想要由 const
  3. 添加的 add_constant
  4. 仅使用 RollingOLS 调用同一组。将 y 重命名为 endog,将 x 重命名为 exog
  5. 您需要在 fit() 上显式调用 RollingOLS
  6. 使用 params 访问系数,并使用 keep 保留相关系数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。