我想探索在熊猫(或其他接受DataFrame / Series友好的库)中执行扩展OLS的解决方案。
pandas.stats.ols.MovingOLS
,因为它已过时; expanding_mean
。例如,有一个具有两列df
和X
的DataFrame y
。为了简化起见,我们只计算beta。
目前,我正在考虑类似
import numpy as np
import pandas as pd
import statsmodel.api as sm
def my_OLS_func(df, y_name, X_name):
y = df[y_name]
X = df[X_name]
X = sm.add_constatn(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.66666667
和1.038462
。
但是,此方法似乎不起作用,因为该方法似乎非常不灵活。我不确定如何将两个系列作为参数传递。 任何建议,将不胜感激。
答案 0 :(得分:1)
一种选择是使用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