05. Posterior predictive: forecasting with uncertainty#

Notebook 04 showed that BayesianVECM.fit works: the model samples, the \(\beta\)-identification pin holds, and the posteriors recover the true parameters on synthetic data. But a model you can only fit is only half the job. The other half is forecasting: given a fitted posterior, what does the model say will happen next?

This notebook walks through BayesianVECM.sample_posterior_predictive(steps), the method that was still a NotImplementedError stub in notebook 04 and is now live.

Since this notebook. Forecasts now work for any rank and deterministic code, and accept future driver paths through exog_future (notebook 09). The bands here are equal-tailed intervals from percentiles, not highest-density intervals.

The core idea (uncertainty propagates through the recursion) is the headline teaching moment. At each step ahead we draw a fresh innovation \(\varepsilon_{T+h} \sim \mathcal{N}(0, \Sigma)\) for every posterior draw of \(\Sigma\). Those innovations compound: a step-1 shock shifts the level, which feeds into the error-correction term at step 2, and so on. The result is a forecast distribution that widens sensibly with the horizon rather than collapsing to a point estimate.

Setup: we use the same bivariate cointegrated DGP as notebook 04 (\(\beta = (1, -0.5)^{\top}\), \(\alpha = (-0.4, 0.2)^{\top}\)) but generate 100 observations instead of 300, hold out the last 20 as a test set, and ask the model to forecast those 20 steps. The fan chart at the end compares the posterior forecast distribution against the actuals.

from __future__ import annotations

import matplotlib.pyplot as plt
import numpy as np

from bayesian_vecm import BayesianVECM

np.set_printoptions(precision=3, suppress=True)
# ---------------------------------------------------------------------------
# Sampling configuration
# ---------------------------------------------------------------------------
# Set FAST_SAMPLING = True for quick execution (CI / first read-through).
# Set FAST_SAMPLING = False for publication-quality posteriors.
# ---------------------------------------------------------------------------
FAST_SAMPLING = True

if FAST_SAMPLING:
    DRAWS, TUNE, CHAINS = 200, 200, 2
else:
    DRAWS, TUNE, CHAINS = 1000, 1000, 4

print(f"Sampling config: draws={DRAWS}, tune={TUNE}, chains={CHAINS}")
if FAST_SAMPLING:
    print("(FAST_SAMPLING=True: posteriors are coarser; set to False for full quality)")
Sampling config: draws=200, tune=200, chains=2
(FAST_SAMPLING=True: posteriors are coarser; set to False for full quality)

1. The DGP and the train/test split#

Same DGP as notebook 04: a bivariate VECM with no short-run dynamics:

\[\Delta y_t = \alpha\,\beta^{\top} y_{t-1} + \varepsilon_t, \qquad \varepsilon_t \sim \mathcal{N}(0, \sigma^2 I_2),\]

with \(\beta = (1, -0.5)^{\top}\), \(\alpha = (-0.4, 0.2)^{\top}\), and \(\sigma = 0.5\).

We generate \(T = 100\) observations, fit on the first 80, and forecast the last 20. The 20 held-out points are the actuals we’ll overlay on the fan chart.

def make_cointegrated_series(
    n_obs: int = 100,
    alpha_true: tuple[float, float] = (-0.4, 0.2),
    beta_true: tuple[float, float] = (1.0, -0.5),
    sigma: float = 0.5,
    seed: int = 0,
) -> np.ndarray:
    rng = np.random.default_rng(seed=seed)
    a0, a1 = alpha_true
    b0, b1 = beta_true
    y = np.zeros((n_obs, 2))
    y[0] = rng.normal(size=2)
    for t in range(1, n_obs):
        ec = b0 * y[t - 1, 0] + b1 * y[t - 1, 1]
        y[t, 0] = y[t - 1, 0] + a0 * ec + rng.normal(scale=sigma)
        y[t, 1] = y[t - 1, 1] + a1 * ec + rng.normal(scale=sigma)
    return y


# Generate full series, then split
T_TOTAL = 100
T_TRAIN = 80
T_TEST = T_TOTAL - T_TRAIN  # 20 held-out steps

endog_full = make_cointegrated_series(n_obs=T_TOTAL, seed=0)
endog_train = endog_full[:T_TRAIN]
endog_test = endog_full[T_TRAIN:]

