applying custom rolling function to dataframe

Viewed 589

I am getting an exception when attempting to apply a custom rolling function to a pandas data frame. For example:

import statsmodels.api as sm
import pandas as pd
import numpy as np

def univar_regr_beta(y, x):
    Y, X = y.as_matrix(), x.as_matrix()

    X = sm.add_constant(X)

    model = sm.OLS(Y, X)
    return model.fit().params[1]

df = pd.DataFrame(np.random.randn(20,3))
srs = pd.Series(np.random.randn(20))

# this returns a value e.g.: 0.06608957
univar_regr_beta(df[0], srs)

# and this returns a rolling sum dataframe
df.rolling(5, 5).apply(np.sum)

# but this breaks when attemp to get rolling beta
df.rolling(5, 5).apply(lambda x: univar_regr_beta(x, srs))

Specifically the exception I get is the following:

AttributeError: 'numpy.ndarray' object has no attribute 'as_matrix'

It looks as though when each column is passed into univar_regr_beta via lambda, that it is being passed as a bumpy array as opposed to a Series. I am not sure if there is a better way to achieve a rolling beta, or if I am just missing something.

Any help is appreciated. Thanks

0 Answers
Related