Environment

Python 3.14.6, NumPy 2.4.6, pandas 2.3.3, Prophet 1.3.0, statsmodels 0.14.6, Matplotlib 3.11.2.

Overview

This article introduces Chapter 9, “Decomposing and Forecasting Sales Changes,” of Marketing Science in Theory and Practice . Before attributing a sales increase to a marketing action, we examine long-term trends and seasonality. Following the book, we cover the limits of before-and-after comparisons, Prophet, state-space models, and implementation in Python.

In addition to point forecasts, we plot sales levels, slopes, seasonality, and forecast uncertainty. The code runs on simulated data.

Setup code (imports and display settings)
import logging
import platform
from importlib.metadata import version
from pathlib import Path
from pprint import pprint

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import matplotlib_fontja  # 日本語の描画用フォントを設定する。
import numpy as np
import pandas as pd
from IPython.display import Latex, SVG, display
from matplotlib.ticker import FuncFormatter
from scipy import stats
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.tsa.statespace.structural import UnobservedComponents

# この例は静的なSVGを使うため、任意のPlotly機能の通知を省く。
logging.getLogger("prophet.plot").setLevel(logging.CRITICAL)
logging.getLogger("cmdstanpy").setLevel(logging.WARNING)
from prophet import Prophet

print(f"実行環境: wa-src(3.14.6) / Python {platform.python_version()}")
for package in ["numpy", "scipy", "pandas", "matplotlib", "prophet",
                "statsmodels", "matplotlib-fontja"]:
    print(f"{package}: {version(package)}")


def sig3(value):
    """末尾の0も残して有効数字3桁で表示する。"""
    return f"{float(value):#.3g}"


np.set_printoptions(formatter={"float_kind": sig3})
pd.options.display.float_format = sig3
plt.rcParams.update({
    "figure.figsize": (10, 4), "font.size": 11,
    "axes.spines.top": False, "axes.spines.right": False,
    "axes.grid": True, "grid.alpha": 0.250,
    "svg.fonttype": "path", "svg.hashsalt": "blog09",
})
BLUE, ORANGE, GRAY = "#245b86", "#b85d28", "#767676"

# リポジトリ直下から実行する場合も、保存先をblog/09配下にそろえる。
base = Path("blog/09") if Path("blog/09/09_nb.ipynb").exists() else Path.cwd()
figure_dir = base / "09_nb_files"
figure_dir.mkdir(parents=True, exist_ok=True)


def save_svg(fig, name):
    """図をSVGで保存し、同じSVGを出力欄に埋め込む。"""
    for ax in fig.axes:
        ax.yaxis.set_major_formatter(FuncFormatter(lambda value, _: sig3(value)))
    fig.tight_layout()
    path = figure_dir / name
    fig.savefig(path, format="svg", bbox_inches="tight", metadata={"Date": None})
    display(SVG(filename=str(path)))
    plt.close(fig)


def date_axis(ax):
    ax.xaxis.set_major_locator(mdates.AutoDateLocator(minticks=4, maxticks=7))
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
実行環境: wa-src(3.14.6) / Python 3.14.6
numpy: 2.4.6
scipy: 1.18.1
pandas: 2.3.3
matplotlib: 3.11.2
prophet: 1.3.0
statsmodels: 0.14.6
matplotlib-fontja: 1.1.0

1. Why decompose sales?

Sales in a coupon week may be 18% above the previous week, but a 15% increase in the same period of the previous year suggests seasonality. Even the three-percentage-point difference cannot be treated directly as the action’s effect when prices and competition differ.

Decompose sales $y_t$ into level $\mu_t$, seasonality $s_t$, a component $x_t$ associated with actions or other factors, and noise $\varepsilon_t$. Subtracting the previous day’s equation shows what enters a before-and-after comparison.

$$ \begin{aligned} y_t&=\mu_t+s_t+x_t+\varepsilon_t,\\ y_{t-1}&=\mu_{t-1}+s_{t-1}+x_{t-1}+\varepsilon_{t-1},\\ \Delta y_t&=y_t-y_{t-1}\\ &=\Delta\mu_t+\Delta s_t+\Delta x_t+\Delta\varepsilon_t. \end{aligned} $$

