我正try 用Python语言实现滚动回归,但使用统计模型‘MovingOLS’失败了.在我的数据框中,‘Year’栏指定了各自观测的年份.

现在,我想用一个滚动的两年窗口来回归‘F1_yield ’和‘WC’,这样,1998年对1999年的预测是基于之前的两年,1997年和1998年,但我没有得到有意义的结果,可能是因为我不知道如何正确设置window参数.那么,如何将window参数与‘Year’变量相关联呢?

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader as pdr
import seaborn
import statsmodels.api as sm
from statsmodels.regression.rolling import RollingOLS

d1 = {'ID': [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6], 'Earnings': [100, 200, 
400, 250, 300, 350, 400, 550, 700, 259, 300, 350, 270, 450, 340, 570, 340, 340], 'WC': 
[20, 40, 35, 55, 60, 65, 30, 28, 32, 45, 60, 52, 23, 54, 45, 87, 54, 65], 'Year': [1995, 
1996, 1997, 1996, 1997, 1998, 1995, 1997, 1998, 1996, 1997, 1998, 1995, 1997, 1998, 1996, 
1997, 1998], 'F1_Earnings': [120, 220, 420, 280, 530, 670, 780, 210, 950, 100, 120, 430, 
780, 210, 950, 100, 120, 430]}

df1 = pd.DataFrame(data=d1)

y = df1['F1_Earnings']
features = ["Earnings", "WC"]
x = df1[features]

rols = RollingOLS(y, x, window=2)
rres = rols.fit()
params = rres.params.copy()
params.index = np.arange(1, params.shape[0] + 1)
params.head()

推荐答案

我认为你遇到的一个问题是window (int): Length of the rolling window. Must be strictly larger than the number of variables in the model.(从documentation).

另外,window只是count个观察值.因此,window=2将只使用列表中前面的两个项目.这是行不通的,因为你每年的观察次数都是可变的.

此外,如果您想要斜率+截距,则需要手动添加截距(作为常量).

考虑到您每年的记录数量是可变的,我认为for循环是唯一真正的 Select .


import pandas as pd
from statsmodels.regression.linear_model import OLS

d1 = {
    'ID': [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],
    'Earnings': [100, 200, 400, 250, 300, 350, 400, 550, 700, 259, 300, 350, 270, 450, 340, 570, 340, 340],
    'WC': [20, 40, 35, 55, 60, 65, 30, 28, 32, 45, 60, 52, 23, 54, 45, 87, 54, 65],
    'Year': [1995, 1996, 1997, 1996, 1997, 1998, 1995, 1997, 1998, 1996, 1997, 1998, 1995, 1997, 1998, 1996, 1997, 1998],
    'F1_Earnings': [120, 220, 420, 280, 530, 670, 780, 210, 950, 100, 120, 430, 780, 210, 950, 100, 120, 430],
}

df1 = pd.DataFrame(data=d1)
# df1 = add_constant(df1)
df1['intercept'] = 1

outcome = ['F1_Earnings']
features = ["Earnings", "WC", 'intercept']

result = {}
for year in df1['Year'].unique():
    current_df = df1[(df1["Year"] <= year) & (df1["Year"] >= (year - 1))]
    model = OLS(current_df[outcome], current_df[features]).fit()
    result[year + 1] = model.params

Python相关问答推荐

替换为Pandas

Python-Polars:如何用两个值的平均值填充NA?

来自ARIMA结果的模型方程

从Python调用GMP C函数时的分段错误和内存泄漏

除了Python之外,可以替代bare?

KNN分类器中的GridSearchCV

使用argsorted索引子集索引数组

如何根据日期和时间将状态更新为已过期或活动?

使用plotnine和Python构建地块

使用SciPy进行曲线匹配未能给出正确的匹配

从收件箱中的列中删除html格式

2D空间中的反旋算法

如何让程序打印新段落上的每一行?

在线条上绘制表面

pyscript中的压痕问题

如何从数据库上传数据到html?

Maya Python脚本将纹理应用于所有对象,而不是选定对象

在输入行运行时停止代码

python—telegraph—bot send_voice发送空文件

替换现有列名中的字符,而不创建新列