【问题标题】:How to obtain prediction intervals with statsmodels timeseries models?如何使用 statsmodels 时间序列模型获得预测区间?
【发布时间】:2019-07-11 05:00:31
【问题描述】:

是否有 statsmodels API 可以从 statsmodels 时间序列模型中检索预测区间?

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

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

! 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) 

我发现了类似的问题,但不是针对时间序列模型的:

【问题讨论】:

    标签: statsmodels


    【解决方案1】:

    只要您检查残差不相关的假设并且您不超过一步,我认为您的预测区间是有效的。注意:我会使用残差的标准差。请参阅Forecasting Principles and Practice 中的第 3.5 节。

    我很确定我们需要根据多步预测区间的预测原理和实践将我们正在使用的模型放入状态空间形式。请参阅第 7.5 章关于指数平滑的内容。 statsmodels 中的State Space Modeling for Local Linear Trend 提供了一个工作示例。 看起来没有什么开箱即用的东西可以在 statsmodels 中生成这些区间。 我个人决定使用 R 来获取我的预测区间,因为预测包无需大量额外工作即可提供这些.

    更新:请参阅下面的评论。 Statsmodels 现在有一些指数平滑模型的状态空间表示。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-18
    • 2020-09-17
    • 2021-12-09
    • 2018-12-21
    • 1970-01-01
    • 2018-11-19
    • 2013-07-07
    相关资源
    最近更新 更多