A change in observed sales is also different from a change in the underlying sales level. Check the surrounding trend in a plot before interpreting a single day’s movement.

2. Decompose sales with Prophet

Prophet’s additive model combines trend $g(t)$, seasonality $s(t)$, and a component $h(t)$ for specified holidays and events. Seasonality is represented by $N$ pairs of waves with period $P$.

$$ \begin{aligned} y(t)&=g(t)+s(t)+h(t)+\varepsilon_t,\\ s(t)&=\sum_{n=1}^{N}\left[a_n\cos\left(\frac{2\pi nt}{P}\right) +b_n\sin\left(\frac{2\pi nt}{P}\right)\right],\\ h(t)&=\mathbf{z}(t)^\top\mathbf{b}_h. \end{aligned} $$

The vector $\mathbf{z}(t)$ indicates events, and $\mathbf{b}_h$ contains their coefficients. Weekly seasonality has $P=7$. The trend can be piecewise linear, with slope changes at changepoints. Prophet can work with missing dates without filling every gap and allows holiday and changepoint settings. Decomposition alone, however, does not establish a marketing action’s causal effect.

3. Estimate level and slope with state-space models

A local-level model separates observations from an underlying level. Observation noise $\varepsilon_t$ represents day-specific variation, while state noise $\eta_t$ changes the level in a way that persists. We assume the noises are independent over time and of each other.

$$ \begin{aligned} y_t&=\mu_t+\varepsilon_t,&\varepsilon_t&\sim\mathcal N(0,r),\\ \mu_t&=\mu_{t-1}+\eta_t,&\eta_t&\sim\mathcal N(0,q). \end{aligned} $$

A smaller signal-to-noise ratio $q/r$ generally gives a smoother estimated level. A local-linear-trend model adds slope $\nu_t$. With state vector $\mathbf{u}_t=(\mu_t,\nu_t)^\top$, matrix multiplication gives the following two equations.

$$ \begin{aligned} \mathbf{u}_t &=\begin{pmatrix}1&1\\0&1\end{pmatrix}\mathbf{u}_{t-1} +\begin{pmatrix}\eta_t\\\zeta_t\end{pmatrix}\\ &=\begin{pmatrix}\mu_{t-1}+\nu_{t-1}+\eta_t\\\nu_{t-1}+\zeta_t\end{pmatrix}. \end{aligned} $$

Follow the Kalman filter

In the local-level model, let yesterday’s estimated mean and variance be $a_{t-1}$ and $P_{t-1}$. First predict the mean $a_t^-$ and variance $P_t^-$ before observing today’s value. Then incorporate the prediction error $v_t$ with weight $K_t$.

$$ \begin{aligned} a_t^-&=a_{t-1},&P_t^-&=P_{t-1}+q,\\ v_t&=y_t-a_t^-,&K_t&=\frac{P_t^-}{P_t^-+r},\\ a_t&=a_t^-+K_tv_t=(1-K_t)a_t^-+K_ty_t,\\ P_t&=(1-K_t)P_t^-=\frac{rP_t^-}{P_t^-+r}. \end{aligned} $$

Larger observation-noise variance $r$ gives less weight to the observation. Filtering uses observations available through the current day; smoothing uses the full period to revise estimates of past states. Smoothed estimates must not be evaluated as forecasts made at those past dates.

4. Implement the models in Python

4.1 Forecast 365 days ahead with Prophet

As in the book, generate daily data for 2022–2024. Add a ¥500 daily trend, annual and weekly seasonality, and noise with standard deviation ¥80,000. These are not observations from the opening coupon example and contain no holiday or treatment effect.

