In [1]:
%matplotlib inline
import pandas as pd
import statsmodels.api as sm 
import numpy as np
import pandas.io.data as web
import datetime

In [2]:
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2014, 12, 31)
prices = web.DataReader(["SPY", "SPXU"], data_source="yahoo", start=start, end=end)["Adj Close"]
returns = np.log(prices / prices.shift(1))
returns = returns[1:]

In [3]:
def compute_ols_beta(returns_window):
    X = sm.add_constant(returns_window['SPXU'].values)
    ols_result = sm.OLS(returns_window['SPY'].values, X).fit()
    return ols_result.params[1]

def rolling_apply_df(df, window, func):
    return pd.Series((compute_ols_beta(df[i:i + window]) for i in range(len(df) - window)), index=df.index[window:])

ols_window = 120
beta_over_time = rolling_apply_df(returns, ols_window, compute_ols_beta)

In [4]:
beta_over_time.plot()


Out[4]:
<matplotlib.axes._subplots.AxesSubplot at 0x108e55750>

In [5]:
X = sm.add_constant(returns['SPXU'].values[1:])
result = sm.OLS(returns['SPY'].values[1:], X).fit()
print(result.summary())


                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.992
Model:                            OLS   Adj. R-squared:                  0.992
Method:                 Least Squares   F-statistic:                 1.593e+05
Date:                Wed, 08 Jul 2015   Prob (F-statistic):               0.00
Time:                        19:24:48   Log-Likelihood:                 7047.7
No. Observations:                1256   AIC:                        -1.409e+04
Df Residuals:                    1254   BIC:                        -1.408e+04
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
const         -0.0002   2.51e-05     -8.615      0.000        -0.000    -0.000
x1            -0.3340      0.001   -399.144      0.000        -0.336    -0.332
==============================================================================
Omnibus:                      765.986   Durbin-Watson:                   2.533
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           473228.381
Skew:                          -1.441   Prob(JB):                         0.00
Kurtosis:                      98.049   Cond. No.                         33.5
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.