def cumulative_ols(data_frame, lhs_column, rhs_column, date_column, min_obs=60
    ):
    """
    Function to perform a cumulative OLS on a Pandas data frame. It is
    meant to be used with `apply` after grouping the data frame by categories
    and sorting by date, so that the regression below applies to the time
    series of a single category's data and the use of `cumsum` will work    
    appropriately given sorted dates. It is also assumed that the date 
    conventions of the left-hand-side and right-hand-side variables have been 
    arranged by the user to match up with any lagging conventions needed.
    This OLS is implicitly univariate and relies on the simplification to the
    formula:
    Cov(x,y) ~ (1/n)*sum(x*y) - (1/n)*sum(x)*(1/n)*sum(y)
    Var(x)   ~ (1/n)*sum(x^2) - ((1/n)*sum(x))^2
    beta     ~ Cov(x,y) / Var(x)
    and the code makes a further simplification be cancelling one factor 
    of (1/n).
    Notes: one easy improvement is to change the date column to a generic sort
    column since there's no special reason the regressions need to be time-
    series specific.
    """
data_frame['xy'] = (data_frame[lhs_column] * data_frame[rhs_column]).fillna(0.0
    )
data_frame['x2'] = (data_frame[rhs_column] ** 2).fillna(0.0)
data_frame['yobs'] = data_frame[lhs_column].notnull().map(int)
data_frame['xobs'] = data_frame[rhs_column].notnull().map(int)
data_frame['cum_yobs'] = data_frame['yobs'].cumsum()
data_frame['cum_xobs'] = data_frame['xobs'].cumsum()
data_frame['cumsum_xy'] = data_frame['xy'].cumsum()
data_frame['cumsum_x2'] = data_frame['x2'].cumsum()
data_frame['cumsum_x'] = data_frame[rhs_column].fillna(0.0).cumsum()
data_frame['cumsum_y'] = data_frame[lhs_column].fillna(0.0).cumsum()
data_frame['cum_cov'] = data_frame['cumsum_xy'] - 1.0 / data_frame['cum_yobs'
    ] * data_frame['cumsum_x'] * data_frame['cumsum_y']
data_frame['cum_x_var'] = data_frame['cumsum_x2'] - 1.0 / data_frame['cum_xobs'
    ] * data_frame['cumsum_x'] ** 2
data_frame['FactorBeta'] = data_frame['cum_cov'] / data_frame['cum_x_var']
data_frame['FactorBeta'][data_frame['cum_yobs'] < min_obs] = np.NaN
return data_frame[[date_column, 'FactorBeta']].set_index(date_column)
Cumulative OLS with Python Pandas