# 元ノートブックと同じ乱数系列と生成条件を使う。
dates = pd.date_range("2022-01-01", "2024-12-31", freq="D")
t = np.arange(len(dates))
random_prophet = np.random.RandomState(42)
trend = 1_000_000 + 500 * t
yearly = 300_000 * np.sin(2 * np.pi * t / (1461 / 4) - np.pi / 2)
weekly = 100_000 * np.sin(2 * np.pi * t / 7)
noise = random_prophet.normal(0, 80_000, len(t))
sales = np.maximum(trend + yearly + weekly + noise, 0).astype(int)
data = pd.DataFrame({"ds": dates, "y": sales})
print(data.head().to_string(index=False))

fig, ax = plt.subplots()
ax.plot(dates, sales / 10_000, color=GRAY, lw=0.700, label="模擬売上")
ax.plot(dates, trend / 10_000, color=BLUE, lw=2, label="生成時のトレンド")
ax.set(title="図1 季節性とノイズを含む日次売上", ylabel="売上(万円)")
ax.legend(loc="upper left")
date_axis(ax)
save_svg(fig, "01_sales.svg")
        ds      y
2022-01-01 739737
2022-01-02 767666
2022-01-03 850485
2022-01-04 867130
2022-01-05 640589


/var/folders/3y/fmw40k0x78xblvb3gkcyvy1h0000gn/T/ipykernel_97239/1775162875.py:54: UserWarning: AutoDateLocator was unable to pick an appropriate interval for this date range. It may be necessary to add an interval value to the AutoDateLocator's intervald dictionary. Defaulting to 6.
  fig.tight_layout()
/var/folders/3y/fmw40k0x78xblvb3gkcyvy1h0000gn/T/ipykernel_97239/1775162875.py:56: UserWarning: AutoDateLocator was unable to pick an appropriate interval for this date range. It may be necessary to add an interval value to the AutoDateLocator's intervald dictionary. Defaulting to 6.
  fig.savefig(path, format="svg", bbox_inches="tight", metadata={"Date": None})

The input columns are date ds and sales y. Hold out the 92 days from October through December 2024. Fit one model for validation and a separate model using the full period to forecast 2025. Add Japanese holidays to illustrate the book’s configuration.

def make_prophet():
    model = Prophet(
        yearly_seasonality=True,
        weekly_seasonality=True,
        daily_seasonality=False,
        changepoint_prior_scale=0.0500,
        seasonality_prior_scale=10,
        holidays_prior_scale=10,
        interval_width=0.800,
    )
    model.add_country_holidays(country_name="JP")
    return model


train = data.loc[data["ds"] < "2024-10-01"].copy()
test = data.loc[data["ds"] >= "2024-10-01"].copy()
evaluation_model = make_prophet().fit(train, seed=42)
final_model = make_prophet().fit(data, seed=42)

# 予測区間のシミュレーションにも乱数シードを指定する。
np.random.seed(42)
future = final_model.make_future_dataframe(periods=365, freq="D")
forecast = final_model.predict(future)
future_forecast = forecast.loc[forecast["ds"] > dates[-1]].copy()
print(f"学習: {len(train)}日 / 検証: {len(test)}日 / 将来予測: {len(future_forecast)}日")

fig, axes = plt.subplots(2, 1, figsize=(10, 7))
for ax, start in zip(axes, ["2022-01-01", "2024-09-01"]):
    observed = data.loc[data["ds"] >= start]
    ax.plot(observed["ds"], observed["y"] / 10_000,
            color=GRAY, lw=0.800, label="模擬売上")
    ax.plot(future_forecast["ds"], future_forecast["yhat"] / 10_000,
            color=BLUE, lw=1.20, label="将来予測")
    ax.fill_between(future_forecast["ds"],
                    future_forecast["yhat_lower"] / 10_000,
                    future_forecast["yhat_upper"] / 10_000,
                    color=BLUE, alpha=0.200, label="80%予測区間")
    ax.axvline(pd.Timestamp("2025-01-01"), color=ORANGE, ls="--")
    ax.set_ylabel("売上(万円)")
    date_axis(ax)
