09. Exogenous regressors: a brand marketing application#

This notebook is the why does this package exist moment.

Brand marketing has long-term effects that short-window regression and standard Media Mix Models miss. A VECM captures the cointegrating relationship between brand awareness and organic sales: the idea that the two series share a common stochastic trend, so deviations from equilibrium are corrected over time. The exog argument introduced in feat/exog lets brand spend enter contemporaneously in the short-run equation, on top of that long-run cointegrating relationship.

What this notebook covers

Synthetic DGP with cointegrated brand awareness + organic sales, driven by brand spend

Why plain OLS gives the wrong elasticity

Fitting BayesianVECM with exog=brand_spend

IRFs: what does a brand spend shock do over 52 weeks?

Counterfactual forecast diff: incremental revenue from a spend uplift

Since this notebook. Drivers can now act with a delay (exog_lags), and exog_irf gives the response of every series to one more unit of a driver. The practitioner guide (notebooks/guides/01_brand_vecm_walkthrough.ipynb) runs the full brand system with both.

The methodology is the Bayesian version of the approach described in this Medium article.

# ---------------------------------------------------------------------------
# Sampling configuration
# ---------------------------------------------------------------------------
FAST_SAMPLING = True

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

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from bayesian_vecm import BayesianVECM

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

1 The business problem#

Media Mix Models (MMMs) decompose observed revenue into contributions from paid media, seasonal effects, and a baseline. The organic sales baseline is what revenue would be without any paid spend: it captures long-run brand equity effects.

The problem is that brand marketing builds equity slowly. A TV burst this quarter raises brand awareness, which raises the organic baseline over the following months and years, but a standard MMM regression window is too short to see that tail. It attributes only the immediate activation spike to the campaign and misses the long-run compounding return.

A VECM on the MMM output captures this cleanly:

\[ \Delta y_t = \underbrace{\alpha \beta^{\top} y_{t-1}}_{\text{error correction}} + \underbrace{\Gamma \, \Delta y_{t-1}}_{\text{short-run dynamics}} + \underbrace{B x_t}_{\text{brand spend} \to \text{awareness}} + \varepsilon_t \]
  • \(y_1\) = organic sales baseline (MMM output) and \(y_2\) = brand awareness are cointegrated: they share a common long-run trend driven by brand equity.

  • Brand spend \(x_t\) is exogenous: it enters via \(B\) and drives awareness directly. Because \(y_1\) is already spend-decomposed, spend has no direct effect on organic sales (\(B[0,:] = 0\)); it works entirely through the awareness channel and the EC mechanism.

  • The EC term \(\alpha \beta^{\top} y_{t-1}\) then propagates the awareness shock into organic sales over time: the long-run tail the MMM cannot see.

2 Synthetic data-generating process#

We simulate 200 weeks of a bivariate system:

  • \(y_1\): organic sales baseline: the brand-spend-decomposed revenue from an MMM. Because brand spend has already been accounted for in the MMM decomposition, it should have no direct contemporaneous effect on this series.

  • \(y_2\): brand awareness score (log index): driven directly by brand spend.

  • \(x\): (log) brand spend: exogenous AR(1) process.

The cointegrating relation \(\beta^{\top} y_{t-1} = y_{1,t-1} - 0.8 y_{2,t-1}\) is the brand equity gap: over the long run, organic sales track awareness. When spend builds awareness, the EC mechanism gradually pulls sales up to match: this is the long-run brand effect that standard MMMs miss.

True parameters:

Parameter

Value

Interpretation

\(\beta\)

\((1, -0.8)\)

Long-run: 1 unit of awareness ↔ 0.8 units of organic sales

\(\alpha\)

\((-0.25, 0.10)\)

Error correction speeds

\(B\)

\((0.0, 0.15)^{\top}\)

Spend drives awareness only; zero direct effect on sales

\(\Gamma_1\)

diag\((0.15, 0.10)\)

Mild own-lag short-run persistence

T = 200

# True parameters
beta_true = np.array([1.0, -0.8])  # cointegrating vector
alpha_true = np.array([-0.25, 0.10])  # EC loadings
b_true = np.array([[0.00], [0.15]])  # spend → awareness only; zero direct sales effect
gamma_true = np.array(
    [
        [0.15, 0.0],  # short-run dynamics (Gamma_1)
        [0.0, 0.10],
    ]
)
sigma_chol = np.array([[0.40, 0.0], [0.15, 0.35]])

