08. Output methods: fitted values, residuals, VAR representation, and diagnostic tests#

This notebook walks through the post-fit output methods shipped in feat/output-methods:

Method / property

What it returns

model.fittedvalues

Posterior fitted ΔY, shape (chain, draw, T_eff, K)

model.resid

Posterior residuals ΔY − fitted, same shape

model.var_rep

Levels VAR(p) coefficient matrices A₁..Aₚ

model.test_normality()

Jarque-Bera normality test per variable

model.test_whiteness(lags)

Ljung-Box whiteness test per variable

All five operate on a fitted model: no extra data required.

Why do these matter for a Bayesian VECM?

In any time-series model the residuals are the part of the data the model could not explain. If they look like white-noise Normal draws you have captured all the systematic dynamics: the model is well specified. If they show autocorrelation or fat tails, something is missing (more lags, a structural break, stochastic volatility, etc.). Classical diagnostics (test_normality, test_whiteness) give you a quick, familiar sanity check before trusting the posterior for forecasting or impulse-response analysis.

The VAR representation (var_rep) turns the VECM parameterisation back into the equivalent levels VAR, which some practitioners find easier to interpret and which underpins the IRF computation.

# ---------------------------------------------------------------------------
# Sampling config: set FAST_SAMPLING = False for publication-quality results
# ---------------------------------------------------------------------------
FAST_SAMPLING = True

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

import arviz as az
import matplotlib.pyplot as plt
import numpy as np

from bayesian_vecm import BayesianVECM

warnings.filterwarnings("ignore", category=FutureWarning)
rng = np.random.default_rng(seed=42)

1 Synthetic cointegrated data#

We generate the same bivariate DGP used in earlier notebooks: a cointegrated system with the long-run relation Y₁ = 0.5 · Y₂ and meaningful short-run dynamics (Γ ≠ 0) so that the residuals have something interesting to diagnose.

T = 120
alpha_true = np.array([-0.4, 0.2])  # error-correction loadings
beta_true = np.array([1.0, -0.5])  # cointegrating vector (normalised)
gamma_true = np.array(
    [
        [0.3, 0.1],  # short-run dynamics (Gamma_1)
        [0.0, 0.2],
    ]
)
sigma_chol = np.array([[0.5, 0.0], [0.2, 0.4]])

y = np.zeros((T, 2))
y[0] = rng.normal(size=2)
y[1] = y[0] + rng.normal(size=2) * 0.5

for t in range(2, T):
    ec = beta_true @ y[t - 1]
    dy_lag1 = y[t - 1] - y[t - 2]
    mu = alpha_true * ec + gamma_true @ dy_lag1
    eps = sigma_chol @ rng.normal(size=2)
    y[t] = y[t - 1] + mu + eps

fig, axes = plt.subplots(1, 2, figsize=(12, 3))
for i, (ax, name) in enumerate(zip(axes, ["Y₁", "Y₂"], strict=True)):
    ax.plot(y[:, i], lw=1)
    ax.set_title(name)
    ax.set_xlabel("t")
plt.suptitle("Synthetic cointegrated series", y=1.02)
plt.tight_layout()
plt.show()

print(f"Shape: {y.shape}  |  Cointegrating relation mean: {(y[:, 0] - 0.5 * y[:, 1]).mean():.3f}")
../_images/7df0fee3d3e65738842a7049218c26a2d634e660ac3defeaa42895ad7f7b68d7.png
Shape: (120, 2)  |  Cointegrating relation mean: -0.027

2 Fit the model#

model = BayesianVECM(k_ar_diff=1, coint_rank=1, deterministic="n")
model.fit(
    y,
    draws=DRAWS,
    tune=TUNE,
    chains=CHAINS,
    cores=1,
    target_accept=0.9,
    progressbar=True,
    random_seed=42,
)
print(model.summary())
NUTS[nutpie]: [alpha, beta_free, Gamma, Sigma_chol]

               mean     sd eti89_lb eti89_ub  ess_bulk  ess_tail r_hat  \
