A practitioner’s guide to Bayesian VECM for brand marketing#
Audience: marketing analysts and brand managers. No econometrics background is needed.
Learning objectives. By the end you will be able to:
§1 Explain why a media mix model with a few weeks of adstock misses the long-term effect of brand.
§2 Set up your own data: which series are brand metrics and sales, which are drivers, and in what units.
§3 Test whether each series trends.
§3a Handle a driver that trends by entering its weekly change.
§3b Check what helps predict what before fitting, including whether budgets follow performance.
§4 Choose the number of long-run relationships.
§5 Fit the model and check the sampler before reading any result.
§6 Read β as the long-run relationships and α as who adjusts and how fast.
§7 Trace how sales respond to an awareness shock and say what the ordering assumption does.
§8 Tell whether one metric helps predict another (evidence tables) apart from how much it explains (FEVD).
§9 Value a spend plan by comparing two forecast paths.
§9a Draw a response curve across spend levels and say what a linear model can and cannot show.
§9b Turn one more unit of a channel into revenue per £ over 1, 3 and 5 years.
§9c Check the model out of sample with a hold-out year.
The notebook runs on simulated data with a known answer, so every step can be checked. What the model found is summarised at the end, before the practical tips.
Why not just use an MMM? A standard Media Mix Model treats the effect of brand spend as gone within a few weeks. Brand investment also builds awareness and consideration, and those hold sales up for years. A VECM models the long-run relationship between the brand metrics and sales, so it can measure the part of the effect that an MMM leaves out.
The variables. Three trending series go in the model as endogenous variables:
Endogenous |
Meaning |
|---|---|
|
Weekly revenue not explained by paid performance media |
|
% unaided brand awareness (survey) |
|
% brand consideration (survey) |
Five series go in as exogenous drivers. Four are stationary. The interest rate trends, so it goes in as its weekly change (§3a):
Exogenous |
Meaning |
|---|---|
|
Brand investment (TV, digital brand, out of home) |
|
Earned media reach |
|
Sponsorship reach |
|
Central bank base rate |
|
Consumer confidence index |
The data is simulated. It comes from simulate_brand_data(), which uses known parameters. Every estimate below can be checked against the value that generated the data.
Reference methodology: Cain (2022) “Modelling short and long-term marketing effects in the consumer purchase journey”, IJRM 39, 96-116.
On GIRFs: Pesaran and Shin (1998) “Generalized impulse response analysis in linear multivariate models”, Economics Letters 58, 17-29. Kim (2009) “Generalized impulse response analysis: General or extreme?”, Auburn University working paper.
# Sampling configuration. Set FAST_SAMPLING = False for a publication-quality run.
FAST_SAMPLING = True
if FAST_SAMPLING:
DRAWS, TUNE, CHAINS = 1000, 1000, 2
else:
DRAWS, TUNE, CHAINS = 2000, 1000, 4
# Every credible interval in this notebook is an 89% equal-tailed interval.
CI_LO, CI_HI = 5.5, 94.5
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from bayesian_vecm import (
BayesianVECM,
check_stationarity,
granger_pretest,
select_coint_rank,
simulate_brand_data,
)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
# The fixed entries of beta have no spread, which makes ArviZ warn in summaries.
warnings.filterwarnings("ignore", category=RuntimeWarning)
plt.rcParams["figure.dpi"] = 110
§1 The problem: why brand effects last longer than your MMM thinks#
Objective: explain why a media mix model with a few weeks of adstock misses the long-term effect of brand.
A Media Mix Model (MMM) measures the short-run sales lift per £ of spend. It works well for channel attribution. Its blind spot is that brand investment builds over years.
A TV burst does more than drive this week’s sales. It raises awareness. Higher awareness raises consideration, and higher consideration raises the baseline of organic sales. A model that assumes the effect decays within 4 to 8 weeks cannot see that.
The chart below is an illustration, not an estimate:
MMM response: flattens after about 10 weeks (geometric adstock with decay 0.7).
VECM response: keeps a long-run tail, because sales are pulled towards a higher equilibrium.
Whenever sales sit below their long-run relationship with the brand metrics, the system corrects upwards. That correction is brand equity at work.
weeks = np.arange(53)
# MMM: geometric adstock with decay 0.7. The weekly effect is gone after about 10 weeks.
mmm_response = 0.7**weeks
# VECM: error correction moves sales towards a new long-run level.
alpha_ec = 0.12
vecm_response = 1.0 - (1.0 - alpha_ec) ** weeks
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(
weeks, mmm_response, lw=2, ls="--", color="tomato", label="MMM (geometric adstock, decay 0.7)"
)
ax.plot(weeks, vecm_response, lw=2, color="steelblue", label="VECM (error correction)")
ax.axhline(1.0, color="steelblue", lw=0.7, ls=":", alpha=0.5, label="VECM long-run level")
ax.set_xlabel("Weeks after the shock")
ax.set_ylabel("Weekly sales response (normalised)")
ax.set_title("Illustration: weekly sales response after a brand shock")
ax.legend()
ax.set_xlim(0, 52)
ax.set_ylim(0, 1.15)
plt.tight_layout()
plt.show()
§2 Your data#
Objective: set up your own data: which series are brand metrics and sales, which are drivers, and in what units.
The cell below is the only cell you need to change to use your own data.
The model needs two DataFrames with a weekly index:
endog: the trending series, log-transformed. Here:organic_sales,brand_awareness,brand_consideration.exog: the drivers from outside the brand system. Here: three marketing channels and two macro variables, each as a deviation from its long-run average.CHANNEL_UNITS: the unit of each marketing channel and its £ cost per unit where known. §9b uses it to turn effects into revenue per £.
# Real data: replace the simulate_brand_data() call below with something like
raw = pd.read_csv("brand_data.csv", index_col="date", parse_dates=True)
endog = np.log(raw[["organic_sales", "brand_awareness", "brand_consideration"]])
exog = raw[["brand_spend", "pr_reach", "sponsorship_reach", "interest_rate", "consumer_confidence"]]
exog = exog - exog.mean()
The default is simulate_brand_data(): 260 weeks (five years) from a VECM with known parameters. The story built into it is a chain:
marketing channels → awareness → consideration → sales
The three channels act on awareness only.
brand_spendis the strongest andsponsorship_reachthe weakest.Awareness leads. Consideration follows awareness, and sales follow consideration.
The two macro variables act on consideration only.
interest_rateis a random walk here: it trends, like a real policy rate. Its effect runs through its weekly change. §3a shows what to do with a driver like this.
data.truth holds the generating parameters. Later sections compare the estimates with it.
# ════════════════════════════════════════════════════════════════════════════
# SWAP CELL: replace this block with your own data loader
# ════════════════════════════════════════════════════════════════════════════
data = simulate_brand_data(exog_unit_root=("interest_rate",))
endog = data.endog # log levels
exog = data.exog # deviations from long-run averages; interest_rate is a level
truth = data.truth # generating parameters (simulated data only)
# Unit of each marketing channel in exog. cost_gbp is the £ cost of one unit,
# or None when it is not known. The simulated data has no real units, so these
# are assumptions: one brand_spend unit is £1,000 and one reach unit is 100,000
# people. With real spend in £1,000s keep cost_gbp = 1_000.
CHANNEL_UNITS = {
"brand_spend": {"unit": "£1,000 of spend", "cost_gbp": 1_000.0},
"pr_reach": {"unit": "100,000 people reached", "cost_gbp": None},
"sponsorship_reach": {"unit": "100,000 people reached", "cost_gbp": None},
}
# ════════════════════════════════════════════════════════════════════════════
# END SWAP CELL
# ════════════════════════════════════════════════════════════════════════════
print(f"endog: {endog.shape} | exog: {exog.shape}")
print(f"Period: {endog.index[0].date()} to {endog.index[-1].date()}")
print()
levels = np.exp(endog)
overview = pd.DataFrame(
{
"Start": levels.iloc[0],
"End": levels.iloc[-1],
"Growth %": (levels.iloc[-1] / levels.iloc[0] - 1) * 100,
}
)
print(overview.round(1))
endog: (260, 3) | exog: (260, 5)
Period: 2021-01-04 to 2025-12-22
Start End Growth %
organic_sales 1000.0 2007.3 100.7
brand_awareness 20.0 36.4 82.1
brand_consideration 10.0 17.2 72.4
n_endog, n_exog = endog.shape[1], exog.shape[1]
fig, axes = plt.subplots(n_endog + n_exog, 1, figsize=(13, 12), sharex=True)
palette_e = ["steelblue", "seagreen", "darkorchid"]
palette_x = ["darkorange", "goldenrod", "peru", "slategrey", "teal"]
for ax, col, c in zip(axes[:n_endog], endog.columns, palette_e, strict=True):
ax.plot(np.exp(endog[col]), lw=0.9, color=c)
ax.set_ylabel(col, fontsize=8)
ax.tick_params(labelsize=7)
for ax, col, c in zip(axes[n_endog:], exog.columns, palette_x, strict=True):
ax.plot(exog[col], lw=0.9, color=c, ls="--")
ax.axhline(0, color="black", lw=0.4)
ax.set_ylabel(col, fontsize=8)
ax.tick_params(labelsize=7)
axes[0].set_title(
"Endogenous series in original units (solid) and exogenous drivers (dashed)", fontsize=10
)
axes[-1].set_xlabel("Date")
plt.tight_layout()
plt.show()
§3 Do your variables have long-run trends?#
Objective: test whether each series trends.
Plain English: does a series wander with no fixed level, or does it keep returning to one?
An I(1) series has no fixed level. It becomes stationary after one difference. These go in
endog, where they can share long-run relationships.An I(0) series is stationary. These go in
exog, where they act on short-run growth.An I(2) series still trends after one difference. Difference it once before using it.
Why this matters. A VECM models the weekly changes but keeps the information in the levels through the cointegrating relations. A model fitted to changes alone would throw that long-run information away.
check_stationarity runs the Augmented Dickey-Fuller test on each column and prints a verdict. A small p-value means stationary.
stationarity = check_stationarity(pd.concat([endog, exog], axis=1))
print(stationarity)
Stationarity check (ADF test, 5% level)
regression = 'c'
variable p (levels) p (diff) order verdict
-----------------------------------------------------------------------------------------------
organic_sales 0.802 0.000 I(1) trending: endog, or exog after .diff()
brand_awareness 0.741 0.000 I(1) trending: endog, or exog after .diff()
brand_consideration 0.726 0.000 I(1) trending: endog, or exog after .diff()
brand_spend 0.000 0.000 I(0) stationary: use as exog
pr_reach 0.000 0.000 I(0) stationary: use as exog
sponsorship_reach 0.000 0.000 I(0) stationary: use as exog
interest_rate 0.578 0.000 I(1) trending: endog, or exog after .diff()
consumer_confidence 0.000 0.000 I(0) stationary: use as exog
Result: the three brand series are I(1). Four of the five drivers are I(0). interest_rate is I(1): it trends. That matches how the data was built.
stationarity.endog and stationarity.exog return the two lists of column names.
The test has low power. A stationary series that reverts slowly can be reported as I(1), most often in short samples. Treat the verdict as a guide and overrule it when you know the series.
§3a A trending driver: difference it#
Objective: handle a driver that trends by entering its weekly change.
Plain English: the interest rate drifts for years with no fixed level. The brand metrics’ weekly growth does not. A drifting level cannot explain a series that keeps returning to its average, so the model needs the rate’s weekly change instead.
The verdict offers two places for an I(1) series:
endog, when the series shares a long-run relationship with the brand series, or when the brand can move it. Neither holds for a policy rate: the brand does not set interest rates, and the rate does not trend with sales.exogafter.diff(), when the series is a driver from outside. That is the case here.
Differencing throws away the level. Do it only for drivers from outside the brand system, never for the brand series themselves: their levels carry the long-run relationships.
What goes wrong in levels. The cell below regresses weekly growth in consideration on its usual controls and the interest rate, once in levels and once in weekly changes, by least squares. The true effect of a one-unit rate change is −0.020.
def rate_effect(rate):
"""Least-squares effect of the rate on consideration growth, with its standard error."""
controls = pd.concat(
[
endog.shift(1).add_suffix(" (last week)"),
endog.diff().shift(1).add_suffix(" growth (last week)"),
],
axis=1,
)
regressors = pd.concat(
[controls, exog.drop(columns="interest_rate"), rate.rename("interest_rate")], axis=1
)
regressors.insert(0, "const", 1.0)
rows = pd.concat(
[endog["brand_consideration"].diff().rename("growth"), regressors], axis=1
).dropna()
design, yv = rows.drop(columns="growth").to_numpy(), rows["growth"].to_numpy()
coef, *_ = np.linalg.lstsq(design, yv, rcond=None)
resid = yv - design @ coef
cov = resid @ resid / (len(yv) - design.shape[1]) * np.linalg.inv(design.T @ design)
return coef[-1], np.sqrt(cov[-1, -1])
true_rate = truth.b[
endog.columns.get_loc("brand_consideration"), exog.columns.get_loc("interest_rate")
]
for label, rate in [
("level", exog["interest_rate"]),
("weekly change", exog["interest_rate"].diff()),
]:
est, se = rate_effect(rate)
print(
f"interest_rate as {label:<14} estimate {est:+.4f} (se {se:.4f}) truth {true_rate:+.4f}"
)
interest_rate as level estimate -0.0016 (se 0.0008) truth -0.0200
interest_rate as weekly change estimate -0.0186 (se 0.0028) truth -0.0200
Reading the output. In levels the estimate is close to zero and the effect is missed. In weekly changes it is close to the truth. Across 40 simulated data sets the levels fit averages −0.0006, and the change fit −0.020 with 92% of its 90% intervals covering the truth.
Difference the rate, drop the first week (it has no change), and check again:
exog = exog.assign(interest_rate=exog["interest_rate"].diff()).iloc[1:]
endog = endog.iloc[1:]
print(check_stationarity(exog[["interest_rate"]]))
Stationarity check (ADF test, 5% level)
regression = 'c'
variable p (levels) p (diff) order verdict
-----------------------------------------------------------------------------------------
interest_rate 0.000 0.000 I(0) stationary: use as exog
From here on interest_rate in exog is the weekly change in the rate. A forecast with it at zero holds the rate where it is. Do the same with your own data for any driver §3 reports as I(1) that comes from outside the brand system.
§3b What helps predict what, before fitting?#
Objective: check what helps predict what before fitting, including whether budgets follow performance.
Plain English: before choosing a model, which series move ahead of which?
granger_pretest runs Granger tests on the levels. It uses the Toda-Yamamoto method, so it is valid before the rank in §4 is known. Drivers and brand metrics enter on equal terms. Each pair is tested in both directions.
Table |
Question |
What a yes means |
|---|---|---|
Drivers |
Does past X help predict the brand metric? |
X may belong in |
Delay |
Does past X still help once this week’s drivers are known? |
Same-week |
Links |
Does past awareness help predict consideration? And so on |
How the brand metrics connect |
Feedback |
Does the past brand metric help predict the driver? |
Budgets follow performance and |
Same period |
Do two series move together within the week? |
An effect no lag can show. The direction is unknown |
pretest = granger_pretest(endog, exog)
print(pretest)
Granger pretest (Toda-Yamamoto)
lags tested = 1 extra lags = 1 n_obs = 257 alpha = 0.05
Drivers: does past X help predict the brand metric?
cause -> effect F p-value verdict
--------------------------------------------------------------------------------
brand_spend -> organic_sales 0.12 0.725 no clear evidence
pr_reach -> organic_sales 1.50 0.222 no clear evidence
sponsorship_reach -> organic_sales 4.10 0.044 helps predict
interest_rate -> organic_sales 0.15 0.700 no clear evidence
consumer_confidence -> organic_sales 0.00 0.989 no clear evidence
brand_spend -> brand_awareness 6.94 0.009 helps predict
pr_reach -> brand_awareness 8.88 0.003 helps predict
sponsorship_reach -> brand_awareness 0.25 0.619 no clear evidence
interest_rate -> brand_awareness 1.35 0.246 no clear evidence
consumer_confidence -> brand_awareness 0.01 0.937 no clear evidence
brand_spend -> brand_consideration 1.51 0.220 no clear evidence
pr_reach -> brand_consideration 1.78 0.183 no clear evidence
sponsorship_reach -> brand_consideration 0.05 0.818 no clear evidence
interest_rate -> brand_consideration 0.23 0.635 no clear evidence
consumer_confidence -> brand_consideration 19.86 0.000 helps predict
Delay: does past X still help once this period's drivers are known?
cause -> effect F p-value verdict
--------------------------------------------------------------------------------
brand_spend -> organic_sales 0.15 0.703 no clear evidence
pr_reach -> organic_sales 1.62 0.204 no clear evidence
sponsorship_reach -> organic_sales 4.18 0.042 helps predict
interest_rate -> organic_sales 0.02 0.900 no clear evidence
consumer_confidence -> organic_sales 0.13 0.715 no clear evidence
brand_spend -> brand_awareness 0.21 0.645 no clear evidence
pr_reach -> brand_awareness 1.00 0.319 no clear evidence
sponsorship_reach -> brand_awareness 0.03 0.857 no clear evidence
interest_rate -> brand_awareness 1.13 0.289 no clear evidence
consumer_confidence -> brand_awareness 0.43 0.513 no clear evidence
brand_spend -> brand_consideration 0.42 0.517 no clear evidence
pr_reach -> brand_consideration 0.01 0.911 no clear evidence
sponsorship_reach -> brand_consideration 0.35 0.556 no clear evidence
interest_rate -> brand_consideration 0.23 0.629 no clear evidence
consumer_confidence -> brand_consideration 0.47 0.492 no clear evidence
Links: does past X help predict the other brand metric?
cause -> effect F p-value verdict
--------------------------------------------------------------------------------
brand_awareness -> organic_sales 0.21 0.651 no clear evidence
brand_consideration -> organic_sales 43.60 0.000 helps predict
organic_sales -> brand_awareness 0.08 0.779 no clear evidence
brand_consideration -> brand_awareness 0.25 0.615 no clear evidence
organic_sales -> brand_consideration 0.09 0.762 no clear evidence
brand_awareness -> brand_consideration 22.40 0.000 helps predict
Feedback: does the past brand metric help predict the driver?
cause -> effect F p-value verdict
--------------------------------------------------------------------------------
organic_sales -> brand_spend 0.02 0.877 no clear evidence
brand_awareness -> brand_spend 0.03 0.853 no clear evidence
brand_consideration -> brand_spend 0.00 0.945 no clear evidence
organic_sales -> pr_reach 0.10 0.756 no clear evidence
brand_awareness -> pr_reach 0.08 0.773 no clear evidence
brand_consideration -> pr_reach 0.03 0.869 no clear evidence
organic_sales -> sponsorship_reach 1.61 0.205 no clear evidence
brand_awareness -> sponsorship_reach 0.01 0.907 no clear evidence
brand_consideration -> sponsorship_reach 1.14 0.288 no clear evidence
organic_sales -> interest_rate 0.81 0.368 no clear evidence
brand_awareness -> interest_rate 0.18 0.672 no clear evidence
brand_consideration -> interest_rate 6.77 0.010 helps predict
organic_sales -> consumer_confidence 0.02 0.879 no clear evidence
brand_awareness -> consumer_confidence 0.04 0.840 no clear evidence
brand_consideration -> consumer_confidence 0.03 0.855 no clear evidence
Same period: correlation of the VAR residuals (direction unknown)
pair corr p-value verdict
--------------------------------------------------------------------------------
organic_sales ~ brand_awareness 0.32 0.000 move together
organic_sales ~ brand_consideration 0.38 0.000 move together
organic_sales ~ brand_spend -0.01 0.816 no clear evidence
organic_sales ~ pr_reach -0.00 0.937 no clear evidence
organic_sales ~ sponsorship_reach 0.03 0.666 no clear evidence
organic_sales ~ interest_rate 0.11 0.085 no clear evidence
organic_sales ~ consumer_confidence -0.06 0.336 no clear evidence
brand_awareness ~ brand_consideration 0.41 0.000 move together
brand_awareness ~ brand_spend 0.60 0.000 move together
brand_awareness ~ pr_reach 0.55 0.000 move together
brand_awareness ~ sponsorship_reach 0.51 0.000 move together
brand_awareness ~ interest_rate -0.08 0.206 no clear evidence
brand_awareness ~ consumer_confidence 0.10 0.118 no clear evidence
brand_consideration ~ brand_spend 0.06 0.367 no clear evidence
brand_consideration ~ pr_reach 0.08 0.195 no clear evidence
brand_consideration ~ sponsorship_reach 0.05 0.396 no clear evidence
brand_consideration ~ interest_rate -0.36 0.000 move together
brand_consideration ~ consumer_confidence 0.42 0.000 move together
Reading the output against the truth.
Links: awareness → consideration and consideration → sales. These are the two links that exist. No reverse link is found.
Drivers: brand spend and PR predict awareness. Consumer confidence predicts consideration. Sponsorship has the smallest effect and is missed. The interest rate is missed too: its effect sits in the same week, and last week’s change in a random walk says nothing about this week’s.
Delay: nothing on awareness. Every channel acts in the same week. Last week’s spend predicts awareness only because spend persists from week to week.
Feedback: none into the three channels. They can be treated as exogenous.
Same period: all three channels move with awareness within the week, and both macro variables move with consideration. This is where their effects sit.
Two links pass by chance: sponsorship → sales (p = 0.044, and 0.042 in the delay table) and consideration → interest rate (p = 0.010). With 51 tests at the 5% level two or three false positives are expected. Look for a pattern across the tables rather than a single p-value.
Monthly data behaves differently. Spend late in a month shows up in next month’s average awareness. On 60 simulated months the delay test flags spend → awareness in about half the seeds. It also misses weaker links more often.
docs/granger_pretest.mdhas the hit rates.
§4 How many long-run relationships?#
Objective: choose the number of long-run relationships.
Plain English: how many equilibrium forces hold the system together?
With 3 endogenous variables the cointegration rank r can be 0, 1, 2 or 3:
r = 0: no long-run relationship. The series drift independently.
r = 1: one long-run relationship.
r = 2: two long-run relationships and one shared trend. This is the structure of the simulated data: sales track consideration, and consideration tracks awareness.
r = 3: every series is stationary. That contradicts §3.
The Johansen trace test estimates r.
coint_result = select_coint_rank(endog, det_order=0, k_ar_diff=1)
print(coint_result)
Johansen cointegration rank test (trace statistic, 5% critical value)
k_ar_diff = 1 det_order = 0
H0: r <= Trace stat Crit val (5%) Reject?
------------------------------------------------
r <= 0 68.307 29.796 yes
r <= 1 25.721 15.494 yes
r <= 2 1.300 3.841 no
------------------------------------------------
Recommended rank: 2
Reading the output: stop at the first row where the test fails to reject. That row’s null hypothesis is the recommended rank. Here it is 2, the true value.
det_order=0allows a constant, which suits series that drift upwards.det_order=1adds a linear trend to the test. On this data it finds the true rank about half as often, so it is not used here.
The test is a guide, not a ruling. Across 400 simulated datasets from this process it returns rank 2 about 80% of the time. If you have good reason to expect a given number of long-run relationships, set
coint_rankyourself.
§5 Fit the model#
Objective: fit the model and check the sampler before reading any result.
Settings:
k_ar_diff=1: one lag of weekly changes.coint_rank: from §4, or your own judgement.deterministic="co": a constant outside the cointegrating relations. It lets the series drift upwards, which brand data in a growing business does.Default priors: weakly informative Normal priors on every coefficient.
PyMC runs MCMC and returns a posterior distribution over every parameter. With FAST_SAMPLING = True this takes about three minutes on two cores.
coint_rank = max(coint_result.rank, 1) # the model needs at least one relation
model = BayesianVECM(k_ar_diff=1, coint_rank=coint_rank, deterministic="co")
model.fit(
endog,
exog=exog,
draws=DRAWS,
tune=TUNE,
chains=CHAINS,
target_accept=0.90,
random_seed=42,
progressbar=False,
)
print("Fitting complete.")
NUTS[nutpie]: [alpha, beta_free, Gamma_centred, Sigma_chol, B]
Fitting complete.
Check the sampler before reading any result. Three numbers cover most problems:
Divergences should be 0.
r-hat should be at or below 1.01 for a final run. Values up to about 1.03 are tolerable for a first look.
Bulk ESS (effective sample size) should be in the hundreds.
The fast settings already meet all three on this data. Set FAST_SAMPLING = False before relying on the numbers, since four longer chains give a firmer check.
summary = model.summary().apply(pd.to_numeric, errors="coerce")
n_div = int(model.idata.sample_stats["diverging"].sum())
print(f"Divergences: {n_div}")
print(f"Max r-hat: {summary['r_hat'].max():.2f}")
print(f"Min bulk ESS: {summary['ess_bulk'].min():.0f}")
Divergences: 0
Max r-hat: 1.00
Min bulk ESS: 1165
# The parameters that carry the long-run story
model.summary(var_names=["alpha", "beta"])
| mean | sd | eti89_lb | eti89_ub | ess_bulk | ess_tail | r_hat | mcse_mean | mcse_sd | |
|---|---|---|---|---|---|---|---|---|---|
| alpha[0, 0] | -0.23 | 0.04 | -0.29 | -0.16 | 1404 | 1316 | 1.00 | 0.0011 | 0.00078 |
| alpha[0, 1] | 0.01 | 0.032 | -0.042 | 0.063 | 1531 | 1470 | 1.00 | 0.00082 | 0.00058 |
| alpha[1, 0] | 0.001 | 0.0237 | -0.036 | 0.04 | 1580 | 1574 | 1.00 | 0.0006 | 0.00042 |
| alpha[1, 1] | 0.05 | 0.0194 | 0.02 | 0.081 | 1515 | 1765 | 1.00 | 0.0005 | 0.00036 |
| alpha[2, 0] | 0.018 | 0.028 | -0.026 | 0.064 | 1469 | 1455 | 1.00 | 0.00074 | 0.0005 |
| alpha[2, 1] | 0.202 | 0.023 | 0.16 | 0.24 | 1313 | 1466 | 1.00 | 0.00064 | 0.00044 |
| beta[0, 0] | 1 | 0 | 1 | 1 | 2000 | 2000 | NaN | 0 | NaN |
| beta[0, 1] | 0 | 0 | 0 | 0 | 2000 | 2000 | NaN | 0 | NaN |
| beta[1, 0] | 0 | 0 | 0 | 0 | 2000 | 2000 | NaN | 0 | NaN |
| beta[1, 1] | 1 | 0 | 1 | 1 | 2000 | 2000 | NaN | 0 | NaN |
| beta[2, 0] | -1.272 | 0.0205 | -1.3 | -1.2 | 1424 | 1379 | 1.00 | 0.00056 | 0.00044 |
| beta[2, 1] | -1.1355 | 0.0176 | -1.2 | -1.1 | 1681 | 1172 | 1.00 | 0.00044 | 0.00034 |
§6 What are α and β telling you?#
Objective: read β as the long-run relationships and α as who adjusts and how fast.
β (the cointegrating vectors) defines the long-run relationships. The model fixes the top block of β to the identity matrix, so each relation is anchored on one variable:
Relation 1 is anchored on
organic_sales.Relation 2 is anchored on
brand_awareness.
The free entries sit in the brand_consideration row. The series are in logs, so they are long-run elasticities. A value of -1.25 in relation 1 means sales are 1.25% higher in the long run for each 1% of extra consideration.
α (the adjustment speeds) says how fast each variable closes a gap in each relation.
A clear non-zero α means the variable follows: it is pulled back towards the relation.
An α row near zero means the variable leads: it does not adjust to anyone else.
The cells below compare both with the values that generated the data.
post = model.idata.posterior
names = list(endog.columns)
r = post["alpha"].shape[-1]
def posterior_table(var, true_values, rows):
draws = post[var].values.reshape(-1, *post[var].shape[2:])[:, : len(names), :]
mean = draws.mean(axis=0)
lo, hi = np.percentile(draws, [CI_LO, CI_HI], axis=0)
out = []
for i in rows:
for j in range(r):
out.append(
{
"variable": names[i],
"relation": j + 1,
"mean": mean[i, j],
"lower": lo[i, j],
"upper": hi[i, j],
"truth": true_values[i, j],
}
)
return pd.DataFrame(out).round(3)
print("beta: long-run coefficients (free row only, the rest are fixed at 0 or 1)")
print(posterior_table("beta", truth.beta, rows=[2]).to_string(index=False))
print()
beta_mean = post["beta"].mean(dim=["chain", "draw"]).values[: len(names)]
print(f"Relation 1: organic_sales = {-beta_mean[2, 0]:.2f} x brand_consideration + constant")
print(f"Relation 2: brand_awareness = {-beta_mean[2, 1]:.2f} x brand_consideration + constant")
beta: long-run coefficients (free row only, the rest are fixed at 0 or 1)
variable relation mean lower upper truth
brand_consideration 1 -1.272 -1.303 -1.238 -1.250
brand_consideration 2 -1.136 -1.164 -1.109 -1.125
Relation 1: organic_sales = 1.27 x brand_consideration + constant
Relation 2: brand_awareness = 1.14 x brand_consideration + constant
print("alpha: adjustment speeds, posterior mean with 89% interval")
print(posterior_table("alpha", truth.alpha, rows=[0, 1, 2]).to_string(index=False))
print()
print("Sales close about a fifth of their gap to consideration each week (relation 1).")
print("Consideration closes about a fifth of its gap to awareness each week (relation 2).")
print("Awareness has the smallest adjustment speeds. §8 tests whether it adjusts at all.")
alpha: adjustment speeds, posterior mean with 89% interval
variable relation mean lower upper truth
organic_sales 1 -0.230 -0.291 -0.163 -0.24
organic_sales 2 0.010 -0.042 0.063 0.00
brand_awareness 1 0.001 -0.036 0.040 0.00
brand_awareness 2 0.050 0.020 0.081 0.00
brand_consideration 1 0.018 -0.026 0.064 0.00
brand_consideration 2 0.202 0.164 0.239 0.18
Sales close about a fifth of their gap to consideration each week (relation 1).
Consideration closes about a fifth of its gap to awareness each week (relation 2).
Awareness has the smallest adjustment speeds. §8 tests whether it adjusts at all.
# Each relation over time. A cointegrating relation should look stationary.
ec_terms = endog.values @ beta_mean # (T, r)
ec_terms = ec_terms - ec_terms.mean(axis=0) # the constant sits outside the relation
rel_titles = [
"Relation 1: sales against consideration",
"Relation 2: awareness against consideration",
]
colors = ["steelblue", "darkorchid"]
fig, axes = plt.subplots(r, 1, figsize=(12, 3 * r), sharex=True, squeeze=False)
for i, ax in enumerate(axes[:, 0]):
ax.plot(endog.index, ec_terms[:, i], lw=0.9, color=colors[i % len(colors)])
ax.axhline(0, color="black", lw=0.6, ls="--")
ax.set_ylabel("Gap (log units)", fontsize=8)
ax.set_title(rel_titles[i] if i < len(rel_titles) else f"Relation {i + 1}", fontsize=9)
axes[-1, 0].set_xlabel("Date")
plt.suptitle("Gaps from the long-run relations: they should keep returning to zero", fontsize=10)
plt.tight_layout()
plt.show()
If these lines wander like the raw series instead of returning to zero, the rank is too high or a variable is in the wrong group. Go back to §3 and §4.
§7 The key output: how do sales respond to an awareness shock?#
Objective: trace how sales respond to an awareness shock and say what the ordering assumption does.
Plain English: awareness jumps this week, for example after a TV burst. What happens to organic sales over the next 52 weeks?
An impulse response function (IRF) traces the answer, with uncertainty. The shock is one standard deviation of the weekly surprise in awareness. The response is in log units, so 0.01 is about 1%.
The default is the generalised IRF (GIRF). It needs no column order. A GIRF for an awareness shock equals a Cholesky IRF with awareness placed first: awareness may move the other series in the same week, and they may not move it. That is a fair reading here. Cain (2022) estimates these same-week links on real brand data and finds that awareness comes first. §10 explains why GIRFs for the other shocks need more care.
Awareness leads in this system, so a shock to it is never pulled back. Sales should rise and then stay up.
irf = model.irf(steps=52, method="girf")
# Dimensions: (chain, draw, horizon, response_variable, shock_variable)
horizons = irf["horizon"].values # 0..52
def irf_draws(response, shock):
values = irf.sel(response_variable=response, shock_variable=shock).values
return values.reshape(-1, len(horizons))
fig, axes = plt.subplots(1, 3, figsize=(15, 4), sharey=True)
for ax, resp in zip(axes, endog.columns, strict=True):
draws = irf_draws(resp, "brand_awareness")
lo, hi = np.percentile(draws, [CI_LO, CI_HI], axis=0)
ax.fill_between(horizons, lo, hi, alpha=0.25, color="steelblue", label="89% interval")
ax.plot(horizons, draws.mean(axis=0), lw=1.8, color="steelblue", label="Posterior mean")
ax.axhline(0, color="black", lw=0.6, ls="--")
ax.set_xlabel("Weeks after shock")
ax.set_title(f"{resp}", fontsize=9)
axes[0].set_ylabel("Response (log units)")
axes[0].legend(fontsize=8)
plt.suptitle("Response to a one standard deviation shock in brand awareness", y=1.02)
plt.tight_layout()
plt.show()
draws_sales = irf_draws("organic_sales", "brand_awareness")
lr_lo, lr_hi = np.percentile(draws_sales[:, -1], [CI_LO, CI_HI])
print(f"Sales response at week 52: {draws_sales[:, -1].mean() * 100:.2f}%")
print(f"89% interval: [{lr_lo * 100:.2f}%, {lr_hi * 100:.2f}%]")
print("The interval excludes zero: the uplift does not fade.")
Sales response at week 52: 1.06%
89% interval: [0.92%, 1.21%]
The interval excludes zero: the uplift does not fade.
# Cumulative response, against an MMM-style adstock matched over the first 4 weeks.
cum_draws = draws_sales.cumsum(axis=1)
cum_mean = cum_draws.mean(axis=0)
cum_lo, cum_hi = np.percentile(cum_draws, [CI_LO, CI_HI], axis=0)
decay = 0.7
adstock_cum = (decay**horizons).cumsum()
mmm_cum = adstock_cum * cum_mean[4] / adstock_cum[4]
fig, ax = plt.subplots(figsize=(10, 4))
ax.fill_between(horizons, cum_lo, cum_hi, alpha=0.25, color="steelblue", label="VECM 89% interval")
ax.plot(horizons, cum_mean, lw=2, color="steelblue", label="VECM posterior mean")
ax.plot(horizons, mmm_cum, lw=2, ls="--", color="tomato", label="Geometric adstock (decay 0.7)")
ax.set_xlabel("Weeks after the awareness shock")
ax.set_ylabel("Cumulative sales response (log units)")
ax.set_title("The long-run tail (both curves matched at week 4)")
ax.legend()
plt.tight_layout()
plt.show()
print(f"Cumulative response at week 52, VECM: {cum_mean[52]:.3f}")
print(f"Cumulative response at week 52, adstock: {mmm_cum[52]:.3f}")
print(f"Ratio: {cum_mean[52] / mmm_cum[52]:.1f}x")
Cumulative response at week 52, VECM: 0.560
Cumulative response at week 52, adstock: 0.058
Ratio: 9.6x
The adstock curve is flat after about 10 weeks. The VECM curve keeps climbing, because sales have moved to a higher level and stay there. The ratio depends on the horizon: the longer the window, the bigger the gap.
Check: the GIRF is a Cholesky IRF with awareness first. A Cholesky IRF needs an order. order= sets it without touching the columns of endog. With awareness first the two methods agree exactly. With the column order, sales come first and awareness can no longer move sales in the same week, so the answer changes.
funnel = ["brand_awareness", "brand_consideration", "organic_sales"]
irf_funnel = model.irf(steps=52, method="cholesky", order=funnel)
irf_columns = model.irf(steps=52, method="cholesky")
shock = dict(shock_variable="brand_awareness")
gap = np.abs(irf_funnel.sel(**shock) - irf.sel(**shock)).max().item()
print(f"Largest gap, GIRF against Cholesky with awareness first: {gap:.1e}")
print()
for label, result in [
("GIRF", irf),
("Cholesky, awareness first", irf_funnel),
("Cholesky, column order (sales first)", irf_columns),
]:
week52 = result.sel(response_variable="organic_sales", horizon=52, **shock).values.ravel()
lo, hi = np.percentile(week52, [CI_LO, CI_HI])
print(f"{label:38s} {week52.mean() * 100:5.2f}% [{lo * 100:.2f}%, {hi * 100:.2f}%]")
Largest gap, GIRF against Cholesky with awareness first: 8.7e-18
GIRF 1.06% [0.92%, 1.21%]
Cholesky, awareness first 1.06% [0.92%, 1.21%]
Cholesky, column order (sales first) 1.02% [0.87%, 1.19%]
§8 What drives what?#
Objective: tell whether one metric helps predict another (evidence tables) apart from how much it explains (FEVD).
Plain English: which metrics lead and which follow?
Two tools answer this from the fitted posterior:
model.granger_causality()asks whether one variable helps predict another.model.fevd()asks how much of each variable’s forecast uncertainty is due to shocks in each of the others.
Evidence tables#
granger_causality() returns four tables:
Table |
Question |
|---|---|
Short run |
Does last week’s growth in X help predict this week’s growth in Y? |
Long run |
Does the level of X pull on Y? |
Weak exogeneity |
Does the variable adjust to any long-run relation at all? |
Exogenous drivers |
Does an exogenous variable help predict Y? |
Each row has an evidence score between 0 and 1. It is the highest credible level at which zero lies outside the posterior. A score at or above 0.95 is reported as a link.
These are statements about prediction, not proof of cause.
§3b put the same question to the raw data before fitting. Here it is put to the fitted model.
causality = model.granger_causality()
print(causality)
What helps predict what
evidence threshold = 0.95 Gamma prior = Normal
Short run: lagged growth in the cause (Gamma)
cause -> effect evidence mean verdict
----------------------------------------------------------------------------------
organic_sales -> brand_awareness 0.17 0.007 no clear evidence
organic_sales -> brand_consideration 0.39 -0.020 no clear evidence
brand_awareness -> organic_sales 0.19 0.022 no clear evidence
brand_awareness -> brand_consideration 1.00 0.222 helps predict
brand_consideration -> organic_sales 1.00 0.513 helps predict
brand_consideration -> brand_awareness 0.60 0.045 no clear evidence
Long run: level of the cause (Pi = alpha beta')
cause -> effect evidence mean verdict
----------------------------------------------------------------------------------
organic_sales -> brand_awareness 0.03 0.001 no clear evidence
organic_sales -> brand_consideration 0.46 0.018 no clear evidence
brand_awareness -> organic_sales 0.25 0.010 no clear evidence
brand_awareness -> brand_consideration 1.00 0.202 pulls on
brand_consideration -> organic_sales 1.00 0.281 pulls on
brand_consideration -> brand_awareness 0.88 -0.058 no clear evidence
Weak exogeneity: does the variable adjust? (alpha row)
variable evidence verdict
--------------------------------------------------------------
organic_sales 1.00 adjusts
brand_awareness 0.97 adjusts
brand_consideration 1.00 adjusts
Exogenous drivers (B)
cause -> effect evidence mean verdict
----------------------------------------------------------------------------------
brand_spend -> organic_sales 0.12 0.001 no clear evidence
brand_spend -> brand_awareness 1.00 0.017 helps predict
brand_spend -> brand_consideration 0.83 -0.004 no clear evidence
pr_reach -> organic_sales 0.29 0.001 no clear evidence
pr_reach -> brand_awareness 1.00 0.013 helps predict
pr_reach -> brand_consideration 0.66 0.002 no clear evidence
sponsorship_reach -> organic_sales 0.28 -0.001 no clear evidence
sponsorship_reach -> brand_awareness 0.98 0.006 helps predict
sponsorship_reach -> brand_consideration 0.29 0.001 no clear evidence
interest_rate -> organic_sales 0.92 0.007 no clear evidence
interest_rate -> brand_awareness 0.31 -0.001 no clear evidence
interest_rate -> brand_consideration 1.00 -0.019 helps predict
consumer_confidence -> organic_sales 0.41 -0.001 no clear evidence
consumer_confidence -> brand_awareness 0.78 0.002 no clear evidence
consumer_confidence -> brand_consideration 1.00 0.017 helps predict
Reading the tables against the truth. The data was built as a chain: channels → awareness → consideration → sales.
Short run: two links are found. They are awareness → consideration and consideration → sales, the two that exist.
Long run: the same two links.
Weak exogeneity: awareness has by far the weakest evidence of adjusting, 0.97 against 1.00 for the other two, and its α of 0.05 is the smallest. In the data it does not adjust at all, so this is a false positive. It is not sampling noise. With
FAST_SAMPLING = Falsethe score is 0.95, still at the threshold, and the 89% interval for awareness’s α still excludes zero. Read the evidence score as a scale, not a pass mark: awareness is still the series that leads.Exogenous drivers: all three channels act on awareness, in the right order of size. Both macro variables act on consideration. The fitted model finds the interest rate effect that §3b missed, because
Bincludes the same week.
Apart from the awareness adjustment, no link is reported that is not in the data. Each table is also a DataFrame, for example causality.exog.
# Channel effects on awareness against the truth
channels = ["brand_spend", "pr_reach", "sponsorship_reach"]
channel_table = causality.exog.query("effect == 'brand_awareness' and cause in @channels").copy()
channel_table["truth"] = truth.b[1, :3]
print(channel_table.round(4).to_string(index=False))
cause effect evidence mean lower upper truth
brand_spend brand_awareness 1.000 0.0175 0.0136 0.0213 0.018
pr_reach brand_awareness 1.000 0.0126 0.0090 0.0162 0.012
sponsorship_reach brand_awareness 0.982 0.0059 0.0019 0.0097 0.006
Forecast error variance decomposition#
The FEVD takes the uncertainty in a forecast h weeks ahead and splits it by source. Each row sums to 1.
At short horizons each series is mostly driven by its own shocks. At long horizons the shocks that last take over. In this system those are awareness shocks.
fevd = model.fevd(steps=52, method="girf")
fevd_mean = fevd.mean(dim=["chain", "draw"])
fevd_h = fevd["horizon"].values
fig, axes = plt.subplots(1, 3, figsize=(15, 4), sharey=True)
for ax, resp in zip(axes, endog.columns, strict=True):
shares = [fevd_mean.sel(response_variable=resp, shock_variable=s).values for s in names]
ax.stackplot(fevd_h, shares, labels=names, colors=palette_e, alpha=0.8)
ax.set_title(f"Forecast uncertainty in {resp}", fontsize=9)
ax.set_xlabel("Forecast horizon (weeks)")
ax.set_xlim(1, 52)
ax.set_ylim(0, 1)
axes[0].set_ylabel("Share due to shocks in")
axes[0].legend(fontsize=8, loc="lower left")
plt.suptitle("Forecast error variance decomposition (posterior mean)", y=1.02)
plt.tight_layout()
plt.show()
print("Share of forecast uncertainty due to awareness shocks (posterior mean):")
table = fevd_mean.sel(shock_variable="brand_awareness", horizon=[1, 4, 13, 52]).to_pandas()
table.index = [f"week {h}" for h in table.index]
print(table.round(2))
Share of forecast uncertainty due to awareness shocks (posterior mean):
response_variable organic_sales brand_awareness brand_consideration
week 1 0.13 0.68 0.18
week 4 0.21 0.70 0.34
week 13 0.38 0.76 0.52
week 52 0.63 0.82 0.72
The awareness share of sales uncertainty grows with the horizon. A week ahead, sales are mostly their own noise. A year ahead, more than half of the uncertainty traces back to awareness.
The share does not reach 1. The shocks to the three series are correlated, and the generalised decomposition splits that shared part between them.
§9 Counterfactual ROI: revenue impact of a brand spend uplift#
Objective: value a spend plan by comparing two forecast paths.
Plain English: what do we gain if brand spend runs above its average for six months?
Two 52-week paths are compared, using the fitted posterior:
Baseline: every exogenous driver at its long-run average.
Uplift: brand spend one standard deviation above average for 26 weeks, then back to average.
Both paths use the same random shocks, so the difference between them is the effect of the spend alone.
Brand spend acts on awareness. Awareness leads, so the gain in awareness is kept after the spend stops. Sales follow it up and stay up.
STEPS = 52
UPLIFT_WEEKS = 26
SPEND_UPLIFT = float(exog["brand_spend"].std()) # one standard deviation
spend_col = exog.columns.get_loc("brand_spend")
baseline_exog = np.zeros((STEPS, exog.shape[1])) # every driver at its average
uplift_exog = baseline_exog.copy()
uplift_exog[:UPLIFT_WEEKS, spend_col] = SPEND_UPLIFT
fc_base = model.sample_posterior_predictive(STEPS, exog_future=baseline_exog, random_seed=0)
fc_uplift = model.sample_posterior_predictive(STEPS, exog_future=uplift_exog, random_seed=0)
y_base = fc_base.posterior_predictive["y"].values # (chain, draw, STEPS, K)
y_uplift = fc_uplift.posterior_predictive["y"].values
# Uplift in each series as a fraction of its baseline level
uplift_pct = np.expm1(y_uplift - y_base) # (chain, draw, STEPS, K)
fc_weeks = np.arange(1, STEPS + 1)
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
axes[0].plot(fc_weeks, baseline_exog[:, spend_col], ls="--", color="grey", label="Baseline")
axes[0].plot(fc_weeks, uplift_exog[:, spend_col], color="darkorange", label="Uplift")
axes[0].set_title("Brand spend (deviation from average)", fontsize=9)
axes[0].set_ylabel("brand_spend")
axes[0].legend(fontsize=8)
for ax, col, c in [
(axes[1], "brand_awareness", "seagreen"),
(axes[2], "organic_sales", "steelblue"),
]:
k = names.index(col)
lo, hi = np.percentile(uplift_pct[..., k], [CI_LO, CI_HI], axis=(0, 1))
ax.fill_between(fc_weeks, lo * 100, hi * 100, alpha=0.25, color=c, label="89% interval")
ax.plot(fc_weeks, uplift_pct[..., k].mean(axis=(0, 1)) * 100, lw=1.8, color=c, label="Mean")
ax.axhline(0, color="black", lw=0.6, ls="--")
ax.set_title(f"Uplift in {col}", fontsize=9)
ax.set_ylabel("% above baseline")
ax.legend(fontsize=8)
for ax in axes:
ax.axvline(UPLIFT_WEEKS, color="grey", lw=0.7, ls=":")
ax.set_xlabel("Forecast week")
plt.suptitle(
f"Brand spend +{SPEND_UPLIFT:.2f} for {UPLIFT_WEEKS} weeks (dotted line: back to average)",
y=1.02,
)
plt.tight_layout()
plt.show()
# Revenue: weekly uplift fraction times recent average weekly sales
recent_sales = float(np.exp(endog["organic_sales"].iloc[-52:]).mean())
sales_uplift = uplift_pct[..., names.index("organic_sales")]
incr_revenue = sales_uplift.sum(axis=-1) * recent_sales # (chain, draw)
rev_lo, rev_hi = np.percentile(incr_revenue, [CI_LO, CI_HI])
wk52_lo, wk52_hi = np.percentile(sales_uplift[..., -1], [CI_LO, CI_HI])
print(f"Average weekly sales over the last year: £{recent_sales:,.0f}")
print(
f"Sales uplift at week 52: {sales_uplift[..., -1].mean() * 100:.1f}%"
f" [{wk52_lo * 100:.1f}%, {wk52_hi * 100:.1f}%]"
)
print(
f"Incremental revenue over 52 weeks: £{incr_revenue.mean():,.0f}"
f" [£{rev_lo:,.0f}, £{rev_hi:,.0f}]"
)
Average weekly sales over the last year: £1,762
Sales uplift at week 52: 23.0% [16.6%, 29.8%]
Incremental revenue over 52 weeks: £12,820 [£8,916, £16,720]
Sales are still above baseline at week 52, half a year after the spend returned to average. An MMM with a few weeks of adstock would report no effect by then.
To turn this into an ROI, divide the incremental revenue by the cost of the extra spend. §9b does this per £ with the units set in the swap cell.
§9a Brand response curve: sales uplift across spend levels#
Objective: draw a response curve across spend levels and say what a linear model can and cannot show.
Plain English: how does the 52-week sales uplift change as brand spend is held at different levels?
The cell runs 13 counterfactuals. Each holds brand spend at one level for the full year, from two standard deviations below average to two above. The other drivers stay at their averages. No new sampling is needed, so it runs in seconds.
What the curve can and cannot show. The model is linear in the spend variable, so the curve has no saturation point by construction. Its slight upward bend comes from converting log uplifts to percentages. The curve shows the size of the effect and its uncertainty. To let the data show diminishing returns, transform spend before fitting (for example, log spend or a saturation curve).
spend_sd = float(exog["brand_spend"].std())
spend_levels = np.linspace(-2, 2, 13) * spend_sd
sales_idx = names.index("organic_sales")
curve_mean = np.zeros(len(spend_levels))
curve_lo = np.zeros(len(spend_levels))
curve_hi = np.zeros(len(spend_levels))
for j, spend_val in enumerate(spend_levels):
test_exog = baseline_exog.copy()
test_exog[:, spend_col] = spend_val
fc = model.sample_posterior_predictive(STEPS, exog_future=test_exog, random_seed=0)
y_test = fc.posterior_predictive["y"].values[..., sales_idx]
# Total sales over the year, relative to the average-spend baseline
year_uplift = np.expm1(y_test - y_base[..., sales_idx]).mean(axis=-1)
curve_mean[j] = year_uplift.mean()
curve_lo[j], curve_hi[j] = np.percentile(year_uplift, [CI_LO, CI_HI])
fig, ax = plt.subplots(figsize=(10, 5))
ax.fill_between(
spend_levels,
curve_lo * 100,
curve_hi * 100,
alpha=0.25,
color="steelblue",
label="89% interval",
)
ax.plot(spend_levels, curve_mean * 100, lw=2, color="steelblue", label="Posterior mean")
ax.axvline(0, color="grey", lw=1, ls="--", label="Average spend")
ax.axhline(0, color="black", lw=0.5, ls=":")
ax.set_xlabel("Brand spend held for 52 weeks (deviation from average)")
ax.set_ylabel("Average sales uplift over the year (%)")
ax.set_title("Brand response curve: sales uplift against brand spend level")
ax.legend()
plt.tight_layout()
plt.show()
print(f"One standard deviation of brand spend is {spend_sd:.2f}.")
print(
f"Holding spend one standard deviation above average for a year lifts sales by "
f"{np.interp(spend_sd, spend_levels, curve_mean) * 100:.1f}% on average over that year."
)
One standard deviation of brand spend is 0.29.
Holding spend one standard deviation above average for a year lifts sales by 17.9% on average over that year.
§9b Return per channel: what does one more unit buy?#
Objective: turn one more unit of a channel into revenue per £ over 1, 3 and 5 years.
Plain English: put one more unit into a channel for one week. How much extra revenue comes back, and how fast?
This is the number a budget decision needs. §9 valued one plan. This section values one unit of each channel so the channels can be compared.
model.exog_irf() traces a one-week rise of one unit in each driver through the fitted system. The rise lifts awareness. Awareness carries the only shocks that last, so sales settle at a higher level and stay there.
That changes how revenue has to be counted:
The extra revenue does not stop. Every week adds a little more.
So the total depends on where counting stops. The tables show three windows: 1, 3 and 5 years.
Units. CHANNEL_UNITS in the swap cell sets them.
brand_spendis in £. Its revenue divided by its cost is a return per £.pr_reachandsponsorship_reachare in people reached. Their revenue is per unit of reach.Give a reach channel a £ cost per unit to compare it with brand spend in £.
WINDOWS = {"1 year": 52, "3 years": 156, "5 years": 260}
channels = list(CHANNEL_UNITS)
# Response of the log levels to a one-week, one-unit rise in each driver
mult = model.exog_irf(steps=max(WINDOWS.values()))
# Log change in weekly sales: (draw, week, channel)
sales_mult = (
mult.sel(response_variable="organic_sales", exog_variable=channels)
.stack(sample=("chain", "draw"))
.transpose("sample", "horizon", "exog_variable")
.values
)
# Extra revenue each week at last year's average weekly sales, then summed
cum_rev = (np.expm1(sales_mult) * recent_sales).cumsum(axis=1)
def interval(draws, decimals):
lo, hi = np.percentile(draws, [CI_LO, CI_HI])
return f"£{draws.mean():,.{decimals}f} [£{lo:,.{decimals}f}, £{hi:,.{decimals}f}]"
per_unit, per_gbp = [], []
for j, ch in enumerate(channels):
cost = CHANNEL_UNITS[ch]["cost_gbp"]
row_unit = {"channel": ch, "unit": CHANNEL_UNITS[ch]["unit"]}
row_gbp = {"channel": ch}
for label, weeks in WINDOWS.items():
total = cum_rev[:, weeks - 1, j]
row_unit[label] = interval(total, 0)
row_gbp[label] = interval(total / cost, 2) if cost else "no cost given"
per_unit.append(row_unit)
per_gbp.append(row_gbp)
print("Extra revenue per unit, one-week rise (posterior mean, 89% interval)")
print(pd.DataFrame(per_unit).to_string(index=False))
print()
print("Revenue back per £1")
print(pd.DataFrame(per_gbp).to_string(index=False))
print()
share_y1 = cum_rev[:, WINDOWS["1 year"] - 1, 0] / cum_rev[:, WINDOWS["5 years"] - 1, 0]
print(f"Share of the 5-year revenue that arrives in year 1: {share_y1.mean() * 100:.0f}%")
Extra revenue per unit, one-week rise (posterior mean, 89% interval)
channel unit 1 year 3 years 5 years
brand_spend £1,000 of spend £2,218 [£1,597, £2,820] £7,399 [£5,451, £9,376] £12,580 [£9,302, £15,948]
pr_reach 100,000 people reached £1,510 [£1,068, £1,967] £4,858 [£3,486, £6,292] £8,207 [£5,923, £10,607]
sponsorship_reach 100,000 people reached £682 [£186, £1,145] £2,241 [£727, £3,689] £3,800 [£1,270, £6,235]
Revenue back per £1
channel 1 year 3 years 5 years
brand_spend £2.22 [£1.60, £2.82] £7.40 [£5.45, £9.38] £12.58 [£9.30, £15.95]
pr_reach no cost given no cost given no cost given
sponsorship_reach no cost given no cost given no cost given
Share of the 5-year revenue that arrives in year 1: 18%
# The true path on simulated data: push one unit of each channel through the DGP
def true_cum_revenue(channel, steps):
n_vars = len(names)
x = np.zeros(truth.b.shape[1])
x[exog.columns.get_loc(channel)] = 1.0
level = np.zeros(n_vars)
growth = np.zeros(n_vars)
path = []
for h in range(steps + 1):
growth = truth.alpha @ truth.beta.T @ level + truth.gamma @ growth
growth = growth + (truth.b @ x if h == 0 else 0.0)
level = level + growth
path.append(level[names.index("organic_sales")])
return (np.expm1(np.array(path)) * recent_sales).cumsum()
weeks_axis = np.arange(1, max(WINDOWS.values()) + 2)
fig, axes = plt.subplots(1, len(channels), figsize=(15, 4))
for j, (ax, ch) in enumerate(zip(axes, channels, strict=True)):
cost = CHANNEL_UNITS[ch]["cost_gbp"] or 1.0
draws = cum_rev[..., j] / cost
lo, hi = np.percentile(draws, [CI_LO, CI_HI], axis=0)
ax.fill_between(weeks_axis, lo, hi, alpha=0.25, color="steelblue", label="89% interval")
ax.plot(weeks_axis, draws.mean(axis=0), lw=1.8, color="steelblue", label="Posterior mean")
ax.plot(
weeks_axis,
true_cum_revenue(ch, len(weeks_axis) - 1) / cost,
ls="--",
color="black",
lw=1,
label="Truth",
)
for weeks in WINDOWS.values():
ax.axvline(weeks, color="grey", lw=0.7, ls=":")
priced = CHANNEL_UNITS[ch]["cost_gbp"] is not None
ax.set_ylabel(
"Revenue per £1 (£)" if priced else f"Revenue per {CHANNEL_UNITS[ch]['unit']} (£)"
)
ax.set_xlabel("Weeks after the one-week rise")
ax.set_title(ch, fontsize=9)
axes[0].legend(fontsize=8)
plt.suptitle(
"Cumulative extra revenue from one more unit for one week (dotted lines: 1, 3, 5 years)", y=1.02
)
plt.tight_layout()
plt.show()
Reading the tables.
Brand spend returns about £2 per £1 within a year and about £13 within five years. Only 18% of the five-year revenue arrives in year 1. An MMM that counts a few weeks of adstock sees only the start of it.
The total keeps rising with the window because the sales uplift is permanent in this model. A longer window is not more accurate. It answers a different question.
The true path lies inside the interval for every channel. Sponsorship has the widest interval for its size, because its effect is the smallest in the data.
PR and sponsorship need a cost per unit before they can be ranked against brand spend.
What the figures are and are not.
They are marginal returns: one more unit near the current level of spend. The model is linear in each channel, so it has no saturation. The figures do not say where a budget should stop.
Revenue is valued at average weekly sales over the last year. A growing business earns more from the same uplift later on. The longer windows are conservative for that reason.
The three simulated channels move together, with a correlation of 0.5. The model separates them using the weeks where they differ. With real data the overlap is often larger and the intervals wider.
§9c Forecasting the levels#
Objective: check the model out of sample with a hold-out year.
Everything so far has been a difference between two paths. The model also forecasts the levels themselves, which is the plainest test of whether it has the dynamics right.
Two checks:
A hold-out year. Refit on the first four years and forecast the fifth, using the drivers that actually ran. A random walk with drift is the benchmark: it carries the last level forward at the average weekly growth.
The year ahead. Forecast 52 weeks past the end of the data with every driver at its average.
HOLDOUT = 52
train = len(endog) - HOLDOUT
holdout_model = BayesianVECM(k_ar_diff=1, coint_rank=coint_rank, deterministic="co")
holdout_model.fit(
endog.iloc[:train],
exog=exog.iloc[:train],
draws=DRAWS,
tune=TUNE,
chains=CHAINS,
target_accept=0.90,
random_seed=42,
progressbar=False,
)
fc = holdout_model.sample_posterior_predictive(
HOLDOUT, exog_future=exog.iloc[train:].to_numpy(), random_seed=0
)
fc_levels = np.exp(fc.posterior_predictive["y"].values.reshape(-1, HOLDOUT, len(names)))
fc_mean = fc_levels.mean(axis=0)
fc_lo, fc_hi = np.percentile(fc_levels, [CI_LO, CI_HI], axis=0)
hist = endog.iloc[:train].to_numpy()
drift = (hist[-1] - hist[0]) / (train - 1)
naive = np.exp(hist[-1] + drift * np.arange(1, HOLDOUT + 1)[:, None])
actual = np.exp(endog.iloc[train:].to_numpy())
def mape(pred):
return np.mean(np.abs(pred / actual - 1), axis=0) * 100
inside = ((actual >= fc_lo) & (actual <= fc_hi)).mean(axis=0) * 100
print(f"Hold-out: fit to {endog.index[train - 1].date()}, forecast {HOLDOUT} weeks")
print(
pd.DataFrame(
{
"VECM MAPE %": mape(fc_mean),
"Random walk MAPE %": mape(naive),
"Weeks inside 89% band %": inside,
},
index=names,
).round(1)
)
dates = endog.index
fig, axes = plt.subplots(1, len(names), figsize=(15, 4))
for i, (ax, name) in enumerate(zip(axes, names, strict=True)):
ax.plot(dates[train - 26 : train], np.exp(hist[-26:, i]), color="black", lw=1)
ax.plot(dates[train:], actual[:, i], color="black", lw=1, label="Actual")
ax.fill_between(
dates[train:], fc_lo[:, i], fc_hi[:, i], alpha=0.25, color="steelblue", label="89% interval"
)
ax.plot(dates[train:], fc_mean[:, i], color="steelblue", lw=1.8, label="VECM")
ax.plot(dates[train:], naive[:, i], color="grey", ls="--", lw=1, label="Random walk")
ax.axvline(dates[train - 1], color="grey", lw=0.7, ls=":")
ax.set_title(name)
ax.tick_params(axis="x", rotation=30)
axes[0].legend(fontsize=8)
plt.tight_layout()
plt.show()
NUTS[nutpie]: [alpha, beta_free, Gamma_centred, Sigma_chol, B]
Hold-out: fit to 2024-12-23, forecast 52 weeks
VECM MAPE % Random walk MAPE % Weeks inside 89% band %
organic_sales 2.2 3.7 100.0
brand_awareness 1.9 3.5 100.0
brand_consideration 1.4 3.6 100.0
AHEAD = 52
baseline = np.zeros((AHEAD, exog.shape[1])) # every driver at its average
fc_ahead = model.sample_posterior_predictive(AHEAD, exog_future=baseline, random_seed=0)
ahead_levels = np.exp(fc_ahead.posterior_predictive["y"].values.reshape(-1, AHEAD, len(names)))
ahead_lo, ahead_hi = np.percentile(ahead_levels, [CI_LO, CI_HI], axis=0)
future = pd.date_range(dates[-1], periods=AHEAD + 1, freq="W-MON")[1:]
fig, axes = plt.subplots(1, len(names), figsize=(15, 4))
for i, (ax, name) in enumerate(zip(axes, names, strict=True)):
ax.plot(dates[-104:], np.exp(endog.iloc[-104:, i]), color="black", lw=1, label="Data")
ax.fill_between(
future, ahead_lo[:, i], ahead_hi[:, i], alpha=0.25, color="steelblue", label="89% interval"
)
ax.plot(future, ahead_levels[..., i].mean(axis=0), color="steelblue", lw=1.8, label="Forecast")
ax.set_title(name)
ax.tick_params(axis="x", rotation=30)
axes[0].legend(fontsize=8)
plt.tight_layout()
plt.show()
last = np.exp(endog.iloc[-1]).to_numpy()
end = ahead_levels[:, -1, :]
growth = (end / last - 1) * 100
lo, hi = np.percentile(growth, [CI_LO, CI_HI], axis=0)
print("Growth over the next 52 weeks, drivers at their averages")
for i, name in enumerate(names):
print(f" {name:22s} {growth[:, i].mean():5.1f}% [{lo[i]:5.1f}%, {hi[i]:5.1f}%]")
Growth over the next 52 weeks, drivers at their averages
organic_sales 12.1% [ -3.6%, 29.6%]
brand_awareness 12.9% [ -0.9%, 27.8%]
brand_consideration 10.0% [ -1.9%, 22.9%]
The hold-out forecast beats the random walk on all three series and stays inside its band for the whole year. It is given the drivers that actually ran, so it tracks their swings. A forecast for planning only has the drivers you plan.
The year-ahead interval keeps widening because shocks to the shared trend never wash out. The long-run relationships stop sales and consideration drifting away from awareness, so the three bands widen together.
A forecast with drivers at their averages is the baseline for any plan. Section 9 is the same forecast with brand spend changed, and the gap between the two is the return.
What the model found#
The data was built with a known answer. Here is what the fitted model says, with 89% intervals:
An awareness shock lasts. Sales are 1.06% higher a year after a typical one-week jump in awareness (0.92% to 1.21%), and the lift does not fade (§7).
The funnel comes out in the right order. Awareness leads. Consideration follows awareness, and sales follow consideration. No reverse link is found (§8).
A six-month campaign keeps paying after it stops. Brand spend one standard deviation above average for 26 weeks lifts sales 23.0% at week 52 (16.6% to 29.8%). That is £12,820 of extra revenue over the year (§9).
Most of the return arrives after year 1. One more £1,000 of brand spend returns about £2,200 within a year and £12,600 within five years. Only 18% of the five-year total lands in year 1 (§9b).
Every figure sits close to the value that generated the data. With your own data there is no truth to check against, so the diagnostics in §5 and the hold-out in §9c carry that weight.
§10 Practical tips for real data#
Choosing k_ar_diff. Fit a VAR in levels with statsmodels and take the HQ order minus one. On the simulated data HQ picks the true order in 94% or more of seeds. docs/choosing_rank_and_lags.md has the detail.
Sampler warnings.
Divergences: raise
target_acceptto 0.95 or usetune=2000.r-hat above 1.01: use more draws or more chains.
Low ESS: the same fix as r-hat.
The prior on Γ. The default is a Normal prior. A horseshoe prior is available with priors={"Gamma": {"dist": "Horseshoe"}}. It shrinks lags that are not needed, which helps when k_ar_diff is set high. Fit it with target_accept=0.99: at 0.90 it gives tens of divergences on this dataset.
Choosing coint_rank. select_coint_rank is a guide. With three years of simulated data it finds the true rank in under half the seeds, and it usually picks too few relationships. With five years it finds it in about 80%. If domain knowledge points to a given number of long-run relationships, use that number. Then check the gap plot in §6.
If a driver tests as I(1). If the brand cannot move it and it does not trend with the brand series, difference it and keep it in exog, as §3a does for the interest rate. Otherwise it belongs in endog.
If a brand metric tests as I(0). Move it from endog to exog. It will still act on short-run growth through the B coefficients.
Units of the channels. Put spend in round units such as £1,000s and reach in 100,000s. The default prior on B is Normal(0, 1), which suits a coefficient of that size. Set CHANNEL_UNITS to match so §9b reports revenue per £.
Why log-transform. The entries of β become elasticities. Differences between two forecast paths become percentage uplifts after np.expm1.
Why deterministic="co". Brand metrics in a growing business drift upwards. A constant outside the cointegrating relations gives the model that drift. "ci" puts the constant inside the relations instead. That fixes the level of each relation but allows no drift, so it suits series with no trend.
Counterfactuals. Compare two forecast paths with the same random_seed, as §9 does. The shared shocks cancel and the difference is the effect of the change alone.
Cholesky IRFs and GIRFs. model.irf(steps=52, method="cholesky") assumes a strict order: a shock to a column can move the columns after it in the same week, and not the ones before it. Set the order with order=, as in §7. Without it the order is the column order of endog. Reordering the columns instead would also change how β is normalised. A GIRF for a shock to one series is the Cholesky IRF with that series first. Each GIRF puts its own shock first, so the GIRFs for different shocks cannot all hold at once (Kim 2009). Read the GIRF for a series you believe comes first in the chain, as Cain (2022) finds for awareness. For the others use a Cholesky order you can defend.