# Exogenous brand spend: AR(1) around a slowly rising trend
spend = np.zeros(T)
spend[0] = 1.0
for t in range(1, T):
    spend[t] = 0.6 * spend[t - 1] + 0.004 * t + rng.normal(0, 0.25)
spend = spend.reshape(-1, 1)  # (T, 1)

# Endogenous series
y = np.zeros((T, 2))
y[0] = [0.0, 0.0]
y[1] = y[0] + rng.normal(size=2) * 0.3

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

var_names = ["organic_sales", "brand_awareness"]

fig, axes = plt.subplots(3, 1, figsize=(12, 7), sharex=True)
for i, (ax, name) in enumerate(zip(axes[:2], var_names, strict=True)):
    ax.plot(y[:, i], lw=1)
    ax.set_ylabel(name)
axes[2].plot(spend, color="darkorange", lw=1)
axes[2].set_ylabel("brand_spend")
axes[2].set_xlabel("week")
plt.suptitle("Synthetic brand marketing system", y=1.01)
plt.tight_layout()
plt.show()

# Cointegrating relation should be stationary
coint_resid = y[:, 0] - 0.8 * y[:, 1]
print(f"Cointegrating residual mean: {coint_resid.mean():.3f}, std: {coint_resid.std():.3f}")
../_images/098837fc362090015fbd064e51e471905e439250855ddad418ac5a5ff7f35587.png
Cointegrating residual mean: -0.324, std: 0.534

3 Why plain OLS gives the wrong elasticity#

Before fitting the VECM, let’s see what a naive OLS on levels gives us. Regressing organic sales on brand spend ignores the cointegrating relationship and treats the series as if they were stationary.

# Naive OLS: sales ~ spend (levels)
x_ols = np.column_stack([np.ones(T), spend.ravel()])
beta_ols, *_ = np.linalg.lstsq(x_ols, y[:, 0], rcond=None)

print("OLS on levels (sales ~ constant + spend):")
print(f"  intercept : {beta_ols[0]:.3f}")
print(f"  spend coef: {beta_ols[1]:.3f}  (true short-run B[0,0] = {b_true[0, 0]:.2f})")
print()

# OLS on differences (closer to the VECM short-run but misses EC term)
dy = np.diff(y, axis=0)  # (T-1, 2)
dx = np.diff(spend, axis=0)  # (T-1, 1)
x_diff = np.column_stack([np.ones(T - 1), dx.ravel()])
beta_diff, *_ = np.linalg.lstsq(x_diff, dy[:, 0], rcond=None)
print("OLS on differences (Δsales ~ constant + Δspend):")
print(f"  spend coef: {beta_diff[1]:.3f}  (true short-run B[0,0] = {b_true[0, 0]:.2f})")
print()
print("Neither approach recovers the full long-run effect: only the VECM")
print("separates the short-run burst from the error-correction channel.")
OLS on levels (sales ~ constant + spend):
  intercept : -1.542
  spend coef: 7.867  (true short-run B[0,0] = 0.00)

OLS on differences (Δsales ~ constant + Δspend):
  spend coef: -0.115  (true short-run B[0,0] = 0.00)

Neither approach recovers the full long-run effect: only the VECM
separates the short-run burst from the error-correction channel.

4 Fitting BayesianVECM with exog=brand_spend#

We fit a VECM with:

  • k_ar_diff=1: one lag of differences (one week of short-run dynamics)

  • coint_rank=1: one cointegrating relation

  • exog=spend: brand spend enters contemporaneously as \(B x_t\)

The model estimates \(\alpha\), \(\beta\) (cointegrating vector, normalised with \(\beta_1=1\)), \(\Gamma_1\) (short-run dynamics), \(B\) (brand spend elasticity), and \(\Sigma\) jointly.

# Train on the first 170 weeks; hold out the last 30 for forecast validation
TRAIN = 170
y_train = y[:TRAIN]
spend_train = spend[:TRAIN]
spend_test = spend[TRAIN:]