alpha[0, 0]   -0.44  0.099     -0.6    -0.28       290       188  1.01   
alpha[1, 0]    0.17  0.093    0.017     0.33       325       268  1.00   
beta[0, 0]        1      0        1        1       400       400   NaN   
beta[1, 0]   -0.495   0.02    -0.53    -0.46       492       321  1.00   
Gamma[0, 0]    0.25   0.11    0.075     0.41       168       214  1.01   
Gamma[0, 1]    0.14   0.11   -0.033     0.32       166       208  1.01   
Gamma[1, 0]   -0.08  0.101    -0.23    0.091       201       234  1.00   
Gamma[1, 1]    0.23    0.1    0.077     0.39       174       193  1.00   
Sigma[0, 0]   0.234  0.033     0.19     0.29       333       357  1.01   
Sigma[0, 1]   0.126  0.024    0.092     0.17       265       314  1.00   
Sigma[1, 0]   0.126  0.024    0.092     0.17       265       314  1.00   
Sigma[1, 1]    0.19  0.025     0.15     0.23       298       268  1.00   

            mcse_mean  mcse_sd  
alpha[0, 0]    0.0058   0.0042  
alpha[1, 0]    0.0052   0.0037  
beta[0, 0]          0      NaN  
beta[1, 0]    0.00091  0.00066  
Gamma[0, 0]    0.0083   0.0057  
Gamma[0, 1]    0.0086   0.0066  
Gamma[1, 0]    0.0071   0.0049  
Gamma[1, 1]    0.0076   0.0054  
Sigma[0, 0]    0.0018   0.0015  
Sigma[0, 1]    0.0015   0.0011  
Sigma[1, 0]    0.0015   0.0011  
Sigma[1, 1]    0.0015   0.0012  

3 Fitted values#

model.fittedvalues returns the posterior distribution of the in-sample fitted first-differences:

\[\hat{\Delta y}_t = \alpha \beta^\top y_{t-1} + \Gamma \Delta x_t\]

Shape: (chain, draw, T_eff, K) where T_eff = T − k − 1 = 118.

Because we get a full posterior distribution over fitted values, we can plot credible bands rather than just a point estimate. The posterior mean is the best point summary; the 80 % HDI shows how much uncertainty the model has about the in-sample fit.

fv = model.fittedvalues
print("fittedvalues shape:", fv.shape)
print("dims:", fv.dims)
fittedvalues shape: (2, 200, 118, 2)
dims: ('chain', 'draw', 'time', 'variable')
# Posterior mean and 80 % HDI of fitted delta-y
fv_mean = fv.mean(("chain", "draw")).values  # (T_eff, K)
fv_hdi = az.hdi(fv, prob=0.80, dim=["chain", "draw"])  # DataArray (time, variable, ci_bound)

# Actual delta-y from idata.constant_data (aligned to T_eff)
dy_actual = model.idata_.constant_data["delta_y"].values  # (T_eff, K)
t_eff = dy_actual.shape[0]
time_idx = np.arange(t_eff)

fig, axes = plt.subplots(2, 1, figsize=(12, 6), sharex=True)
var_labels = ["ΔY₁", "ΔY₂"]

for k, ax in enumerate(axes):
    lo = fv_hdi.sel(ci_bound="lower").values[:, k]
    hi = fv_hdi.sel(ci_bound="upper").values[:, k]
    ax.fill_between(time_idx, lo, hi, alpha=0.35, label="80 % HDI fitted")
    ax.plot(time_idx, fv_mean[:, k], lw=1.5, label="Posterior mean fitted")
    ax.plot(time_idx, dy_actual[:, k], lw=1, ls="--", color="black", alpha=0.7, label="Actual")
    ax.set_ylabel(var_labels[k])
    ax.legend(loc="upper right", fontsize=8)

axes[-1].set_xlabel("t (T_eff index)")
plt.suptitle("Fitted values vs actuals (first differences)", y=1.01)
plt.tight_layout()
plt.show()
../_images/d37785f6186778b04306b9581c18be8957d3d95171f8fd01fa29a148f8731847.png

4 Residuals#

model.resid is the posterior distribution of \(\hat{\varepsilon}_t = \Delta y_t - \hat{\Delta y}_t\), identical shape to fittedvalues.

