一个datafram中多列的滚动回归

2024-09-28 20:54:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的数据框,包含了20年内10000列(股票)的每日价格时间序列(5000行x 10000列)。缺失的观测值用NaNs表示。你知道吗

            0      1      2      3      4      5       6      7      8      \
31.12.2009  30.75  66.99    NaN    NaN    NaN    NaN  393.87  57.04    NaN   
01.01.2010  30.75  66.99    NaN    NaN    NaN    NaN  393.87  57.04    NaN   
04.01.2010  31.85  66.99    NaN    NaN    NaN    NaN  404.93  57.04    NaN   
05.01.2010  33.26  66.99    NaN    NaN    NaN    NaN  400.00  58.75    NaN   
06.01.2010  33.26  66.99    NaN    NaN    NaN    NaN  400.00  58.75    NaN   

现在我想在整个样本期内为每一列运行一个250天窗口的滚动回归,并将系数保存在另一个数据框中

使用两个for循环对列和行进行迭代不是很有效,所以我尝试了这个方法,但是得到了以下错误消息

def regress(start, end):
    y = df_returns.iloc[start:end].values

    if np.isnan(y).any() == False:
        X = np.arange(len(y))
        X = sm.add_constant(X, has_constant="add")
        model = sm.OLS(y,X).fit()

        return model.params[1]

    else:
        return np.nan


regression_window = 250

for t in (regression_window, len(df_returns.index)):

    df_coef[t] = df_returns.apply(regress(t-regression_window, t), axis=1)
TypeError: ("'float' object is not callable", 'occurred at index 31.12.2009')

Tags: 数据adddfforlennpnanwindow
1条回答
网友
1楼 · 发布于 2024-09-28 20:54:35

这是我的版本,使用测向滚动(),而不是遍历列。 我不完全确定这是你想要的不要犹豫发表评论

import statsmodels.regression.linear_model as sm
import statsmodels.tools.tools as sm2
df_returns =pd.DataFrame({'0':[30,30,31,32,32],'1':[60,60,60,60,60],'2':[np.NaN,np.NaN,np.NaN,np.NaN,np.NaN]})


def regress(X,Z):

    if np.isnan(X).any() == False:
        model = sm.OLS(X,Z).fit()        
        return model.params[1]

    else:
        return np.NaN


regression_window = 3
Z = np.arange(regression_window)
Z= sm2.add_constant(Z, has_constant="add")
df_coef=pd.DataFrame()
for col in df_returns.columns:
    df_coef[col]=df_returns[col].rolling(window=regression_window).apply(lambda col : regress(col, Z))
df_coef

相关问题 更多 >