print(f"Full series shape : {endog_full.shape}")
print(f"Training set      : rows 0..{T_TRAIN - 1}  ({T_TRAIN} obs)")
print(f"Test set (actuals): rows {T_TRAIN}..{T_TOTAL - 1} ({T_TEST} obs)")
print()
print("Training set: last 3 rows (these seed the forecast recursion):")
print(endog_train[-3:])
Full series shape : (100, 2)
Training set      : rows 0..79  (80 obs)
Test set (actuals): rows 80..99 (20 obs)

Training set: last 3 rows (these seed the forecast recursion):
[[1.881 3.687]
 [2.017 3.641]
 [1.345 2.481]]

2. Fit the model on the training set#

Nothing new here compared to notebook 04: fit takes the training data and runs pm.sample. With only 80 observations and a bivariate model the sampler is fast; the posteriors won’t be as tight as with 300 obs but they’ll still recover the true parameters reasonably well.

We pass cores=1 to sidestep a multiprocessing issue on macOS.

model = BayesianVECM(k_ar_diff=1, coint_rank=1, deterministic="n")
model.fit(
    endog_train,
    draws=DRAWS,
    tune=TUNE,
    chains=CHAINS,
    random_seed=42,
    progressbar=False,
    cores=1,
)

print("Training complete.")
print(model.summary())
NUTS[nutpie]: [alpha, beta_free, Gamma, Sigma_chol]
Training complete.
               mean     sd eti89_lb eti89_ub  ess_bulk  ess_tail r_hat  \
alpha[0, 0]   -0.33  0.102    -0.49    -0.18       312       265  1.01   
alpha[1, 0]   0.143  0.101   -0.014      0.3       496       357  1.01   
beta[0, 0]        1      0        1        1       400       400   NaN   
beta[1, 0]   -0.466  0.053    -0.55    -0.39       385       251  1.00   
Gamma[0, 0]    0.02  0.124    -0.16     0.22       341       139  1.02   
Gamma[0, 1]    0.07  0.112    -0.11     0.26       496       319  1.01   
Gamma[1, 0]    -0.1  0.119    -0.29     0.09       436       267  1.00   
Gamma[1, 1]   0.104  0.116    -0.08      0.3      1040       374  1.02   
Sigma[0, 0]   0.246  0.041     0.19     0.32       574       285  1.01   
Sigma[0, 1]   0.032  0.028  -0.0072    0.078       597       304  1.00   
Sigma[1, 0]   0.032  0.028  -0.0072    0.078       597       304  1.00   
Sigma[1, 1]    0.26  0.043      0.2     0.33       701       203  1.01   

            mcse_mean  mcse_sd  
alpha[0, 0]    0.0058   0.0039  
alpha[1, 0]    0.0045   0.0032  
beta[0, 0]          0      NaN  
beta[1, 0]     0.0029   0.0024  
Gamma[0, 0]    0.0067   0.0046  
Gamma[0, 1]     0.005   0.0038  
Gamma[1, 0]    0.0056   0.0036  
Gamma[1, 1]    0.0036   0.0025  
Sigma[0, 0]    0.0018   0.0016  
Sigma[0, 1]    0.0012  0.00087  
Sigma[1, 0]    0.0012  0.00087  
Sigma[1, 1]    0.0015   0.0011  

3. Forecast with sample_posterior_predictive#

sample_posterior_predictive(steps) rolls the VECM recursion forward from the end of the training series:

\[ \Delta y_{T+h} = \alpha\,\beta^{\top} y_{T+h-1} + \Gamma_1\,\Delta y_{T+h-1} + \varepsilon_{T+h}, \qquad y_{T+h} = y_{T+h-1} + \Delta y_{T+h}, \]

for \(h = 1, \dots, \text{steps}\). The seed window (the last k_ar_diff + 1 = 2 rows of endog_train) provides the last level and the last lagged difference needed to start the recursion.

For each posterior draw, a fresh \(\varepsilon_{T+h}\) is drawn at every step from \(\mathcal{N}(0, \Sigma_{(d)})\). The result is a distribution over forecast paths, not a point estimate.

The return type is an xr.DataTree with a posterior_predictive child node holding:

  • y: forecast levels, shape (chain, draw, steps, K).

  • delta_y: forecast first differences, same shape.