What we expect from well-specified residuals:

  • Zero mean

  • No systematic trend or seasonality

  • Roughly symmetric (normality)

  • No autocorrelation (white noise)

We plot the posterior-mean residuals (the single best-guess residual series), which is what the classical diagnostic tests operate on.

resid = model.resid
resid_mean = resid.mean(("chain", "draw")).values  # (T_eff, K)

fig, axes = plt.subplots(2, 2, figsize=(13, 6))

for k in range(2):
    r = resid_mean[:, k]

    # Time series
    axes[k, 0].plot(time_idx, r, lw=1)
    axes[k, 0].axhline(0, color="red", lw=0.8, ls="--")
    axes[k, 0].set_title(f"Residuals: {var_labels[k]}")
    axes[k, 0].set_xlabel("t")

    # Histogram
    axes[k, 1].hist(r, bins=20, edgecolor="white")
    axes[k, 1].set_title(f"Distribution: {var_labels[k]}")
    axes[k, 1].set_xlabel("residual")

plt.suptitle("Posterior-mean residuals", y=1.01)
plt.tight_layout()
plt.show()

# Quick sanity check: delta_y = fitted + resid for every draw
recon = (model.fittedvalues + model.resid).mean(("chain", "draw")).values
max_err = np.abs(recon - dy_actual).max()
print(f"Max reconstruction error (fitted + resid vs delta_y): {max_err:.2e}")
../_images/c635110ff0f4e3eb3e672aec95c757d208ac144086c3097cc1807577a8df2774.png
Max reconstruction error (fitted + resid vs delta_y): 1.04e-14

The reconstruction error is machine-precision zero: fittedvalues + resid exactly recovers delta_y for every draw.

5 VAR representation#

Every VECM has an equivalent levels VAR(p) with \(p = k_{\text{ar\_diff}} + 1\). The standard conversion is:

\[A_1 = I_K + \alpha\beta^\top + \Gamma_1, \quad A_j = \Gamma_j - \Gamma_{j-1} \; (j=2,\dots,k), \quad A_{k+1} = -\Gamma_k\]

model.var_rep returns these matrices as a DataArray of shape (chain, draw, lag, response_variable, shock_variable) where lag runs 1..p.

For \(k=1\) we get \(p=2\) matrices: \(A_1\) and \(A_2 = -\Gamma_1\).

Why is this useful? The eigenvalues of the companion matrix built from \(A_1..A_p\) determine whether the VAR is stationary in levels (all roots inside the unit circle) or I(1)/cointegrated (one or more roots on the circle). It also underpins IRF computation: model.irf() uses this conversion internally.

vr = model.var_rep
print("var_rep shape:", vr.shape)
print("lag coord:", vr.coords["lag"].values)

# Posterior mean of A_1 and A_2
vr_mean = vr.mean(("chain", "draw")).values  # (p, K, K)
for j in range(vr_mean.shape[0]):
    print(f"\nPosterior mean A_{j + 1}:")
    print(np.round(vr_mean[j], 3))
var_rep shape: (2, 200, 2, 2, 2)
lag coord: [1 2]

Posterior mean A_1:
[[0.804 0.362]
 [0.089 1.152]]

Posterior mean A_2:
[[-0.249 -0.142]
 [ 0.076 -0.234]]
# Posterior distribution of A_1 diagonal (own-lag coefficients)
fig, axes = plt.subplots(1, 2, figsize=(11, 3.5))

for k, ax in enumerate(axes):
    a1_kk = vr.sel(lag=1).values[:, :, k, k].ravel()  # (chain*draw,)
    ax.hist(a1_kk, bins=30, edgecolor="white")
    ax.axvline(vr_mean[0, k, k], color="red", lw=1.5, ls="--", label=f"mean={vr_mean[0, k, k]:.3f}")
    ax.set_title(f"A₁[{k},{k}]: own-lag coeff for {var_labels[k]}")
    ax.set_xlabel("coefficient value")
    ax.legend(fontsize=9)

