Cof*_*nda 12 python dataframe pandas
我有这样的数据帧:
Date Y X1 X2 X3
22 2004-05-12 9.348158e-09 0.000081 0.000028 0.000036
23 2004-05-13 9.285989e-09 0.000073 0.000081 0.000097
24 2004-05-14 9.732308e-09 0.000085 0.000073 0.000096
25 2004-05-17 2.235977e-08 0.000089 0.000085 0.000099
26 2004-05-18 2.792661e-09 0.000034 0.000089 0.000150
27 2004-05-19 9.745323e-09 0.000048 0.000034 0.000053
......
1000 2004-05-20 1.835462e-09 0.000034 0.000048 0.000099
1001 2004-05-21 3.529089e-09 0.000037 0.000034 0.000043
1002 2004-05-24 3.453047e-09 0.000043 0.000037 0.000059
1003 2004-05-25 2.963131e-09 0.000038 0.000043 0.000059
1004 2004-05-26 1.390032e-09 0.000029 0.000038 0.000054
Run Code Online (Sandbox Code Playgroud)
我想运行一个滚动的100天窗口OLS回归估计,这是:
首先是第101行,我使用第1行到第100行运行Y-X1,X2,X3的回归,并估计第101行的Y;
然后对于第102行,我使用第2行到第101行运行Y-X1,X2,X3的回归,并估计第102行的Y;
然后对于第103行,我使用第2行到第101行运行Y-X1,X2,X3的回归,并估计第103行的Y;
......
直到最后一排.
这该怎么做?
Ale*_*der 17
model = pd.stats.ols.MovingOLS(y=df.Y, x=df[['X1', 'X2', 'X3']],
window_type='rolling', window=100, intercept=True)
df['Y_hat'] = model.y_predict
Run Code Online (Sandbox Code Playgroud)
statsmodels 0.11.0 添加了 RollingOLS(2020 年 1 月)
from statsmodels.regression.rolling import RollingOLS
#add constant column to regress with intercept
df['const'] = 1
#fit
model = RollingOLS(endog =df['Y'].values , exog=df[['const','X1','X2','X3']],window=20)
rres = model.fit()
rres.params.tail() #look at last few intercept and coef
Run Code Online (Sandbox Code Playgroud)
或者使用R型回归公式
model = RollingOLS.from_formula('Y ~ X1 + X2 + X3' , data = df, window=20)
rres = model.fit()
rres.params.tail()
Run Code Online (Sandbox Code Playgroud)
我还需要做一些滚动回归,在pandas.ols中遇到了pandas depreciated function的问题。下面是我的解决方法
基本上,我首先使用创建一个空的 numpy 数组,然后使用 numpy polyfit 在 for 循环中生成回归值。然后我将 numpy 数组添加到熊猫数据框中。希望对社会有所帮助!
data = pd.DataFrame(x_data, y_data)
regression = np.zeros((len(data.index),2)) #set the regression numpy array empty first
for row in range(0, len(data.index), 1):
y = data.y_data[row: row + 300]
x = data.x_data[row: row + 300]
regression[row] = np.polyfit(x, y, 1)
data['beta'] = regression[:,0]
data['alpha'] = regression[:,1]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14514 次 |
| 最近记录: |