axes[0].set_title("図2 Prophetによる365日先の予測(下段は拡大)")
axes[0].legend(ncol=3, loc="upper left")
save_svg(fig, "02_prophet_forecast.svg")
02:07:43 - cmdstanpy - INFO - Chain [1] start processing


02:07:44 - cmdstanpy - INFO - Chain [1] done processing


02:07:45 - cmdstanpy - INFO - Chain [1] start processing


02:07:45 - cmdstanpy - INFO - Chain [1] done processing


学習: 1004日 / 検証: 92日 / 将来予測: 365日
# 成分の図は全期間で学習したモデルの結果であり、精度検証とは分ける。
fig, axes = plt.subplots(4, 1, figsize=(10, 10))
axes[0].plot(forecast["ds"], forecast["trend"] / 10_000, color=BLUE)
axes[0].set_title("図3 Prophetの成分分解:トレンド")
axes[1].plot(forecast["ds"], forecast["holidays"] / 10_000, color=ORANGE)
axes[1].set_title("祝日成分(生成データには祝日効果なし)")
for ax in axes[:2]:
    date_axis(ax)

week = forecast.loc[forecast["ds"].between("2024-01-01", "2024-01-07")]
axes[2].plot(np.arange(7), week["weekly"] / 10_000, "o-", color=BLUE)
axes[2].set_xticks(np.arange(7), list("月火水木金土日"))
axes[2].set_title("週次季節性")
year = forecast.loc[forecast["ds"].between("2024-01-01", "2024-12-31")]
axes[3].plot(year["ds"], year["yearly"] / 10_000, color=BLUE)
axes[3].xaxis.set_major_locator(mdates.MonthLocator(interval=2))
axes[3].xaxis.set_major_formatter(mdates.DateFormatter("%m月"))
axes[3].set_title("年次季節性")
for ax in axes:
    ax.set_ylabel("成分(万円)")
save_svg(fig, "03_prophet_components.svg")

Figure 3 shows an upward trend and higher seasonal values in summer. Nonzero holiday estimates do not demonstrate real holiday effects because none were included when generating the data.

Evaluate accuracy on the 92 held-out days. From errors $e_i=y_i-\hat y_i$, calculate RMSE and MAPE, and check the actual coverage of the 80% prediction intervals. MAPE is undefined when sales are zero, so verify that sales are positive in this example.

np.random.seed(42)
validation = evaluation_model.predict(test[["ds"]])
actual = test["y"].to_numpy()
estimate = validation["yhat"].to_numpy()
error = actual - estimate
assert np.all(actual > 0)
rmse = np.sqrt(np.mean(error ** 2))
mape = 100 * np.mean(np.abs(error) / actual)
covered = ((actual >= validation["yhat_lower"].to_numpy())
           & (actual <= validation["yhat_upper"].to_numpy()))
coverage = 100 * covered.mean()

# 重要な式は \( ... \) のLaTeXとして出力欄に表示する。
display(Latex(
    r"\(\displaystyle \begin{aligned}"
    r"\mathrm{RMSE}&=\sqrt{\frac{1}{n}\sum_{i=1}^{n}e_i^2},\\"
    r"\mathrm{MAPE}&=\frac{100}{n}\sum_{i=1}^{n}\frac{|e_i|}{y_i}"
    r"\end{aligned}\)"
))
pprint({"RMSE(円)": sig3(rmse), "MAPE(%)": sig3(mape),
        "80%予測区間の被覆率(%)": sig3(coverage)}, sort_dicts=False)

fig, axes = plt.subplots(2, 1, figsize=(10, 6), sharex=True)
axes[0].plot(test["ds"], actual / 10_000, color=GRAY, label="実績")
axes[0].plot(test["ds"], estimate / 10_000, color=BLUE, label="検証用予測")
axes[0].fill_between(test["ds"], validation["yhat_lower"] / 10_000,
                     validation["yhat_upper"] / 10_000,
                     color=BLUE, alpha=0.200, label="80%予測区間")