plt.suptitle("Posterior of A₁ diagonal entries", y=1.01)
plt.tight_layout()
plt.show()
../_images/ddf9dedd9f6f500eae168f68ab676c9afdd706e208c63e025b6295a327600caf.png

6 Diagnostic tests#

The two classical post-estimation checks operate on the posterior-mean residuals: a single \((T_{\text{eff}}, K)\) array. Both return a pandas.DataFrame with one row per endogenous variable.

6.1 Normality: Jarque-Bera#

The Jarque-Bera statistic tests whether the skewness and excess kurtosis of the residuals are jointly zero. Under H₀ (normality) it follows a χ²(2) distribution. A large p-value means we cannot reject normality: good news for the Gaussian likelihood assumption.

norm_results = model.test_normality()
norm_results.index = var_labels
print("Jarque-Bera normality test")
print(norm_results.round(4))
print("\nInterpretation: p_value > 0.05 → cannot reject normality (residuals look Gaussian)")
Jarque-Bera normality test
     jb_stat  p_value
ΔY₁   0.3268   0.8492
ΔY₂   7.2350   0.0268

Interpretation: p_value > 0.05 → cannot reject normality (residuals look Gaussian)

6.2 Whiteness: Ljung-Box#

The Ljung-Box portmanteau statistic tests whether the first lags autocorrelations of the residuals are jointly zero. Under H₀ (white noise) it follows χ²(lags). A large p-value means no evidence of remaining autocorrelation: the model has captured the serial dependence in the data.

We test at lags=10 (default) and lags=5.

wb10 = model.test_whiteness(lags=10)
wb5 = model.test_whiteness(lags=5)

wb10.index = var_labels
wb5.index = var_labels

print("Ljung-Box whiteness test (lags=10)")
print(wb10.round(4))
print()
print("Ljung-Box whiteness test (lags=5)")
print(wb5.round(4))
print("\nInterpretation: p_value > 0.05 → cannot reject white noise (no residual autocorrelation)")
Ljung-Box whiteness test (lags=10)
     lb_stat  p_value  lags
ΔY₁   4.2459   0.9356    10
ΔY₂  15.9599   0.1008    10

Ljung-Box whiteness test (lags=5)
     lb_stat  p_value  lags
ΔY₁   3.0650   0.6900     5
ΔY₂   6.8805   0.2297     5

Interpretation: p_value > 0.05 → cannot reject white noise (no residual autocorrelation)

6.3 Autocorrelation plots#

The test statistic summarises all lags into one number. Plotting the autocorrelation function (ACF) shows which lags are problematic if the test fails.

from statsmodels.graphics.tsaplots import plot_acf

fig, axes = plt.subplots(1, 2, figsize=(12, 3.5))

for k, ax in enumerate(axes):
    plot_acf(resid_mean[:, k], lags=20, ax=ax, title=f"ACF residuals: {var_labels[k]}")

plt.tight_layout()
plt.show()
../_images/514751545688044032c1975b311e730c5ae391f02535c6aa2f91a54de5fb6598.png

Spikes within the blue 95 % confidence band indicate no significant autocorrelation at that lag. Spikes outside the band are candidates for model extension (more lags, structural breaks, stochastic volatility).

7 Summary#

Property / method

Shape / type

Key point

fittedvalues

DataArray (C, D, T_eff, K)

Full posterior; use .mean(("chain","draw")) for point estimate

resid

DataArray (C, D, T_eff, K)

fittedvalues + resid == delta_y exactly

var_rep

DataArray (C, D, p, K, K)

VECM → VAR(p) conversion; lag coord runs 1..p

test_normality()

DataFrame (K × 2)

Jarque-Bera; p_value > 0.05 → residuals Gaussian

test_whiteness(lags)

DataFrame (K × 3)

Ljung-Box; p_value > 0.05 → no residual autocorrelation

Since this notebook. exog shipped (notebook 09). Notebook 13 covers the other post-fit outputs: granger_causality and fevd.

What came next at this stage: feat/exog: contemporaneous exogenous regressors (brand spend, macro drivers). Once exog lands, sample_posterior_predictive and irf would both accept future exog paths, enabling counterfactual forecast comparisons.