mercredi 6 juillet 2016

Better way to do rolling beta for groupby in pandas


This is related to a prior question I asked - Calculate rolling correlation with pandas. In order to calculate correlation, I define the below function and apply to the df.

def roll_beta_groupby(x):
    x['Mkt_Corr'] = pd.rolling_corr(x['Mkt Return_weighted'], x['Excess Rtn % MTD'],window = 36,min_periods = 36)
    x.drop('Mkt_Corr',axis = 1,inplace = True)
    return x

df = df.groupby(['key']).apply(roll_beta_groupby)

Is there a better way to do this? I tried:

df.groupby(['key'])['Col1'].rolling(window = i).corr(df['Col2'])

but did not have any luck.

Better in the sense that my function Seems to take a long time and Will not take inputs like window size. Also, it Seems like there should be a cleaner way to do use rolling functions and group by together.


Aucun commentaire:

Enregistrer un commentaire