axes[0].set(title="図4 未学習の92日間で予測を検証する", ylabel="売上(万円)")
axes[0].legend(ncol=3, loc="upper left")
axes[1].plot(test["ds"], error / 10_000, color=ORANGE)
axes[1].axhline(0, color=GRAY, ls="--")
axes[1].set_ylabel("実績 − 予測(万円)")
date_axis(axes[1])
save_svg(fig, "04_prophet_validation.svg")

$$\displaystyle \begin{aligned}\mathrm{RMSE}&=\sqrt{\frac{1}{n}\sum_{i=1}^{n}e_i^2},\\\mathrm{MAPE}&=\frac{100}{n}\sum_{i=1}^{n}\frac{|e_i|}{y_i}\end{aligned}$$

{'RMSE(円)': '7.31e+04', 'MAPE(%)': '4.34', '80%予測区間の被覆率(%)': '82.6'}

4.2 Define and fit a state-space model

Next use another simulated dataset from the book, with changing level and slope, weekly seasonality, and observation noise. It differs from the Prophet dataset and therefore cannot support an accuracy comparison between the two methods. Weekly seasonality is updated by negating the sum of the previous six days and adding noise.

rng = np.random.default_rng(13)
level = np.empty(len(dates))
slope = np.empty(len(dates))
level[0], slope[0] = 1_000_000, 450
for i in range(1, len(dates)):
    slope[i] = slope[i - 1] + rng.normal(0, 15)
    level[i] = level[i - 1] + slope[i - 1] + rng.normal(0, 3_000)

seasonal = np.empty(len(dates))
seasonal[:7] = [14_000, 19_000, 6_000, -5_000, -9_000, -7_000, -18_000]
for i in range(7, len(dates)):
    seasonal[i] = -seasonal[i - 6:i].sum() + rng.normal(0, 1_500)

noise = rng.normal(0, 20_000, len(dates))
ssm_sales = np.maximum(level + seasonal + noise, 0).astype(int)
ts = pd.Series(ssm_sales, index=dates, name="sales").asfreq("D")

# 初期状態はexact diffuse法で扱い、ノイズ分散を最尤推定する。
model = UnobservedComponents(
    ts, level="local linear trend", seasonal=7, use_exact_diffuse=True,
)
result = model.fit(method="powell", disp=False)
assert result.mle_retvals["converged"], "最適化の収束を確認すること。"
pprint({name: sig3(value) for name, value in result.params.items()}, sort_dicts=False)
{'sigma2.irregular': '4.07e+08',
 'sigma2.level': '1.05e+07',
 'sigma2.trend': '149.',
 'sigma2.seasonal': '9.40e+05'}

The parameter sigma2.irregular is observation-noise variance; level, trend, and seasonal are the respective state-noise variances. A larger value does not mean that a component contributed more to sales.

4.3 Plot components and prediction errors

Extract level, slope, and seasonality smoothed using the full observation period. Following the book, exclude the first 14 days from plots and summaries of variation. Residuals are sales minus level and seasonality. Because the data are simulated, we can compare with the states used to generate them.

decomposition = pd.DataFrame({
    "水準": result.level.smoothed,
    "傾き": result.trend.smoothed,
    "季節性": result.seasonal.smoothed,
}, index=dates)
decomposition["残差"] = ts - decomposition["水準"] - decomposition["季節性"]
visible = decomposition.iloc[14:]

fig, axes = plt.subplots(4, 1, figsize=(10, 10))
for ax, component, truth, unit, divisor in zip(
    axes, ["水準", "傾き", "季節性", "残差"],
    [level, slope, seasonal, None],
    ["万円", "円/日", "万円", "万円"], [10_000, 1, 10_000, 10_000],
):
    # 週周期が読めるよう、季節性だけ最後の8週間を拡大する。
    start = len(dates) - 56 if component == "季節性" else 14
    if component == "水準":
        ax.plot(dates[start:], ts.iloc[start:] / divisor,
                color=GRAY, alpha=0.450, lw=0.700, label="観測値")
    if truth is not None:
        ax.plot(dates[start:], truth[start:] / divisor,
                color=ORANGE, ls="--", lw=1.20, label="生成時の状態")
    ax.plot(dates[start:], decomposition[component].iloc[start:] / divisor,
            color=BLUE, lw=1.20, label="平滑化推定" if truth is not None else "残差")
    ax.set(title=component + ("(末尾56日)" if component == "季節性" else ""),
           ylabel=unit)
    ax.legend(loc="upper left", ncol=3)
    date_axis(ax)