model = BayesianVECM(k_ar_diff=1, coint_rank=1, deterministic="n")
model.fit(
    pd.DataFrame(y_train, columns=var_names),
    exog=spend_train,
    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, B]

               mean      sd eti89_lb eti89_ub  ess_bulk  ess_tail r_hat  \
alpha[0, 0]  -0.417   0.064    -0.51    -0.32       245       268  1.00   
alpha[1, 0]    0.04   0.065   -0.063     0.15       166       245  1.01   
beta[0, 0]        1       0        1        1       400       400   NaN   
beta[1, 0]   -0.842   0.022    -0.88    -0.81       142       181  1.01   
Gamma[0, 0]   0.175   0.077    0.054     0.29       269       334  1.00   
Gamma[0, 1]      -0   0.084    -0.13     0.13       304       334  1.00   
Gamma[1, 0]   -0.02   0.081    -0.16     0.11       321       295  1.01   
Gamma[1, 1]    0.07   0.091   -0.078     0.22       296       272  1.01   
B[0, 0]       -0.19    0.08    -0.32   -0.054       165       193  1.00   
B[1, 0]       0.162   0.051    0.088     0.24       205       288  1.01   
Sigma[0, 0]   0.157   0.017     0.13     0.18       555       292  1.01   
Sigma[0, 1]   0.066  0.0141    0.045     0.09       462       272  1.01   
Sigma[1, 0]   0.066  0.0141    0.045     0.09       462       272  1.01   
Sigma[1, 1]   0.166    0.02     0.14      0.2       531       237  1.01   

            mcse_mean  mcse_sd  
alpha[0, 0]    0.0041   0.0032  
alpha[1, 0]     0.005   0.0033  
beta[0, 0]          0      NaN  
beta[1, 0]     0.0019   0.0014  
Gamma[0, 0]    0.0047   0.0032  
Gamma[0, 1]    0.0048   0.0035  
Gamma[1, 0]    0.0045   0.0035  
Gamma[1, 1]    0.0053   0.0037  
B[0, 0]        0.0062   0.0044  
B[1, 0]        0.0036   0.0025  
Sigma[0, 0]   0.00076   0.0006  
Sigma[0, 1]   0.00067  0.00047  
Sigma[1, 0]   0.00067  0.00047  
Sigma[1, 1]   0.00093  0.00068  

5 Parameter recovery#

Let’s check whether the model recovers the true parameters.

What to look for:

  • beta[1, 0] close to −0.8 (the free cointegrating entry; beta[0,0] is pinned at 1)

  • alpha[0, 0] close to −0.25, alpha[1, 0] close to 0.10

  • B[0, 0] close to 0.00, B[1, 0] close to 0.15

Note on fast-sampling results: With FAST_SAMPLING=True (200 draws, 2 chains) the posteriors below are indicative only. alpha and B[0,0] show the most bias: EC loadings are hard to pin down with limited data and few draws, and collinearity between spend and the cointegrating trend can inflate B[0,0] away from its true value of 0. Set FAST_SAMPLING=False for publication-quality recovery (1000 draws, 4 chains).

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

params = [
    ("beta", (1, 0), -0.8, "beta[1,0]"),
    ("alpha", (0, 0), -0.25, "alpha[0,0]"),
    ("alpha", (1, 0), 0.10, "alpha[1,0]"),
    ("B", (0, 0), 0.00, "B[0,0]  (spend → sales, should be ~0)"),
    ("B", (1, 0), 0.15, "B[1,0]  (spend → awareness)"),
    ("Gamma", (0, 0), 0.15, "Gamma[0,0]"),
]

for ax, (var, idx, truth, label) in zip(axes.ravel(), params, strict=True):
    samples = model.idata_.posterior[var].values[:, :, idx[0], idx[1]].ravel()
    ax.hist(samples, bins=30, edgecolor="white")
    ax.axvline(truth, color="red", lw=1.5, ls="--", label=f"true={truth}")
    ax.axvline(samples.mean(), color="black", lw=1, ls="-", label=f"mean={samples.mean():.3f}")
    ax.set_title(label, fontsize=9)
    ax.legend(fontsize=7)

