Hi I'm trying to calculate regression betas for an expanding window in pandas. I have the following function to calculate beta
def beta(row, col1, col2):
return numpy.cov(row[col1],row[col2]) / numpy.var(row[col1])
And I've tried the following to get the expanding beta on my dataframe df
pandas.expanding_apply(df, beta, col1='col1', col2='col2')
pandas.expanding_apply(df, beta, kwargs={'col1':'col1', 'col2':'col2'})
df.expanding.apply(...)
However none of them work, I either get something that says the kwargs aren't getting passed through or if I hardcode the column names in the beta
function I get
*** IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
Thanks
Example:
def beta(row, col1, col2):
return numpy.cov(row[col1],row[col2]) / numpy.var(row[col1])
df = pandas.DataFrame({'a':[1,2,3,4,5],'b':[.1,5,.3,.5,6]})
pandas.expanding_apply(compute_df, beta, col1='a', col2='b')
pandas.expanding_apply(compute_df, beta, kwargs={'col1':'a', 'col2':'b'})
Both of those return errors