axes[0].set_title("図5 状態空間モデルの成分分解:水準")
save_svg(fig, "05_ssm_components.svg")
/var/folders/3y/fmw40k0x78xblvb3gkcyvy1h0000gn/T/ipykernel_97239/1775162875.py:54: UserWarning: AutoDateLocator was unable to pick an appropriate interval for this date range. It may be necessary to add an interval value to the AutoDateLocator's intervald dictionary. Defaulting to 6.
  fig.tight_layout()
/var/folders/3y/fmw40k0x78xblvb3gkcyvy1h0000gn/T/ipykernel_97239/1775162875.py:56: UserWarning: AutoDateLocator was unable to pick an appropriate interval for this date range. It may be necessary to add an interval value to the AutoDateLocator's intervald dictionary. Defaulting to 6.
  fig.savefig(path, format="svg", bbox_inches="tight", metadata={"Date": None})

Distinguish an increase in level from its rate of increase, the slope. Dividing each component’s standard deviation by the standard deviation of observations compares their variation. These ratios are not contribution percentages that sum to 100%.

component_sd = visible[["水準", "季節性", "残差"]].std()
sd_ratio = 100 * component_sd / ts.iloc[14:].std()
print(pd.DataFrame({"標準偏差(円)": component_sd,
                    "観測値との標準偏差比(%)": sd_ratio}).to_string())

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].bar(component_sd.index, component_sd / 10_000,
            color=[BLUE, ORANGE, GRAY])
axes[0].set(title="図6 成分の変動幅", ylabel="標準偏差(万円)")
axes[1].bar(sd_ratio.index, sd_ratio, color=[BLUE, ORANGE, GRAY])
axes[1].set(title="標準偏差の比(寄与率ではない)", ylabel="比(%)")
save_svg(fig, "06_component_variation.svg")
     標準偏差(円)  観測値との標準偏差比(%)
水準  2.31e+05           99.4
季節性 1.65e+04           7.10
残差  1.89e+04           8.16

For model diagnostics, use standardized one-step-ahead prediction errors, which differ from smoothed residuals. Inspect a histogram and QQ plot for the distribution, and an autocorrelation plot and Ljung–Box tests for dependence over time. Finding no problem does not guarantee future forecast accuracy.

display(Latex(
    r"\(\displaystyle e_t^{\mathrm{std}}="
    r"\frac{y_t-\hat y_{t\mid t-1}}{\sqrt{F_t}},\quad "
    r"F_t=\mathrm{Var}(y_t\mid y_1,\ldots,y_{t-1})\)"
))
diagnostic_start = max(result.loglikelihood_burn,
                       result.filter_results.nobs_diffuse)
standardized = result.filter_results.standardized_forecasts_error[0, diagnostic_start:]
standardized = standardized[np.isfinite(standardized)]

fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].hist(standardized, bins=30, density=True,
             color=BLUE, alpha=0.650, label="予測誤差")
grid = np.linspace(-4, 4, 200)
axes[0].plot(grid, stats.norm.pdf(grid), color=ORANGE, label="標準正規分布")
axes[0].set(title="図7 標準化予測誤差", xlabel="誤差", ylabel="密度")
axes[0].legend(fontsize=9)
stats.probplot(standardized, dist="norm", plot=axes[1])
axes[1].set(title="QQプロット", xlabel="正規分布の理論分位点", ylabel="誤差の分位点")
plot_acf(standardized, lags=20, zero=False, ax=axes[2], alpha=0.0500)
axes[2].set(title="自己相関(帯は95%区間)", xlabel="時点差(日)", ylabel="自己相関")
for ax in axes[:2]:
    ax.xaxis.set_major_formatter(FuncFormatter(lambda value, _: sig3(value)))