plt.suptitle("Posterior distributions vs. true values", y=1.01)
plt.tight_layout()
plt.show()
../_images/ad387dfbd2f888e153befd646e6f0738862f661c5beb0bb182f232371b0eac0f.png

6 Impulse response: how does an awareness shock propagate to organic sales?#

Brand spend builds awareness (\(B[1,0]\)), and awareness is cointegrated with organic sales. The IRF shows what happens to the endogenous system after a unit shock to one of its variables.

The most interesting response for a brand marketer is: organic sales responding to a shock in brand awareness: this is the EC mechanism in action. Because the two series share a long-run equilibrium, a positive awareness shock does not just fade; it permanently shifts the equilibrium level of organic sales upward.

We use GIRF (Generalised IRF, Pesaran & Shin 1998): order-invariant, appropriate for systems where contemporaneous feedback runs in both directions.

irf = model.irf(steps=52)

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

# The key story: organic sales responding to an awareness shock
combos = [
    ("organic_sales", "brand_awareness", "Sales response to awareness shock"),
    ("brand_awareness", "brand_awareness", "Awareness response to own shock"),
]
horizons = np.arange(53)

for ax, (resp, shock, title) in zip(axes, combos, strict=True):
    draws = irf.sel(response_variable=resp, shock_variable=shock).values.reshape(-1, 53)
    lo, hi = np.percentile(draws, [10, 90], axis=0)
    mean = draws.mean(axis=0)
    ax.fill_between(horizons, lo, hi, alpha=0.3, label="80 % credible band")
    ax.plot(horizons, mean, lw=1.5, label="Posterior mean")
    ax.axhline(0, color="black", lw=0.8, ls="--")
    ax.set_title(title, fontsize=10)
    ax.set_xlabel("horizon (weeks)")
    ax.legend(fontsize=8)

plt.suptitle("GIRF: 52-week impulse responses", y=1.01)
plt.tight_layout()
plt.show()

# Long-run organic sales response to awareness shock
sales_to_awareness = irf.sel(
    response_variable="organic_sales", shock_variable="brand_awareness"
).values.reshape(-1, 53)
print("Long-run (week 52) sales response to awareness shock:")
print(f"  Mean: {sales_to_awareness[:, -1].mean():.4f}")
print(
    f"  80% CI: [{np.percentile(sales_to_awareness[:, -1], 10):.4f}, "
    f"{np.percentile(sales_to_awareness[:, -1], 90):.4f}]"
)
../_images/ad16649ebe0e90e15982c164b737adad64091454289e94a1f71dcbc369ab893a.png
Long-run (week 52) sales response to awareness shock:
  Mean: 0.3532
  80% CI: [0.3063, 0.4015]

7 Counterfactual forecast: ROI of a spend uplift#

To price the return on a specific spend plan we use sample_posterior_predictive with two exog_future paths and take the difference.

The causal chain is: $\(\text{spend uplift} \xrightarrow{B[1,0]} \text{awareness} \xrightarrow{\alpha\beta^{\top}} \text{organic sales (long-run)}\)$

Scenario:

  • Baseline: spend at its recent mean for 30 weeks.

  • Uplift: spend is 30 % higher for weeks 1–12, then returns to baseline.

The difference in forecast organic sales (cumulated over the horizon) is the incremental revenue from the spend uplift. Because the VECM captures the EC mechanism, this includes the long-run awareness tail, not just the immediate activation effect.

STEPS = 30
spend_mean = spend_train.mean()

# Baseline and uplift spend paths
baseline_path = np.full((STEPS, 1), spend_mean)
uplift_path = baseline_path.copy()
uplift_path[:12] *= 1.30  # 30 % uplift for first 12 weeks

fc_base = model.sample_posterior_predictive(STEPS, exog_future=baseline_path, random_seed=0)
fc_uplift = model.sample_posterior_predictive(STEPS, exog_future=uplift_path, random_seed=0)

# Incremental sales = uplift forecast - baseline forecast
y_base = fc_base.posterior_predictive["y"].values  # (C, D, steps, K)
y_uplift = fc_uplift.posterior_predictive["y"].values
incr = y_uplift - y_base  # (C, D, steps, K)

