日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python滑动窗口求回归——OLS和WLS

發布時間:2023/12/20 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python滑动窗口求回归——OLS和WLS 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

核心代碼其實就一行

modle=regression.linear_model.OLS(temp_y,index_x).fit()

預備:

指定窗口大小,半衰期和數據長度,求一個權重序列:

Example:


權重計算函數:

#n是窗口大小 #j可以理解為距離當前計算日期的天數(backward) #返回的數字是計算得出的權重的值 def cf(j,n,halflife):p1 = j # j從1開始,到n結束。p1是作為分子的p2 = halflife # p2是作為分母的p3 = math.pow(0.5,p1/p2)return p3def weight_list(length,halflife,window_size):out = list()# get weightsfor v in range(length):j = v + 1out.append(cf(j,window_size,halflife))return out

OLS版本:

import statsmodels.api as sm from statsmodels import regression# 子操作:窗口內的回歸 # 輸入解釋變量序列x和被解釋變量序列y,可以返回回歸的系數beta def linreg(x):x=sm.add_constant(x)global yindex_x=x.indextemp_y=y.loc[index_x] #y的index需要與df_x保持一致modle=regression.linear_model.OLS(temp_y,x).fit() # OLS的第一個參數是被解釋變量return modle.params[0] # 需要按列循環進行計算#%%導入必須的包 from sklearn.linear_model import LinearRegression as LR #線性回歸所需要的包 import pandas as pd#%%滾動回歸 y=Y.to_frame() #不得不用到的一個global變量,也就是回歸的y。Y是大盤收益率,為Tx1結構 df2=close_ret_rate # 個股日收益率表,為TxN的結構 window_size=100 halflife=25for each_column in df2.columns:print(each_column)# df2[each_column]=df2[each_column].rolling(window_size).apply(lambda x:linreg(pd.DataFrame(x)))

如果要算WLS版本的回歸

# 滾動回歸的另一個輪子,有效!!! # 需要按列循環進行計算 #%%導入必須的包 from sklearn.linear_model import LinearRegression as LR #線性回歸所需要的包 import pandas as pddef cf(j,n,halflife):p1 = j # j從1開始,到n結束。p1是作為分子的p2 = halflife # p2是作為分母的p3 = math.pow(0.5,p1/p2)return p3def weight_list(halflife,window_size):out = list()# get weightsfor v in range(window_size):j = v + 1out.append(cf(j,window_size,halflife))return out#%%滾動回歸 y=Y.to_frame() #不得不用到的一個global變量,也就是回歸的y df2=close_ret_rate window_size=60 halflife=30 weight_list=weight_list(halflife,window_size) print(weight_list)#首先定義一下apply里要用到的函數 def rolling_regression(df_x): #df_x是rolling取出來的回歸的x,是一個50乘1的dfglobal yglobal weight_listdf_x=sm.add_constant(df_x)index_x=df_x.indextemp_y=y.loc[index_x] #y的index需要與df_x保持一致modle=regression.linear_model.WLS(temp_y,df_x,weight_list).fit() return model.coef_[1]for each_column in df2.columns:print(each_column)df2[each_column]=df2[each_column].rolling(60).apply(lambda x:linreg(pd.DataFrame(x)))

總結

以上是生活随笔為你收集整理的python滑动窗口求回归——OLS和WLS的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。