代码之家  ›  专栏  ›  技术社区  ›  Chris Snow

如何用statsmodels时间序列模型获得预测区间?

  •  0
  • Chris Snow  · 技术社区  · 6 年前

    是否有一个statsmodels API从statsmodels timeseries模型中检索预测间隔?

    目前,我正在使用以下方法手动计算预测间隔:

    enter image description here

    这是我的密码。首先,获取一些样本数据。。。

    ! python -c 'import datapackage' || pip install datapackage
    
    %matplotlib inline
    
    import datapackage
    
    from statsmodels.graphics.tsaplots import plot_acf
    from statsmodels.tsa.api import SimpleExpSmoothing
    import statsmodels.api as sm
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    def get_data():
        # data licensed for non-commercial use only - https://datahub.io/core/bond-yields-uk-10y
        data_url = 'https://datahub.io/core/bond-yields-uk-10y/datapackage.json'
    
        resources = datapackage.Package(data_url).resources
    
        quarterly_csv_url = [pkg for pkg in resources if pkg.name == 'quarterly_csv'][0].descriptor['path']
        data = pd.read_csv(quarterly_csv_url)
        data = data.set_index('Date', drop=True).asfreq('Q')
        return data
    

    data = get_data()
    data = data[ data.index > '2005/']
    
    fit = SimpleExpSmoothing(data).fit()
    fcast = fit.forecast(1).rename('Forecast')
    xhat = fcast.get_values()[0]
    
    z = 1.96
    sse = fit.sse
    predint_xminus = xhat - z * np.sqrt(sse/len(data))
    predint_xplus  = xhat + z * np.sqrt(sse/len(data))
    

    绘制间隔。。。

    plt.rcParams["figure.figsize"] = (20,5)
    
    ax = data.plot(legend=True, title='British Goverment Bonds - 10y')
    ax.set_xlabel('yield')
    
    #
    # 1-Step Prediction
    #
    prediction = pd.DataFrame( 
        data  = [ data.values[-1][0],  xhat ], 
        index = [ data.index[-1],      data.index[-1] + 1 ],
        columns = ['1-Step Predicted Rate']
    )
    _ = prediction.plot(ax=ax, color='black')
    
    #
    # upper 95% prediction interval
    #
    upper_pi_data = pd.DataFrame( 
        data  = [ xhat,           predint_xplus ], 
        index = [ data.index[-1], data.index[-1] + 1 ]
    )
    _ = upper_pi_data.plot(ax=ax, color='green', legend=False) 
    
    #
    # lower 95% prediction interval
    #
    lower_pi_data = pd.DataFrame( 
        data  = [ xhat,           predint_xminus ], 
        index = [ data.index[-1], data.index[-1] + 1 ]
    )
    _ = lower_pi_data.plot(ax=ax, color='green', legend=False) 
    

    enter image description here

    我发现了类似的问题,但不是针对timeseries模型:

    0 回复  |  直到 6 年前
        1
  •  2
  •   Ryan Boch    5 年前

    Forecasting Principles and Practice

    State Space Modeling for Local Linear Trend 在statsmodels中提供了一个工作示例。 在statsmodels中似乎没有任何现成的方法来生成这些间隔。 我个人决定使用R来获得我的预测时间间隔,因为预测包提供这些时间间隔而不需要额外的努力。

    推荐文章