10. Horseshoe priors on Γ and cointegration rank selection#
What this notebook covers:
The over-specified lag problem. With real marketing data the right lag order
kis unknown. Settingk_ar_difftoo high gives an over-parameterised Γ block: most entries are near zero but the Normal(0, 0.5) prior smears mass over all of them equally.Regularised horseshoe prior. The horseshoe (Carvalho, Polson & Scott 2010; regularised by Piironen & Vehtari 2017) shrinks irrelevant Γ entries toward zero while preserving genuine short-run dynamics. An alternative to choosing the lags with an information criterion.
Cointegration rank selection.
select_coint_rankwraps the Johansen trace test to recommendrbefore fitting.Side-by-side comparison. The true DGP has no short-run dynamics, so every Γ entry is zero. We fit at
k=3. The Normal prior spreads mass over all 12 entries; the horseshoe pulls them to zero.
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from bayesian_vecm import BayesianVECM, select_coint_rank
warnings.filterwarnings("ignore", category=UserWarning)
# Set True for fast CI runs; False for publication-quality posteriors
FAST_SAMPLING = True
DRAWS = 200 if FAST_SAMPLING else 1000
TUNE = 200 if FAST_SAMPLING else 1000
CHAINS = 2 if FAST_SAMPLING else 4
rng = np.random.default_rng(seed=42)
1. The over-specified lag problem#
In a VECM the short-run dynamics block Γ has shape (K, K·k): one column per lagged-difference variable. With K=2 variables and k_ar_diff=3 that gives a 2×6 matrix of 12 free parameters, even though the true DGP here has no short-run dynamics at all.
The standard Normal(0, 0.5) prior treats every entry symmetrically. The sampler has no reason to shrink the spurious lags toward zero: it just places a wide posterior over all of them.
True DGP: bivariate cointegrated system with Γ = 0.
We’ll fit with k_ar_diff=3 and show what happens to the posterior on lags 2 and 3 under each prior.
# --- True DGP: pure EC, no short-run dynamics (true Gamma = 0) ----------
# Built from one common I(1) trend so rank=1 is reliably detected.
# y1 ~ trend, y2 ~ 0.5 * trend => cointegrating vector [1, -2].
# There are NO genuine lag-1 dynamics (true Gamma is all zeros).
# Fitting at k_ar_diff=3 gives 12 spurious Gamma entries: the ideal
# scenario to show that horseshoe shrinks them while Normal does not.
n_obs = 300
trend = np.cumsum(rng.normal(scale=1.0, size=n_obs))
y = np.column_stack(
[
trend + rng.normal(scale=0.5, size=n_obs),
0.5 * trend + rng.normal(scale=0.5, size=n_obs),
]
)
endog = pd.DataFrame(y, columns=["y1", "y2"])
fig, axes = plt.subplots(2, 1, figsize=(10, 4), sharex=True)
for i, ax in enumerate(axes):
ax.plot(endog.iloc[:, i], lw=0.8)
ax.set_ylabel(endog.columns[i])
axes[-1].set_xlabel("Time")
fig.suptitle("Simulated cointegrated series: one common trend, no lag dynamics", y=1.01)
plt.tight_layout()
plt.show()
2. Rank selection with select_coint_rank#
Before fitting, use the Johansen trace test to confirm the cointegration rank. The DGP has r=1: we should see the test reject H₀: r≤0 but not H₀: r≤1.
rank_result = select_coint_rank(endog, k_ar_diff=3, det_order=0)
print(rank_result)
print(f"\nUsing coint_rank = {rank_result.rank}")
Johansen cointegration rank test (trace statistic, 5% critical value)
k_ar_diff = 3 det_order = 0
H0: r <= Trace stat Crit val (5%) Reject?
------------------------------------------------
r <= 0 65.556 15.494 yes
r <= 1 1.948 3.841 no
------------------------------------------------
Recommended rank: 1
Using coint_rank = 1
3. Fit with Normal prior (over-specified k=3)#
The default Normal(0, 0.5) prior on Γ. With k_ar_diff=3 the model has 12 Γ entries; the last 8 (lags 2 and 3) are spurious.
model_normal = BayesianVECM(
k_ar_diff=3,
coint_rank=rank_result.rank,
deterministic="n",
)
model_normal.fit(
endog,
draws=DRAWS,
tune=TUNE,
chains=CHAINS,
target_accept=0.9,
random_seed=42,
cores=1, # macOS Jupyter multiprocessing workaround
)
print(model_normal.summary(var_names=["Gamma"]))
NUTS[nutpie]: [alpha, beta_free, Gamma, Sigma_chol]
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat \
Gamma[0, 0] -0.11 0.085 -0.25 0.023 189 271 1.01
Gamma[0, 1] 0.08 0.15 -0.14 0.3 174 267 1.01
Gamma[0, 2] -0.059 0.077 -0.18 0.056 277 300 1.01
Gamma[0, 3] 0.02 0.12 -0.18 0.2 201 207 1.00
Gamma[0, 4] -0.062 0.074 -0.17 0.05 258 328 1.01
Gamma[0, 5] 0.01 0.11 -0.18 0.17 231 259 1.00
Gamma[1, 0] -0.06 0.05 -0.14 0.016 183 141 1.02
Gamma[1, 1] 0.06 0.09 -0.081 0.21 180 231 1.01
Gamma[1, 2] -0.015 0.047 -0.089 0.062 199 217 1.01
Gamma[1, 3] -0.07 0.076 -0.2 0.046 168 163 1.02
Gamma[1, 4] -0.037 0.043 -0.1 0.032 188 217 1.00
Gamma[1, 5] -0.04 0.066 -0.15 0.07 247 245 1.00
mcse_mean mcse_sd
Gamma[0, 0] 0.0062 0.0041
Gamma[0, 1] 0.011 0.0073
Gamma[0, 2] 0.0046 0.0032
Gamma[0, 3] 0.0085 0.006
Gamma[0, 4] 0.0046 0.0034
Gamma[0, 5] 0.007 0.0051
Gamma[1, 0] 0.0037 0.0027
Gamma[1, 1] 0.0068 0.005
Gamma[1, 2] 0.0033 0.0024
Gamma[1, 3] 0.0059 0.0045
Gamma[1, 4] 0.0031 0.0021
Gamma[1, 5] 0.0042 0.0031
4. Fit with regularised horseshoe prior (over-specified k=3)#
Now the same over-specified model with priors={"Gamma": {"dist": "Horseshoe"}}. The global scale τ shrinks all Γ entries, while per-entry local scales λᵢⱼ allow genuine dynamics to escape shrinkage.
model_hs = BayesianVECM(
k_ar_diff=3,
coint_rank=rank_result.rank,
deterministic="n",
priors={"Gamma": {"dist": "Horseshoe", "tau_scale": 1.0}},
)
model_hs.fit(
endog,
draws=DRAWS,
tune=TUNE,
chains=CHAINS,
target_accept=0.99,
random_seed=42,
cores=1, # macOS Jupyter multiprocessing workaround
)
print(model_hs.summary(var_names=["Gamma"]))
NUTS[nutpie]: [alpha, beta_free, Gamma_tau, Gamma_lambda, Gamma_c2, Gamma_z, Sigma_chol]
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat \
Gamma[0, 0] -0.005 0.021 -0.04 0.016 341 267 1.01
Gamma[0, 1] -0.004 0.025 -0.039 0.027 418 398 1.00
Gamma[0, 2] -0.002 0.018 -0.034 0.018 305 329 1.01
Gamma[0, 3] -0.002 0.025 -0.032 0.031 244 190 1.02
Gamma[0, 4] -0.002 0.018 -0.033 0.017 502 433 1.00
Gamma[0, 5] -0.002 0.019 -0.029 0.025 347 351 1.00
Gamma[1, 0] -0.005 0.016 -0.036 0.011 259 365 1.02
Gamma[1, 1] 0.005 0.02 -0.013 0.036 350 297 1.00
Gamma[1, 2] 0 0.013 -0.019 0.02 447 362 1.02
Gamma[1, 3] -0.021 0.035 -0.09 0.0085 156 258 1.01
Gamma[1, 4] -0.005 0.016 -0.03 0.01 181 305 1.02
Gamma[1, 5] -0.006 0.02 -0.043 0.014 312 211 1.02
mcse_mean mcse_sd
Gamma[0, 0] 0.0011 0.0018
Gamma[0, 1] 0.0014 0.0028
Gamma[0, 2] 0.00097 0.0015
Gamma[0, 3] 0.0017 0.0032
Gamma[0, 4] 0.00084 0.0012
Gamma[0, 5] 0.00098 0.0016
Gamma[1, 0] 0.0011 0.0015
Gamma[1, 1] 0.001 0.0018
Gamma[1, 2] 0.00063 0.00082
Gamma[1, 3] 0.0028 0.0031
Gamma[1, 4] 0.00082 0.0014
Gamma[1, 5] 0.0013 0.002
Note on sampling. The horseshoe is non-centred: the sampler draws standard normals \(z\) and sets \(\Gamma = z \, \tau \, \tilde{\lambda}\). Drawing Γ directly from \(\mathcal{N}(0, \tau^2 \tilde{\lambda}^2)\) creates a funnel that NUTS cannot cross. Use
target_accept=0.99. A few divergences can remain withFAST_SAMPLING=True; set it toFalsefor a production run.
5. Posterior comparison: Normal vs horseshoe#
The key question: do the Γ entries, all zero in the true DGP, stay near zero under the horseshoe but not under the Normal prior?
Γ columns are ordered lag-major: [Δy1(t-1), Δy2(t-1), Δy1(t-2), Δy2(t-2), Δy1(t-3), Δy2(t-3)]. Every entry is zero in the truth, so every column is a test of shrinkage.
def _gamma_posterior_means(idata):
"""Return posterior mean of Gamma as a (K, K*k) array."""
return idata.posterior["Gamma"].mean(dim=["chain", "draw"]).values
def _gamma_posterior_std(idata):
"""Return posterior std of Gamma as a (K, K*k) array."""
return idata.posterior["Gamma"].std(dim=["chain", "draw"]).values
means_normal = _gamma_posterior_means(model_normal.idata)
means_hs = _gamma_posterior_means(model_hs.idata)
stds_normal = _gamma_posterior_std(model_normal.idata)
stds_hs = _gamma_posterior_std(model_hs.idata)
k_cols = means_normal.shape[1] # K * k_ar_diff = 6
k_rows = means_normal.shape[0] # K = 2
# Flatten row-major: entry (i,j) -> label "Γ[i,j]"
labels = [f"Γ[{i},{j}]" for i in range(k_rows) for j in range(k_cols)]
m_n = means_normal.ravel()
m_h = means_hs.ravel()
s_n = stds_normal.ravel()
s_h = stds_hs.ravel()
# True values are all zeros: the DGP has no short-run dynamics
true_vals = np.zeros(k_rows * k_cols)
x = np.arange(len(labels))
width = 0.35
fig, ax = plt.subplots(figsize=(14, 5))
ax.bar(
x - width / 2,
m_n,
width,
yerr=s_n,
label="Normal prior",
alpha=0.7,
color="steelblue",
capsize=3,
)
ax.bar(
x + width / 2,
m_h,
width,
yerr=s_h,
label="Horseshoe prior",
alpha=0.7,
color="darkorange",
capsize=3,
)
ax.scatter(x, true_vals, color="black", zorder=5, marker="x", s=60, label="True value")
# Shade all columns: true Gamma is all zeros, every entry is spurious
for col in range(len(labels)):
ax.axvspan(col - 0.5, col + 0.5, alpha=0.06, color="red")
ax.axhline(0, color="black", lw=0.6, ls="--")
ax.set_xticks(x)
ax.set_xticklabels(labels, rotation=45, ha="right")
ax.set_ylabel("Posterior mean ± 1 SD")
ax.set_title("Γ posteriors: Normal vs Horseshoe (all entries are zero in the true DGP)")
ax.legend()
plt.tight_layout()
plt.show()
Reading the chart:
The shaded (red) columns are spurious: true value is zero.
Under the Normal prior, all entries have non-trivial posterior spread: the prior offers no incentive to shrink toward zero even when the truth is zero.
Under the horseshoe, all entries are pulled tight to zero, correctly reflecting the true sparse (all-zero) Gamma. The global shrinkage τ is small because the data support it.
6. Posterior density plots for selected entries#
A closer look at two entries: both spurious since the true DGP has no lag dynamics.
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
entries = [
("Γ[0,0]: lag 1 (true=0.0)", (0, 0), 0.0),
("Γ[0,2]: lag 2 (true=0.0)", (0, 2), 0.0),
]
for ax, (title, (row, col), true_val) in zip(axes, entries, strict=True):
draws_n = (
model_normal.idata.posterior["Gamma"].sel(Gamma_dim_0=row, Gamma_dim_1=col).values.ravel()
)
draws_h = model_hs.idata.posterior["Gamma"].sel(Gamma_dim_0=row, Gamma_dim_1=col).values.ravel()
ax.hist(draws_n, bins=40, density=True, alpha=0.5, color="steelblue", label="Normal")
ax.hist(draws_h, bins=40, density=True, alpha=0.5, color="darkorange", label="Horseshoe")
ax.axvline(true_val, color="black", ls="--", lw=1.5, label=f"True = {true_val}")
ax.set_title(title)
ax.set_xlabel("Posterior draw")
ax.set_ylabel("Density")
ax.legend(fontsize=8)
plt.tight_layout()
plt.show()
7. Global shrinkage parameter τ#
The global scale τ controls overall sparsity. A small τ posterior means the data support strong global shrinkage: most Γ entries are near zero, consistent with an over-specified model where only a few lags matter.
tau_draws = model_hs.idata.posterior["Gamma_tau"].values.ravel()
fig, ax = plt.subplots(figsize=(7, 3))
ax.hist(tau_draws, bins=50, density=True, color="darkorange", alpha=0.8)
ax.axvline(
np.median(tau_draws),
color="black",
ls="--",
lw=1.5,
label=f"Median τ = {np.median(tau_draws):.3f}",
)
ax.set_xlabel("τ (global shrinkage)")
ax.set_ylabel("Density")
ax.set_title("Posterior of Gamma_tau: small value signals a sparse Γ block")
ax.legend()
plt.tight_layout()
plt.show()
print("Prior: HalfCauchy(1.0)")
print(f"Posterior median τ = {np.median(tau_draws):.4f}")
print(f"Posterior mean τ = {np.mean(tau_draws):.4f}")
Prior: HalfCauchy(1.0)
Posterior median τ = 0.0082
Posterior mean τ = 0.0122
8. Posterior standard deviations: how much does each prior spread mass?#
Smaller posterior SD = tighter estimate. For spurious entries we want SD ≈ 0 (concentrated at zero). For genuine entries we want comparable SD between models: we don’t want the horseshoe to over-shrink the signal.
# Repeat the lag pattern for each row of Gamma (k_rows times)
lag_pattern = ["lag 1"] * 2 + ["lag 2"] * 2 + ["lag 3"] * 2
lag_labels = lag_pattern * k_rows
df_sd = pd.DataFrame(
{
"Entry": labels,
"Lag": lag_labels,
"SD (Normal)": s_n.round(4),
"SD (Horseshoe)": s_h.round(4),
"True value": true_vals.round(3),
}
)
df_sd["SD ratio (HS/N)"] = (df_sd["SD (Horseshoe)"] / df_sd["SD (Normal)"]).round(3)
print(df_sd.to_string(index=False))
print("\nSD ratio < 1 means horseshoe is tighter (desired for spurious lags).")
print("SD ratio ≈ 1 means the horseshoe adds no shrinkage.")
Entry Lag SD (Normal) SD (Horseshoe) True value SD ratio (HS/N)
Γ[0,0] lag 1 0.0852 0.0208 0.0 0.244
Γ[0,1] lag 1 0.1453 0.0251 0.0 0.173
Γ[0,2] lag 2 0.0767 0.0176 0.0 0.229
Γ[0,3] lag 2 0.1202 0.0246 0.0 0.205
Γ[0,4] lag 3 0.0736 0.0184 0.0 0.250
Γ[0,5] lag 3 0.1065 0.0191 0.0 0.179
Γ[1,0] lag 1 0.0505 0.0160 0.0 0.317
Γ[1,1] lag 1 0.0908 0.0195 0.0 0.215
Γ[1,2] lag 2 0.0467 0.0126 0.0 0.270
Γ[1,3] lag 2 0.0758 0.0353 0.0 0.466
Γ[1,4] lag 3 0.0427 0.0155 0.0 0.363
Γ[1,5] lag 3 0.0664 0.0199 0.0 0.300
SD ratio < 1 means horseshoe is tighter (desired for spurious lags).
SD ratio ≈ 1 means the horseshoe adds no shrinkage.
9. In practice#
from bayesian_vecm import BayesianVECM, select_coint_rank
# Step 1: determine rank
rank_result = select_coint_rank(endog_df, k_ar_diff=3, det_order=0)
print(rank_result) # readable table
r = rank_result.rank # or override with domain knowledge
# Step 2: fit with generous k and horseshoe
model = BayesianVECM(
k_ar_diff=3,
coint_rank=r,
priors={"Gamma": {"dist": "Horseshoe", "tau_scale": 1.0}},
)
model.fit(endog_df, target_accept=0.99)
The horseshoe suits data where the lag criteria disagree. It expresses uncertainty about which lags matter instead of a yes or no.
When HQ gives a clear lag order, the default Normal prior at that order is simpler and samples faster.
docs/choosing_rank_and_lags.mdcompares the two on the simulated brand data.
10. Summary#
Feature |
|
|---|---|
Opt-in |
Yes: default prior stays Normal(0, 0.5) |
Additional RVs |
|
Kwargs |
|
Applies to |
The lag columns of Γ. A constant or trend keeps Normal(0, 0.5). α, β, Σ and B are unchanged |
Sampler |
|
Reference |
Piironen & Vehtari (2017) regularised horseshoe |
Rank selection workflow: select_coint_rank → set coint_rank → fit with generous k_ar_diff + horseshoe.