首页 > 解决方案 > 如何将代码从 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

标签: pythonpandasregressionstatsmodels

解决方案


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

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. 获取要保留的 beta 列表。我们不想要const哪个被添加add_constant
  3. 仅使用 调用同一组RollingOLS。重命名yendogxexog
  4. 您需要显式调用fit()on RollingOLS
  5. 使用 访问系数params,并使用keep保留相关系数。

推荐阅读