How to perform rolling regression fast

Viewed 91

I am performing rolling regression on stock returns for the last 4 years with 26 factors. And I want to calculate Beta associated with each factor for each return. So I have two dataframe one with returns for years 2016-2020 and the factors. I used for loops to retrieve each value from the data frame and then perform rolling regression to find the Beta values, but it is taking too much time to compute. I want to make it faster. Is there any alternative to using for loops and making it faster?

This is my code right here:

N = len(XY)  #XY is merged dataset of sec_rets and fac_rets


regression = np.zeros((len(fac_rets.index),2)) 

for s in range(len(sec_rets.columns)):
    
    for i in range(N):
        XY.iloc[i:i+252]
        Y = XY.iloc[i:i+252, s]
        X = XY.iloc[i:i+252][fac_cols]
        regr = linear_model.LinearRegression()
        regr.fit(X,Y)
        coefs = pd.DataFrame(regr.coef_, index=fac_cols, columns=[s]) 
         
0 Answers
Related