在pandas中进行滚动多项式回归

3

我对pandas还比较陌生,在搜索过程中并没有找到一个可行的答案。

到目前为止,我能够像这样计算简单回归的滚动系数 (Y= coef1 * A + coef2 * B)

model = pd.ols(y=df['Y'],x=df[['A','B']],window_type='rolling',window=100)

在statsmodels中,我可以进行多项式回归,但没有滚动窗口选项。model.beta返回coef1和coef2的DataFrame。
poly_2 = smf.ols(formula='Y ~ 1 + A+ I(B** 2.0)', data=df).fit()

我该如何“混合”这个多项式回归的滚动系数呢?我没有在pandas中找到编写patsy风格公式的方法,但也许是我搜索得不好。感谢你的帮助。
1个回答

3

多项式回归就是一个平凡的普通最小二乘回归,其中一个变量具有指数。使用smf.ols(我认为)唯一获得的好处就是能够使用类似于R的公式,例如I(B**2.0) 公式。但幸运的是,可以在没有smf的情况下构建相同的逻辑,然后可以使用Pandas ols。

让我们设置一些示例数据(提问时的一个很好的第一步):

n=500
df = pd.DataFrame(randn(n), index=pd.date_range('1/1/2000', periods=n))
df.columns = ['A']
df['B'] = randn(n)
df['Y'] = 5 + 3 * df.A + 6 * df.B **2 + randn(n)

在这个例子中,数据Y是A和B^2的函数。因此,我们可以使用没有多项式的滑动OLS:

pd.ols(y=df['Y'],x=df[['A','B']],window_type='rolling',window=100)
-------------------------Summary of Regression Analysis-------------------------

Formula: Y ~ <A> + <B> + <intercept>

Number of Observations:         100
Number of Degrees of Freedom:   3

R-squared:         0.1184
Adj R-squared:     0.1003

Rmse:              9.6488

F-stat (2, 97):     6.5159, p-value:     0.0022

Degrees of Freedom: model 2, resid 97

-----------------------Summary of Estimated Coefficients------------------------
      Variable       Coef    Std Err     t-stat    p-value    CI 2.5%   CI 97.5%
--------------------------------------------------------------------------------
             A     3.8514     1.0675       3.61     0.0005     1.7592     5.9436
             B     0.0693     0.9073       0.08     0.9393    -1.7091     1.8476
     intercept    11.8889     0.9655      12.31     0.0000     9.9965    13.7813
---------------------------------End of Summary---------------------------------

但如果你需要多项式,只需创建一个变量即可代表多项式:

df['B2'] = df.B **2

然后您可以使用B2运行OLS:

pd.ols(y=df['Y'],x=df[['A','B2']],window_type='rolling',window=100)

-------------------------Summary of Regression Analysis-------------------------

Formula: Y ~ <A> + <B2> + <intercept>

Number of Observations:         100
Number of Degrees of Freedom:   3

R-squared:         0.9869
Adj R-squared:     0.9867

Rmse:              1.1748

F-stat (2, 97):  3662.8849, p-value:     0.0000

Degrees of Freedom: model 2, resid 97

-----------------------Summary of Estimated Coefficients------------------------
      Variable       Coef    Std Err     t-stat    p-value    CI 2.5%   CI 97.5%
--------------------------------------------------------------------------------
             A     2.8258     0.1304      21.67     0.0000     2.5702     3.0814
            B2     6.0091     0.0748      80.29     0.0000     5.8624     6.1558
     intercept     5.1074     0.1448      35.28     0.0000     4.8237     5.3911
---------------------------------End of Summary---------------------------------

正交多项式呢? - tmthyjames
1
@tmthyjames,它们确实存在。如果您想得到更丰富的答案,您需要提出一个具体的问题。 - JD Long

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接