Rolling Regression Estimation in Python dataframe

I also needed to do some rolling regression, and encountered the issue of pandas depreciated function in the pandas.ols. Below, is my work-around

Basically, I use create an empty numpy array first, then use numpy polyfit to generate the regression values in a for-loop. Then I add the numpy arrays into the panda dataframe. Hope that helps the community!

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]

statsmodels 0.11.0 added RollingOLS (Jan2020)

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

Or use R-style regression formula

model = RollingOLS.from_formula('Y ~ X1 + X2 + X3' , data = df, window=20)
rres = model.fit()
rres.params.tail()

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