FORECAST_STEPS = T_TEST  # 20: match the held-out window

pp = model.sample_posterior_predictive(steps=FORECAST_STEPS, random_seed=42)

# y_draws: shape (chain, draw, steps, K) -> reshape to (n_draws_total, steps, K)
y_draws = pp["posterior_predictive"]["y"].values
n_chains, n_draws, n_steps, n_vars = y_draws.shape
y_flat = y_draws.reshape(n_chains * n_draws, n_steps, n_vars)

print(f"Forecast output shape (chain, draw, steps, K): {y_draws.shape}")
print(f"Reshaped to (n_draws_total, steps, K)        : {y_flat.shape}")
print()
print("First 3 draws of y0 at step 1 (spot-check for non-zero spread):")
print(y_flat[:3, 0, 0])
Forecast output shape (chain, draw, steps, K): (2, 200, 20, 2)
Reshaped to (n_draws_total, steps, K)        : (400, 20, 2)

First 3 draws of y0 at step 1 (spot-check for non-zero spread):
[1.252 1.77  0.029]

4. Summarising the forecast distribution#

With draws of each future level we can compute any posterior summary we like. For the fan chart we want:

  • Posterior median: the central forecast path.

  • 80% interval (10th–90th percentile): a reasonably tight band.

  • 94% interval (3rd–97th percentile): a wider band showing the tails.

We use np.quantile over the draw axis.

# Summaries over the draw dimension (axis 0 after flattening).
y_median = np.median(y_flat, axis=0)  # (steps, K)
y_q10 = np.quantile(y_flat, 0.10, axis=0)  # 80% interval lower
y_q90 = np.quantile(y_flat, 0.90, axis=0)  # 80% interval upper
y_q03 = np.quantile(y_flat, 0.03, axis=0)  # 94% interval lower
y_q97 = np.quantile(y_flat, 0.97, axis=0)  # 94% interval upper

# x-axis indices
x_train = np.arange(T_TRAIN)
x_forecast = np.arange(T_TRAIN, T_TRAIN + FORECAST_STEPS)

print("Forecast summary for y0 (first variable):")
print(f"{'step':>4}  {'median':>7}  {'80% lo':>7}  {'80% hi':>7}  {'actual':>7}")
for h in range(FORECAST_STEPS):
    print(
        f"{h + 1:>4}  {y_median[h, 0]:>7.3f}  {y_q10[h, 0]:>7.3f}  "
        f"{y_q90[h, 0]:>7.3f}  {endog_test[h, 0]:>7.3f}"
    )
Forecast summary for y0 (first variable):
step   median   80% lo   80% hi   actual
   1    1.190    0.495    1.816    1.560
   2    1.098    0.270    1.910    1.142
   3    1.082    0.129    1.963    2.056
   4    1.153    0.114    2.038    1.734
   5    1.092    0.084    2.198    2.208
   6    1.159   -0.060    2.154    2.330
   7    1.150   -0.065    2.180    2.374
   8    1.209   -0.027    2.276    2.327
   9    1.156   -0.037    2.342    1.275
  10    1.070   -0.133    2.463    0.548
  11    1.169   -0.187    2.320    0.929
  12    1.092   -0.212    2.438    1.413
  13    1.059   -0.277    2.350    1.142
  14    1.097   -0.215    2.446    1.016
  15    1.010   -0.339    2.599    1.482
  16    1.104   -0.496    2.571    0.537
  17    1.031   -0.428    2.613    1.353
  18    1.117   -0.513    2.588    1.125
  19    1.041   -0.406    2.716    0.661
  20    1.008   -0.507    2.669    0.712

5. The fan chart#

A fan chart overlays the posterior forecast distribution against the held-out actuals. The shaded regions are the 80% and 94% interval bands; the solid orange line is the posterior median; the dashed black line is what actually happened.

A few things to look for:

  • Do the bands contain the actuals most of the time? For an 80% band you’d expect roughly 80% coverage: not perfect with 20 points, but gross failures are a red flag.

  • Do the bands widen with the horizon? They should: uncertainty compounds through the recursion. A flat band would indicate innovations are being ignored.

  • Does the median track the general direction? The error-correction mechanism pulls both series towards the cointegrating relation, so persistent deviations in the actuals should be loosely followed.