save_svg(fig, "07_prediction_error_diagnostics.svg")

# statsmodelsと同じ初期期間の扱いでLjung–Box検定を行う。
lb = result.test_serial_correlation(method="ljungbox", lags=[7, 14, 20])[0]
pprint({f"{lag}日差までのp値": sig3(value)
        for lag, value in zip([7, 14, 20], lb[1])}, sort_dicts=False)

$$\displaystyle e_t^{\mathrm{std}}=\frac{y_t-\hat y_{t\mid t-1}}{\sqrt{F_t}},\quad F_t=\mathrm{Var}(y_t\mid y_1,\ldots,y_{t-1})$$

{'7日差までのp値': '0.875', '14日差までのp値': '0.888', '20日差までのp値': '0.975'}

4.4 Make longer forecasts with prediction intervals

Holding the fitted parameters fixed, observation forecast variance equals the state forecast covariance $\mathbf{P}$ mapped through observation matrix $\mathbf{Z}$, plus observation-noise variance $r$. Uncertainty in level and slope accumulates, so intervals widen farther into the future.

display(Latex(
    r"\(\displaystyle \mathrm{Var}(y_{T+h}\mid y_1,\ldots,y_T)="
    r"\mathbf{Z}\mathbf{P}_{T+h\mid T}\mathbf{Z}^{\top}+r\)"
))
prediction = result.get_forecast(steps=365)
mean = prediction.predicted_mean
interval = prediction.conf_int(alpha=0.200)
width = interval.iloc[:, 1] - interval.iloc[:, 0]

fig, axes = plt.subplots(2, 1, figsize=(10, 7))
axes[0].plot(ts.index[-365:], ts.iloc[-365:] / 10_000,
             color=GRAY, lw=0.800, label="模擬売上")
axes[0].plot(mean.index, mean / 10_000, color=BLUE, label="将来予測")
axes[0].fill_between(mean.index, interval.iloc[:, 0] / 10_000,
                     interval.iloc[:, 1] / 10_000,
                     color=BLUE, alpha=0.200, label="80%予測区間")
axes[0].axvline(mean.index[0], color=ORANGE, ls="--")
axes[0].set(title="図8 状態空間モデルによる365日先の予測", ylabel="売上(万円)")
axes[0].legend(loc="upper left", ncol=3)
date_axis(axes[0])
axes[1].plot(np.arange(1, 366), width / 10_000, color=BLUE)
axes[1].set(xlabel="予測する日数", ylabel="区間の全幅(万円)",
            title="予測期間と区間幅の関係")
save_svg(fig, "08_ssm_forecast.svg")

pprint({f"{h}日先の区間全幅(万円)": sig3(width.iloc[h - 1] / 10_000)
        for h in [30, 90, 180, 365]}, sort_dicts=False)

$$\displaystyle \mathrm{Var}(y_{T+h}\mid y_1,\ldots,y_T)=\mathbf{Z}\mathbf{P}_{T+h\mid T}\mathbf{Z}^{\top}+r$$

{'30日先の区間全幅(万円)': '7.56',
 '90日先の区間全幅(万円)': '11.1',
 '180日先の区間全幅(万円)': '16.4',
 '365日先の区間全幅(万円)': '28.5'}

These intervals depend on the model assumptions and fitted parameters. They do not cover every possible future structural change. Inventory and staffing decisions should consider higher and lower outcomes as well as point forecasts.

Conclusion

This article introduced sales decomposition, forecasting, and latent-state estimation with Prophet and state-space models.

Separate seasonality from level changes, then examine held-out forecast errors and prediction intervals. Assessing a marketing action’s effect still requires a separate comparison with what would have happened without the action.

Marketing Science in Theory and Practice explains changepoints, matrix representations of state-space models, the Kalman filter, and interpretation in more detail. The full chapter code is available on the support page .