带有滚动窗口问题的Statsmodels OLS

时间:2019-01-11 18:49:40

标签: python regression

我想使用滚动窗口进行回归,但是回归后我只得到了一个参数:

 rolling_beta = sm.OLS(X2, X1, window_type='rolling', window=30).fit()
 rolling_beta.params

结果:

 X1    5.715089
 dtype: float64

可能是什么问题?

提前感谢,罗兰

1 个答案:

答案 0 :(得分:0)

我认为问题在于参数window_type='rolling'window=30根本不执行任何操作。首先,我将向您展示原因,最后,我将提供用于滚动窗口线性回归的设置。


1。。您的功能出现问题:

由于您没有提供一些示例数据,因此以下函数可以返回所需大小的数据帧,并带有一些随机数:

# Function to build synthetic data
import numpy as np
import pandas as pd
import statsmodels.api as sm
from collections import OrderedDict

def sample(rSeed, periodLength, colNames):

    np.random.seed(rSeed)
    date = pd.to_datetime("1st of Dec, 1999")   
    cols = OrderedDict()

    for col in colNames:
        cols[col] = np.random.normal(loc=0.0, scale=1.0, size=periodLength)
    dates = date+pd.to_timedelta(np.arange(periodLength), 'D')

    df = pd.DataFrame(cols, index = dates)
    return(df)

输出:

X1        X2
2018-12-01 -1.085631 -1.294085
2018-12-02  0.997345 -1.038788
2018-12-03  0.282978  1.743712
2018-12-04 -1.506295 -0.798063
2018-12-05 -0.578600  0.029683
.
.
.
2019-01-17  0.412912 -1.363472
2019-01-18  0.978736  0.379401
2019-01-19  2.238143 -0.379176

现在,尝试:

rolling_beta = sm.OLS(df['X2'], df['X1'], window_type='rolling', window=30).fit()
rolling_beta.params

输出:

X1   -0.075784
dtype: float64

这至少也代表了输出的结构,这意味着您期望每个示例窗口都有一个估算值,但您得到的是一个估算值。因此,我在网上和statsmodels文档中四处寻找使用同一功能的其他示例,但无法找到实际有效的特定示例。我确实找到了一些讨论,讨论不久前不推荐使用此功能。因此,我使用一些伪造的参数输入来测试相同的功能:

rolling_beta = sm.OLS(df['X2'], df['X1'], window_type='amazing', window=3000000).fit()
rolling_beta.params

输出:

X1   -0.075784
dtype: float64

如您所见,估算值是相同的,并且对于虚假输入,不会返回任何错误消息。因此,我建议您看一下下面的功能。这是我汇总来执行滚动回归估计的东西。


2。。该函数用于在熊猫数据框的滚动窗口上进行回归

df = sample(rSeed = 123, colNames = ['X1', 'X2', 'X3'], periodLength = 50)

def RegressionRoll(df, subset, dependent, independent, const, win, parameters):
    """
    RegressionRoll takes a dataframe, makes a subset of the data if you like,
    and runs a series of regressions with a specified window length, and
    returns a dataframe with BETA or R^2 for each window split of the data.

    Parameters:
    ===========

    df: pandas dataframe
    subset: integer - has to be smaller than the size of the df
    dependent: string that specifies name of denpendent variable
    inependent: LIST of strings that specifies name of indenpendent variables
    const: boolean - whether or not to include a constant term
    win: integer - window length of each model
    parameters: string that specifies which model parameters to return:
                BETA or R^2

    Example:
    ========
        RegressionRoll(df=df, subset = 50, dependent = 'X1', independent = ['X2'],
                   const = True, parameters = 'beta', win = 30)

    """

    # Data subset
    if subset != 0:
        df = df.tail(subset)
    else:
        df = df

    # Loopinfo
    end = df.shape[0]
    win = win
    rng = np.arange(start = win, stop = end, step = 1)

    # Subset and store dataframes
    frames = {}
    n = 1

    for i in rng:
        df_temp = df.iloc[:i].tail(win)
        newname = 'df' + str(n)
        frames.update({newname: df_temp})
        n += 1

    # Analysis on subsets
    df_results = pd.DataFrame()
    for frame in frames:
        #print(frames[frame])

        # Rolling data frames
        dfr = frames[frame]
        y = dependent
        x = independent

        if const == True:
            x = sm.add_constant(dfr[x])
            model = sm.OLS(dfr[y], x).fit()
        else:
            model = sm.OLS(dfr[y], dfr[x]).fit()

        if parameters == 'beta':
            theParams = model.params[0:]
            coefs = theParams.to_frame()
            df_temp = pd.DataFrame(coefs.T)

            indx = dfr.tail(1).index[-1]
            df_temp['Date'] = indx
            df_temp = df_temp.set_index(['Date'])

        if parameters == 'R2':
            theParams = model.rsquared
            df_temp = pd.DataFrame([theParams])
            indx = dfr.tail(1).index[-1]
            df_temp['Date'] = indx
            df_temp = df_temp.set_index(['Date'])
            df_temp.columns = [', '.join(independent)]
        df_results = pd.concat([df_results, df_temp], axis = 0)

    return(df_results)


df_rolling = RegressionRoll(df=df, subset = 50, dependent = 'X1', independent = ['X2'], const = True, parameters = 'beta',
                                     win = 30)

输出:一个数据帧,其中每30个周期窗口的X1上X2的OLS的beta估计值。

const        X2
Date                          
2018-12-30  0.044042  0.032680
2018-12-31  0.074839 -0.023294
2019-01-01 -0.063200  0.077215
.
.
.
2019-01-16 -0.075938 -0.215108
2019-01-17 -0.143226 -0.215524
2019-01-18 -0.129202 -0.170304