STL 分解

将月度制造业销售额分解为趋势、季节和残余成分。

STL 分解

STL(基于 Loess 的季节–趋势分解)将序列写成观测值 = 趋势 + 季节 + 残余。各面板共用时间轴,但纵轴刻度各自独立,因此每个面板左侧的灰色竖条——在数据单位上长度完全相同——显示了每个成分的真实大小:竖条短,说明该成分占主导;竖条长,说明该成分较小。

背景为 Warin (2024, Technology Innovations in Statistics Education),介绍如何在统计学课程中使用加拿大统计局的开放经济数据,月度制造业销售额是典型的教学序列。此处数据为说明用途的模拟数据,并非加拿大统计局的数字:一条类似制造业销售额的序列,单位为十亿元,2005 年 1 月至 2023 年 12 月(228 个月),由含两次下滑(2009 年和 2020 年春)的趋势、固定的月度模式和噪声构成。同一条模拟序列用于 STL、SARIMA 和季节子序列三个示例。分解使用 statsmodels.tsa.seasonal.STL,周期 12 个月,采用稳健拟合;副标题按 Wang、Smith 和 Hyndman (2006) 的定义给出趋势强度和季节性强度。

代码及图中文字均为英文。

stl-decomposition.py · 50 行
下载 GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.tsa.seasonal import STL

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

res = STL(sales, period=12, robust=True).fit()
parts = {"Observed": sales, "Trend": res.trend, "Seasonal": res.seasonal, "Remainder": res.resid}
colors = ["#1D1D1F", "#007AFF", "#FF9500", "#8E8E93"]

# Strength of trend and seasonality (0 = none, 1 = all the variation)
f_trend = max(0, 1 - res.resid.var() / (res.trend + res.resid).var())
f_seas = max(0, 1 - res.resid.var() / (res.seasonal + res.resid).var())

fig, axes = plt.subplots(4, 1, figsize=(9, 7.5), sharex=True,
                         gridspec_kw=dict(height_ratios=[1.4, 1, 1, 1]))
bar = 2 * res.resid.abs().max()  # common scale bar, in billions of dollars
x0 = sales.index[0] - np.timedelta64(400, "D")

for ax, (name, s), c in zip(axes, parts.items(), colors):
    if name == "Remainder":
        ax.vlines(s.index, 0, s, color=c, lw=0.8)
        ax.axhline(0, color="#C7C7CC", lw=0.8)
    else:
        ax.plot(s.index, s, color=c, lw=2 if name == "Trend" else 1)
    ax.set_ylabel(name, rotation=0, ha="right", va="center", labelpad=14)
    # Scale bar: same height in billions in every panel
    mid = (s.max() + s.min()) / 2
    ax.plot([x0, x0], [mid - bar / 2, mid + bar / 2], color="#C7C7CC", lw=5, solid_capstyle="butt",
            clip_on=False)

axes[-1].set_xlabel("Year")
fig.align_ylabels(axes)
axes[0].set_xlim(x0 - np.timedelta64(200, "D"), sales.index[-1])
slump = res.trend.diff(12).idxmin().year                                  # steepest yearly fall
low = res.seasonal.groupby(res.seasonal.index.month_name()).mean().idxmin()  # weakest month
axes[0].set_title(f"Manufacturing sales: the {slump} slump, and a dip every {low}", pad=26)
axes[0].text(0, 1.04, f"STL, period 12, robust · n = 228 months (simulated) · strength: trend = "
             f"{f_trend:.2f}, seasonality = {f_seas:.2f} · grey bars = {bar:.1f} bn",
             transform=axes[0].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). STL decomposition. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/time-series/stl-decomposition/

@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}
}

更多时间序列图表