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

问题描述 投票:1回答:1

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

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

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

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

statsmodels
1个回答
2
投票

只要你检查残差是不相关的假设并且你没有超过一步,我认为你的预测间隔是有效的。注意:我会使用残差的标准差。见Forecasting Principles and Practice的3.5节。

我很确定我们需要根据多步预测间隔的预测原则和实践将我们使用的模型放入状态空间形式。有关指数平滑的信息,请参见第7.5章。 statsmodels中的State Space Modeling for Local Linear Trend提供了一个工作示例。在statsmodel中看起来没有任何开箱即可产生这些间隔的东西。我个人决定使用R来获取我的预测间隔,因为预测包提供了这些,而无需额外的努力。

© www.soinside.com 2019 - 2024. All rights reserved.