在 pandas 中高效扩展 OLS

Efficient expanding OLS in pandas

我想探索在 pandas(或其他接受 DataFrame/Series 友好的库)中高效执行扩展 OLS 的解决方案。

  1. 假设数据集很大,我对任何带有 for 循环的解决方案都不感兴趣;
  2. 我正在寻找有关扩展而不是滚动的解决方案。滚动函数总是需要固定的 window 而扩展使用变量 window (从头开始);
  3. 请不要推荐 pandas.stats.ols.MovingOLS 因为它已被弃用;
  4. 请不要推荐其他已弃用的方法,例如 expanding_mean

例如,有一个包含两列 Xy 的 DataFrame df。为了简单起见,我们只计算 beta。 目前,我正在考虑

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

def my_OLS_func(df, y_name, X_name):
  y = df[y_name]
  X = df[X_name]
  X = sm.add_constant(X)
  b = np.linalg.pinv(X.T.dot(X)).dot(X.T).dot(y)
  return b

df = pd.DataFrame({'X':[1,2.5,3], 'y':[4,5,6.3]})

df['beta'] = df.expanding().apply(my_OLS_func, args = ('y', 'X'))

df['beta'] 的预期值为 0(或 NaN)、0.666666671.038462

但是,这个方法好像行不通,因为这个方法看起来很不灵活。我不确定如何将这两个系列作为参数传递。 如有任何建议,我们将不胜感激。

一种选择是使用来自 Statsmodels 的 RecursiveLS(递归最小二乘法)模型:

# Simulate some data
rs = np.random.RandomState(seed=12345)

nobs = 100000
beta = [10., -0.2]
sigma2 = 2.5

exog = sm.add_constant(rs.uniform(size=nobs))
eps = rs.normal(scale=sigma2**0.5, size=nobs)
endog = np.dot(exog, beta) + eps

# Construct and fit the recursive least squares model
mod = sm.RecursiveLS(endog, exog)
res = mod.fit()
# This is a 2 x 100,000 numpy array with the regression coefficients
# that would be estimated when using data from the beginning of the
# sample to each point. You should usually ignore the first k=2
# datapoints since they are controlled by a diffuse prior.
res.recursive_coefficients.filtered