CONTEXT_ROWS = 20  # training points to show for visual context
x_context = x_train[-CONTEXT_ROWS:]
var_labels = ["$y_0$", "$y_1$"]

fig, axes = plt.subplots(2, 1, figsize=(10, 7), sharex=True)

for k, ax in enumerate(axes):
    ax.plot(
        x_context,
        endog_train[-CONTEXT_ROWS:, k],
        color="steelblue",
        linewidth=1.5,
        label="Training data",
    )
    ax.plot(
        x_forecast,
        endog_test[:, k],
        color="black",
        linewidth=1.5,
        linestyle="--",
        label="Held-out actuals",
    )
    ax.fill_between(
        x_forecast,
        y_q03[:, k],
        y_q97[:, k],
        color="orange",
        alpha=0.18,
        label="94% interval",
    )
    ax.fill_between(
        x_forecast,
        y_q10[:, k],
        y_q90[:, k],
        color="orange",
        alpha=0.35,
        label="80% interval",
    )
    ax.plot(
        x_forecast,
        y_median[:, k],
        color="darkorange",
        linewidth=2.0,
        label="Posterior median",
    )
    ax.axvline(T_TRAIN - 0.5, color="grey", linewidth=0.8, linestyle=":")
    ax.set_ylabel(var_labels[k], fontsize=12)
    ax.legend(loc="upper left", fontsize=9)
    ax.set_title(f"Variable {k}: {FORECAST_STEPS}-step forecast fan chart", fontsize=11)

axes[-1].set_xlabel("Time index", fontsize=11)
fig.suptitle(
    "BayesianVECM posterior predictive"
    f": train t=0..{T_TRAIN - 1}, forecast t={T_TRAIN}..{T_TOTAL - 1}",
    fontsize=12,
    y=1.01,
)
plt.tight_layout()
plt.show()
../_images/f522ffe1606dbea18dcc8cd66804790d84972b6dff187370d71fb950372f48aa.png

6. Uncertainty propagation: watching the bands widen#

The widening of the interval bands is the direct consequence of compounding innovations. Let’s measure the 80% band width at each step to make it concrete.

band_width = y_q90 - y_q10  # (steps, K)

print("80% interval band width by forecast step:")
print(f"{'step':>4}  {'y0 width':>10}  {'y1 width':>10}")
for h in range(FORECAST_STEPS):
    print(f"{h + 1:>4}  {band_width[h, 0]:>10.3f}  {band_width[h, 1]:>10.3f}")

print()
print("Width ratio (step 20 / step 1):")
for k in range(n_vars):
    ratio = band_width[-1, k] / band_width[0, k]
    print(f"  y{k}: {ratio:.2f}x wider at the horizon than at step 1")
80% interval band width by forecast step:
step    y0 width    y1 width
   1       1.321       1.325
   2       1.640       2.033
   3       1.834       2.357
   4       1.924       2.903
   5       2.114       3.200
   6       2.214       3.366
   7       2.245       3.643
   8       2.303       4.017
   9       2.379       4.234
  10       2.596       4.496
  11       2.507       4.542
  12       2.650       4.769
  13       2.627       4.822
  14       2.661       5.166
  15       2.938       5.409
  16       3.067       5.468
  17       3.041       5.568
  18       3.101       5.791
  19       3.122       5.802
  20       3.177       6.137

Width ratio (step 20 / step 1):
  y0: 2.40x wider at the horizon than at step 1
  y1: 4.63x wider at the horizon than at step 1

7. Coverage check#

With only 20 held-out points the coverage estimate is noisy, but it’s worth a quick sanity check. For an 80% band we’d expect roughly 16 of the 20 actuals inside it.

for k in range(n_vars):
    inside_80 = int(np.sum((endog_test[:, k] >= y_q10[:, k]) & (endog_test[:, k] <= y_q90[:, k])))
    inside_94 = int(np.sum((endog_test[:, k] >= y_q03[:, k]) & (endog_test[:, k] <= y_q97[:, k])))
    print(
        f"y{k}:  80% interval coverage = {inside_80}/{T_TEST} ({100 * inside_80 // T_TEST}%)  "
        f" 94% interval coverage = {inside_94}/{T_TEST} ({100 * inside_94 // T_TEST}%)"
    )
