Created
October 18, 2019 01:15
-
-
Save Skanda319/b396a7294a8c0870eee95314fd9a079d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# implements a rolling ridge regression of length window | |
window = 250 # train window | |
dt_list = [] | |
pred_list = [] | |
up1sd =[] | |
down1sd = [] | |
rsq = [] | |
pred_df = pd.DataFrame() | |
#xvars_df_zsc = (xvars_df_m - xvars_df_m.rolling(60).mean()) / xvars_df_m.rolling(60).std() | |
#reg_dat = pd.concat([xvars_df_zsc,y],axis=1).dropna() | |
beta_df = pd.DataFrame() | |
res = Ridge(alpha=0.1,normalize=True) | |
inputs = pd.DataFrame() | |
for i in range(window + 1,len(reg_dat.index)): | |
df_train = reg_dat.iloc[(i-window-1):(i)].dropna() | |
if(len(df_train) > 0): | |
df_test = reg_dat.iloc[[i]] | |
if(len(df_test.T.dropna()) > 0): | |
dt_list = dt_list + [reg_dat.index[i]] | |
x_train = df_train.drop(columns='Y_VAR') | |
res.fit(x_train,df_train['Y_VAR']) | |
resid = df_train['Y_VAR'] - res.predict(x_train) | |
res_sd = resid.std() | |
roll_beta = pd.DataFrame(res.coef_).T | |
roll_beta.index = [reg_dat.index[i]] | |
beta_df = pd.concat([beta_df,roll_beta],axis=0) | |
pred = res.predict(df_test.drop(columns='Y_VAR')) | |
inputs = inputs.append(df_test.drop(columns='Y_VAR')) | |
pred_list = pred_list + [pred] | |
up1sd = up1sd + [pred+res_sd] | |
down1sd = down1sd + [pred-res_sd] | |
#rsq = rsq + [res.rsquared] | |
pred_df = pd.DataFrame(pred_list,index=dt_list,columns=['FORECAST']) | |
up_df = pd.DataFrame(up1sd,index=dt_list,columns=['UP_1SD']) | |
down_df = pd.DataFrame(down1sd,index=dt_list,columns=['DOWN_1SD']) | |
#rsq_df = pd.DataFrame(rsq,index=dt_list,columns=['RSQ']) | |
pred_df = pd.concat([pred_df,up_df,down_df],axis=1) | |
reg_pred_df = pred_df.copy() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment