SARIMA 预测
月度制造业销售额的季节性 ARIMA 预测,附 80% 和 95% 区间,并与留出数据对比。

只有附带不确定性,预测才是诚实的。深色扇形为 80% 预测区间,浅色扇形为 95% 区间;两者都随预测期延长而变宽。最后两年数据在拟合时被留出,因此圆点显示的是实际发生的情况,副标题报告样本外 RMSE,以及这些月份中有多少落在 95% 区间之内。
背景为 Warin (2024, Technology Innovations in Statistics Education),介绍如何在统计学课程中使用加拿大统计局的开放经济数据,月度制造业销售额是典型的教学序列。此处数据为说明用途的模拟数据,并非加拿大统计局的数字:一条类似制造业销售额的序列,单位为十亿元,2005 年 1 月至 2023 年 12 月(228 个月),由含两次下滑(2009 年和 2020 年春)的趋势、固定的月度模式和噪声构成。同一条模拟序列用于 STL、SARIMA 和季节子序列三个示例。模型基于 2005–2021 年数据拟合,预测 2022–2023 年的 24 个月。它是季节性 ARIMA(1,1,1)(0,1,1)₁₂——经典的“航空”结构——用 statsmodels.tsa.statespace.SARIMAX 拟合;区间来自 get_forecast().conf_int()。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.tsa.statespace.sarimax import SARIMAX
# Simulated data, set in the context of Warin (2024) [warin2024statcan]
# Data: simulated monthly manufacturing sales, billions of dollars, 2005–2023 (shared generator)
rng = np.random.default_rng(2024)
idx = pd.date_range("2005-01-01", "2023-12-01", freq="MS")
t = np.arange(len(idx))
trend = 48 + 0.06 * t - 7 * np.exp(-((t - 54) / 9) ** 2) - 8 * np.exp(-((t - 183) / 2.5) ** 2)
season = np.tile([-3.0, -0.8, 2.6, 0.6, 1.2, 2.2, -3.4, -1.2, 1.6, 2.0, 0.4, -2.2], len(idx) // 12)
sales = pd.Series(trend + season + rng.normal(0, 0.7, len(idx)), index=idx)
h = 24 # hold out the last two years
train, test = sales[:-h], sales[-h:]
# Fit a seasonal ARIMA and forecast the held-out horizon
fit = SARIMAX(train, order=(1, 1, 1), seasonal_order=(0, 1, 1, 12)).fit(disp=False)
fc = fit.get_forecast(h)
mean, ci95, ci80 = fc.predicted_mean, fc.conf_int(alpha=0.05), fc.conf_int(alpha=0.20)
rmse = np.sqrt(((test - mean) ** 2).mean())
mae = (test - mean).abs().mean() # mean absolute error
covered = ((test >= ci95.iloc[:, 0]) & (test <= ci95.iloc[:, 1])).sum()
fig, ax = plt.subplots(figsize=(9, 5))
hist = train["2014":]
ax.plot(hist.index, hist, color="#1D1D1F", lw=1.4, label="Observed (training)")
ax.fill_between(mean.index, ci95.iloc[:, 0], ci95.iloc[:, 1], color="#007AFF", alpha=0.15, lw=0,
label="95% prediction interval")
ax.fill_between(mean.index, ci80.iloc[:, 0], ci80.iloc[:, 1], color="#007AFF", alpha=0.28, lw=0,
label="80% prediction interval")
ax.plot(mean.index, mean, color="#007AFF", lw=2, label="Forecast")
ax.scatter(test.index, test, s=16, color="#FF9500", edgecolor="white", lw=0.6, zorder=4,
label="Held-out actuals")
# Mark the forecast origin
ax.axvline(test.index[0], color="#AEAEB2", lw=1, ls="--")
ax.text(test.index[0], 0.97, " forecast origin", transform=ax.get_xaxis_transform(),
fontsize=9, color="#8E8E93", va="top")
ax.set(ylabel="Manufacturing sales (billions of dollars)", xlim=(hist.index[0], test.index[-1]))
ax.legend(loc="upper left", ncols=3)
ax.set_ylim(top=mean.max() + 12)
ax.set_title(f"A seasonal ARIMA tracks sales two years ahead, off by {mae:.1f} bn on average", pad=26)
ax.text(0, 1.02, f"SARIMA(1,1,1)(0,1,1)₁₂ · AIC = {fit.aic:.0f} · RMSE = {rmse:.2f} bn over {h} held-out "
f"months (simulated) · {covered}/{h} actuals inside the 95% PI",
transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()
图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。
数据来源
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - Warin (2024), Statistics Canada's open economic data for teaching. Warin, T. (2024). Access Statistics Canada's open economic data for statistics and data science courses. Technology Innovations in Statistics Education, 15(1). https://doi.org/10.5070/t5.1868
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not Statistics Canada's figures.
这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。
如何引用
PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。
Warin, T. (2026). SARIMA forecast. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/time-series/arima-forecast/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}