y0:  80% interval coverage = 15/20 (75%)   94% interval coverage = 20/20 (100%)
y1:  80% interval coverage = 20/20 (100%)   94% interval coverage = 20/20 (100%)

8. The error-correction term in the forecast#

One of the distinctive features of a VECM forecast (vs a plain VAR-in-differences) is that the error-correction term keeps pulling both series back towards the cointegrating relation. We can see this by computing \(\hat{\beta}^{\top} y_{T+h}\) along the posterior median path: it should stay close to zero rather than drifting.

This is what distinguishes VECM from a VAR-in-differences: a VAR-in-differences ignores the cointegrating relation entirely, so level forecasts can drift apart indefinitely. The VECM doesn’t: the error-correction mechanism keeps their long-run combination anchored.

# Posterior mean of beta[1, 0] (the free entry; beta[0, 0] = 1 always)
beta1_mean = float(model.idata_.posterior["beta"].values[:, :, 1, 0].mean())
print(f"Posterior mean beta[1, 0] = {beta1_mean:.4f}  (true = -0.5)")

ec_median_forecast = y_median[:, 0] + beta1_mean * y_median[:, 1]
ec_true_test = endog_test[:, 0] - 0.5 * endog_test[:, 1]
ec_true_train = endog_train[:, 0] - 0.5 * endog_train[:, 1]

fig, ax = plt.subplots(figsize=(10, 3.5))
ax.plot(
    x_train[-CONTEXT_ROWS:],
    ec_true_train[-CONTEXT_ROWS:],
    color="steelblue",
    label="Training  $\\hat{\\beta}^{\\top} y_t$",
)
ax.plot(x_forecast, ec_true_test, color="black", linestyle="--", label="Held-out actuals")
ax.plot(x_forecast, ec_median_forecast, color="darkorange", linewidth=2.0, label="Forecast median")
ax.axhline(0, color="grey", linewidth=0.8, linestyle=":")
ax.axvline(T_TRAIN - 0.5, color="grey", linewidth=0.8, linestyle=":")
ax.set_xlabel("Time index")
ax.set_ylabel("$\\hat{\\beta}^{\\top} y_t$")
ax.set_title("Error-correction term along the forecast path")
ax.legend(fontsize=9)
plt.tight_layout()
plt.show()

print(f"\nec_t in training       : mean={ec_true_train.mean():.3f}, std={ec_true_train.std():.3f}")
print(f"ec_t in held-out test  : mean={ec_true_test.mean():.3f}, std={ec_true_test.std():.3f}")
ec_fc_mean = ec_median_forecast.mean()
ec_fc_std = ec_median_forecast.std()
print(f"ec_t median forecast   : mean={ec_fc_mean:.3f}, std={ec_fc_std:.3f}")
Posterior mean beta[1, 0] = -0.4660  (true = -0.5)
../_images/d683c99a7f274c7d098a51c8cdaf36763901be51e0bc84682af912c0b4f3cf0d.png
ec_t in training       : mean=-0.144, std=0.617
ec_t in held-out test  : mean=0.016, std=0.696
ec_t median forecast   : mean=0.002, std=0.060

9. What this unlocks and what’s still to come#

Shipped this slice (feat/posterior-predictive):

The original target API is now complete end-to-end:

model = BayesianVECM(k_ar_diff=1, coint_rank=1, deterministic="n")
model.fit(endog_train)                                    # posterior
model.summary()                                           # tabular summary
pp = model.sample_posterior_predictive(steps=20)          # forecast distribution
y  = pp["posterior_predictive"]["y"].values               # (chain, draw, steps, K)

The forecasting loop is NumPy-only: fully vectorised over (chain x draw), single Python loop over steps, innovations drawn from the posterior Cholesky of \(\Sigma\) pre-computed once. Returns an xr.DataTree with posterior_predictive/y (levels) and posterior_predictive/delta_y (differences).

Still to do at this stage:

  • fit and sample_posterior_predictive still require coint_rank=1 and deterministic="n". The graph extension (higher ranks, deterministic terms) is the next estimator slice.

  • No Bayesian model averaging across ranks: that waits until the wider graph is in.

  • No diagnostics notebook: convergence checks and trace plots are worth their own walkthrough once we have more model variants to compare.