# Organic sales is variable 0
incr_sales = incr[..., 0]  # (C, D, steps)
cumul_incr = incr_sales.cumsum(axis=-1)  # cumulative incremental sales

horizons_fc = np.arange(1, STEPS + 1)
lo_c, hi_c = np.percentile(cumul_incr, [10, 90], axis=(0, 1))
mean_c = cumul_incr.mean(axis=(0, 1))

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

# Left: spend paths
axes[0].plot(horizons_fc, baseline_path, label="baseline", ls="--", color="grey")
axes[0].plot(horizons_fc, uplift_path, label="uplift (+30 % for 12w)", color="darkorange")
axes[0].set_title("Brand spend scenarios")
axes[0].set_xlabel("forecast week")
axes[0].set_ylabel("spend")
axes[0].legend(fontsize=8)

# Right: cumulative incremental organic sales
axes[1].fill_between(horizons_fc, lo_c, hi_c, alpha=0.3, label="80 % credible band")
axes[1].plot(horizons_fc, mean_c, lw=1.5, label="Posterior mean")
axes[1].axhline(0, color="black", lw=0.8, ls="--")
axes[1].set_title("Cumulative incremental organic sales\n(uplift - baseline)")
axes[1].set_xlabel("forecast week")
axes[1].set_ylabel("cumulative incremental sales")
axes[1].legend(fontsize=8)

plt.suptitle("Counterfactual forecast: ROI of a 12-week spend uplift", y=1.01)
plt.tight_layout()
plt.show()

print(f"Posterior mean cumulative incremental sales at week 30: {mean_c[-1]:.3f}")
print(f"80 % credible interval: [{lo_c[-1]:.3f}, {hi_c[-1]:.3f}]")
../_images/9eed6edb63907f51433bef670812d2115b6dec2450259e29f575997889e69af0.png
Posterior mean cumulative incremental sales at week 30: 6.483
80 % credible interval: [3.990, 8.729]

8 Forecast vs. held-out actuals#

We held out the last 30 observations. Let’s compare the baseline forecast to actuals.

actual_test = y[TRAIN:]  # (30, 2)

y_base_mean = y_base.mean(axis=(0, 1))  # (steps, K)
lo_b = np.percentile(y_base, 10, axis=(0, 1))
hi_b = np.percentile(y_base, 90, axis=(0, 1))

fig, axes = plt.subplots(1, 2, figsize=(13, 4), sharey=False)

for k, (ax, name) in enumerate(zip(axes, var_names, strict=True)):
    ax.fill_between(horizons_fc, lo_b[:, k], hi_b[:, k], alpha=0.3, label="80 % forecast band")
    ax.plot(horizons_fc, y_base_mean[:, k], lw=1.5, label="Posterior mean forecast")
    ax.plot(horizons_fc, actual_test[:, k], lw=1, ls="--", color="black", alpha=0.8, label="Actual")
    ax.set_title(name)
    ax.set_xlabel("forecast week")
    ax.legend(fontsize=8)

plt.suptitle("30-week ahead forecast vs. actuals (baseline spend)", y=1.01)
plt.tight_layout()
plt.show()
../_images/2c477cecdc22dce4c9e5816da5655a781a128c13d47b354454043fad95f52c3e.png

9 Summary#

What we did

Key result

Framed organic sales as MMM output, awareness as the equity channel

Brand spend has zero direct effect on sales; all impact flows through awareness

Simulated a cointegrated system

Awareness and organic sales share a stochastic trend

Showed OLS gives the wrong elasticity

Levels OLS conflates long-run and short-run effects

Fitted BayesianVECM(exog=spend)

\(B[0,0] \approx 0\), \(B[1,0] \approx 0.15\): model correctly attributes spend to awareness

Computed GIRF: awareness → sales

Persistent long-run response via EC mechanism

Ran counterfactual forecast diff

Incremental sales from spend uplift with posterior credible bands

The key insight: brand spend builds awareness, and awareness is cointegrated with organic sales. The error-correction term propagates the awareness gain into organic sales over time: a tail that is structurally invisible to a standard MMM. The counterfactual forecast diff gives the practitioner a Bayesian ROI estimate with honest uncertainty.

What came next: the multi-variable system (awareness, consideration and organic sales) and the applied workflow. Both are in the practitioner guide.