本文共 1381 字,大约阅读时间需要 4 分钟。
方法
model = pd.stats.ols.MovingOLS(y=df.y, x=df.x, window_type='rolling',window=1000, intercept=True)
在pandas2.x中去掉了
替换的代码如下:
window = 1000 a = np.array([np.nan] * len(df)) b = [np.nan] * len(df) # If betas required. y_ = df.y.values x_ = df[['x']].assign(constant=1).values for n in range(window, len(df)): y = y_[(n - window):n] X = x_[(n - window):n] # betas = Inverse(X'.X).X'.y betas = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y) y_hat = betas.dot(x_[n, :]) a[n] = y_hat b[n] = betas.tolist() # If betas required.或者:df=df.dropna() #uncomment this line to drop nanswindow = 5df['a']=None #constant df['b1']=None #beta1 df['b2']=None #beta2 for i in range(window,len(df)): temp=df.iloc[i-window:i,:] RollOLS=sm.OLS(temp.loc[:,'Y'],sm.add_constant(temp.loc[:,['time','X']])).fit() df.iloc[i,df.columns.get_loc('a')]=RollOLS.params[0] df.iloc[i,df.columns.get_loc('b1')]=RollOLS.params[1] df.iloc[i,df.columns.get_loc('b2')]=RollOLS.params[2]当然,也有人自己写了一个模型解决这个问题,如下:# Rolling regressions from pyfinance.ols import OLS, RollingOLS, PandasRollingOLS y = data.usd x = data.drop('usd', axis=1) window = 12 # months model = PandasRollingOLS(y=y, x=x, window=window) print(model.beta.head())参考:主要是stackoverflow里面的2个网址https://www.e-learn.cn/content/wangluowenzhang/754972https://e-learn.cn/content/wangluowenzhang/192368
转自:
转载地址:http://jwfws.baihongyu.com/