Response curves for your channels: plug in your own data#

Audience: analysts who want the return on each marketing channel from their own weekly data. No VECM background is needed. Guides 01 to 05 explain each step in depth.

How to use it. Edit the configuration cell below and run every cell. Nothing else needs changing. Every step records a check in a table that is printed at the end with a decision log you can keep.

Learning objectives. By the end you will be able to:

  • §1 Get weekly data into the shape the model needs: logs for sales and brand metrics, raw spend for channels with diminishing returns, yearly terms if there is a yearly pattern.

  • §2 Run the checks before fitting and know which ones need a decision from you.

  • §3 Fit one model with carryover, diminishing returns and a same-week link, and check the sampler.

  • §4 Read each channel’s carryover, saturation, how much of its effect lasts, and return per £ at current spend.

  • §5 Draw a response curve in £ for a campaign on each channel, see where the data ends and read off how much to spend.

  • §6 See what happens to sales if a channel goes dark for a quarter, and whether they come back.

  • §7 Keep a record of every check and choice for the write-up.

By default it runs on simulated data with all three features in the truth, and half of every lift in the brand metrics fading with a half-life of a year, so the answers can be checked against the values that generated the data. Set DATA_PATH to your file to switch.

Method. The model follows Cain (2022), Modelling short- and long-term marketing effects in the consumer purchase journey, International Journal of Research in Marketing 39(1), 96-116. Cain (2025), Long-term advertising effects: The Adstock illusion, Applied Marketing Analytics 11(1), 23-42, explains why a long adstock cannot stand in for brand building.

# ════════════════════════════════════════════════════════════════════════════
# CONFIGURATION: the only cell to edit
# ════════════════════════════════════════════════════════════════════════════
# A CSV with one row per week. None runs on simulated data with a known answer.
DATA_PATH = None
DATE_COLUMN = "week"

# Sales in £ a week: base sales, or total sales (see guides 06 and 07).
SALES = "organic_sales"
# Brand metrics from the tracker, in funnel order (top of the funnel first).
BRAND_METRICS = ["brand_awareness", "brand_consideration"]

# Marketing channels and the £ cost of one unit of each column.
# Put spend in £1,000s (cost 1_000) and reach in 100,000s. Use None when a
# unit has no £ cost: the return is then reported per unit.
CHANNELS = {
    "brand_spend": 1_000.0,
    "pr_reach": None,
    "sponsorship_reach": None,
}
# Other drivers set outside the brand system: prices, macro, distribution.
OTHER_DRIVERS = ["interest_rate", "consumer_confidence"]
# Yearly pattern in sales or the brand metrics (most weekly retail data has one;
# base sales built as guide 06 recommends keep it). True adds yearly terms as
# drivers and runs the rank test on a deseasonalised copy. Check the
# week-of-year chart in §1 before deciding.
SEASONAL = False

# Options (guide 03 and guide 04). Leave a list empty to switch an option off.
ADSTOCK = list(CHANNELS)  # effect carries over for weeks
SATURATION = list(CHANNELS)  # each extra £ buys a bit less; needs raw spend
# Same-week links between brand metrics, and the drivers that reach each
# effect only through its cause. Ask the exclusion question for every driver
# listed: "could this change consideration other than by building awareness?"
LINKS = {"brand_consideration": ["brand_awareness"]}
EXCLUDED = {"brand_consideration": list(CHANNELS)}
# Channels whose lift in the brand metrics may drain away over months. The model
# then estimates the share that lasts and how fast the rest fades. Empty assumes
# every lift lasts for good, which overstates long-term returns if it does not.
FADING = list(CHANNELS)

# Response curves (§5): a campaign of this many weeks on one channel, at each
# spend level, with the other channels at their average.
CAMPAIGN_WEEKS = 13
# £ of revenue each extra £ must bring back. 1.0 breaks even on revenue;
# 1 / gross margin breaks even on profit (a 40% margin needs 2.5).
HURDLE = 1.0
# Annual discount rate for revenue that arrives later. Cain (2022) uses 10%.
DISCOUNT = 0.10
# Going dark (§6): a channel switched off for DARK_WEEKS, then back to average,
# with sales followed for FOLLOW_WEEKS from the day it stops.
DARK_WEEKS = 13
FOLLOW_WEEKS = 156

# Lags and rank. None lets the tests choose; check the rank against the funnel.
K_AR_DIFF = None
COINT_RANK = None

# Placebo check (§4): refit once with every channel shifted by a year, which
# breaks any real effect. A shifted channel that still looks clear shows how
# easily the clear-effect rule is fooled on this data. Adds one fit.
PLACEBO = True

FINAL_RUN = False  # True for 4 chains of 2,000 draws before reporting
SEED = 1
# ════════════════════════════════════════════════════════════════════════════
import warnings
from pathlib import Path

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=RuntimeWarning)
plt.rcParams["figure.dpi"] = 110
pd.set_option("display.width", 140)

DRAWS, TUNE, CHAINS = (2000, 1000, 4) if FINAL_RUN else (1000, 1000, 2)
LEVEL = 0.90  # every interval is a 90% interval
TAILS = (100 * (1 - LEVEL) / 2, 100 * (1 + LEVEL) / 2)
SIMULATED = DATA_PATH is None
CHECKS = []


def check(step, item, result, status, action=""):
    """Record one check. status is "ok", "look" or "decide"."""
    CHECKS.append(
        {"step": step, "check": item, "result": result, "status": status, "action": action}
    )
    flag = {"ok": "ok    ", "look": "LOOK  ", "decide": "DECIDE"}[status]
    print(f"[{flag}] {item}: {result}" + (f"  ->  {action}" if action else ""))


def interval(x, fmt="{:.2f}"):
    lo, hi = np.percentile(x, TAILS)
    return f"{fmt.format(np.median(x))} ({fmt.format(lo)} to {fmt.format(hi)})"

§1 Load and prepare the data#

Objective: get weekly data into the shape the model needs.

What the cell below does to each group of columns:

  • Sales and brand metrics: natural logs. Effects then read as % changes and the long-run ties as ratios.

  • Channels with saturation: raw spend, never below zero. The curve needs real spend levels.

  • Other channels: deviation from their average, so 0 means a normal week.

  • Other drivers: deviation from their average. A driver that trends (a policy rate) enters as its weekly change, chosen by the test in §2.

The simulated brand has carryover (decays 0.5, 0.3 and 0.6), saturation and a same-week link from awareness to consideration of 0.2. Its interest rate is a random walk, so the trending-driver rule gets exercised too.

if SIMULATED:
    DECAYS = {"brand_spend": 0.5, "pr_reach": 0.3, "sponsorship_reach": 0.6}
    LAMBDAS = {"brand_spend": 5.0, "pr_reach": 3.0, "sponsorship_reach": 5.0}
    sim = simulate_brand_data(
        exog_unit_root=("interest_rate",),
        exog_adstock=DECAYS,
        exog_saturation=LAMBDAS,
        contemporaneous={"brand_consideration": {"brand_awareness": 0.2}},
        exog_fade=dict.fromkeys(DECAYS, 52.0),
        exog_fade_share=0.5,
    )
    truth = sim.truth
    # Back to what a data file holds: levels, not logs.
    raw = pd.concat([np.exp(sim.endog), sim.exog], axis=1)
else:
    raw = pd.read_csv(DATA_PATH, index_col=DATE_COLUMN, parse_dates=True).sort_index()

channels = list(CHANNELS)
drivers = channels + OTHER_DRIVERS
endog_cols = [SALES, *BRAND_METRICS]
missing = [c for c in endog_cols + drivers if c not in raw.columns]
if missing:
    raise KeyError(f"Columns not in the data: {missing}")
raw = raw[endog_cols + drivers].astype(float)

freq = pd.infer_freq(raw.index)
if freq is None or not freq.startswith("W"):
    raise ValueError(
        f"This notebook needs weekly data, one row per week; the dates look like {freq!r}. "
        "Windows, carryover and campaigns are all counted in weeks."
    )
not_positive = [c for c in endog_cols if (raw[c] <= 0).any()]
if not_positive:
    raise ValueError(
        f"Sales and brand metrics must be above zero to take logs: {not_positive}. "
        "Fill or drop the weeks with zeros first."
    )
if CAMPAIGN_WEEKS > 52:
    check(
        "data",
        "campaign length",
        f"{CAMPAIGN_WEEKS} weeks",
        "look",
        "longer than the 1-year window, which then ends before the campaign does",
    )

check(
    "data",
    "weeks of data",
    f"{len(raw)} weeks",
    "ok" if len(raw) >= 208 else "look",
    "" if len(raw) >= 208 else "under four years: fit the neighbouring rank too",
)
gaps = int(raw.isna().sum().sum())
check(
    "data",
    "missing values",
    f"{gaps}",
    "ok" if gaps == 0 else "decide",
    "" if gaps == 0 else "interpolate short gaps and note them, or shorten the sample",
)
raw = raw.interpolate(limit_direction="both")
negative = [c for c in SATURATION if (raw[c] < 0).any()]
if negative:
    raise ValueError(f"Saturated channels need raw, non-negative spend: {negative}")

# Yearly terms: two harmonics of the 52.18-week year, as drivers.
SEASON_COLS = []
if SEASONAL:
    week = np.arange(len(raw), dtype=float)
    for k in (1, 2):
        for name, f in (("sin", np.sin), ("cos", np.cos)):
            col = f"season_{name}{k}"
            raw[col] = f(2 * np.pi * k * week / 52.1775)
            SEASON_COLS.append(col)
    drivers = drivers + SEASON_COLS
check(
    "data",
    "yearly pattern",
    "yearly terms added" if SEASONAL else "none added",
    "decide",
    "check the week-of-year chart: SEASONAL = True if each year rises and falls the same way",
)

endog = np.log(raw[endog_cols])
exog = raw[drivers].copy()
not_saturated = [c for c in drivers if c not in SATURATION]
spend_mean = raw[channels].mean()

print(f"\n{endog.index[0].date()} to {endog.index[-1].date()}, {len(endog)} weeks")
print(raw.describe().T[["mean", "min", "max"]].round(2))
[ok    ] weeks of data: 260 weeks
[ok    ] missing values: 0
[DECIDE] yearly pattern: none added  ->  check the week-of-year chart: SEASONAL = True if each year rises and falls the same way

2021-01-04 to 2025-12-22, 260 weeks
                        mean     min      max
organic_sales        1460.41  951.05  2218.24
brand_awareness        27.85   18.86    38.30
brand_consideration    13.45    9.76    18.67
brand_spend             0.98    0.42     2.23
pr_reach                1.05    0.50     2.38
sponsorship_reach       0.96    0.39     2.37
interest_rate          -1.33   -4.05     0.96
consumer_confidence    -0.00   -1.22     1.14
fig, axes = plt.subplots(2, 1, figsize=(13, 6), sharex=True)
(np.exp(endog) / np.exp(endog.iloc[0]) * 100).plot(ax=axes[0])
axes[0].set_title("Sales and brand metrics, indexed to 100 in the first week")
raw[channels].plot(ax=axes[1], lw=0.8)
axes[1].set_title("Channels, raw units")
plt.tight_layout()
plt.show()

# Week-of-year chart: each year as a line, after taking out the year's own level.
# Lines that rise and fall together mean a yearly pattern (set SEASONAL = True).
fig, axes = plt.subplots(1, len(endog_cols), figsize=(5 * len(endog_cols), 3.4), squeeze=False)
for ax, col in zip(axes[0], endog_cols, strict=True):
    series = endog[col] - endog[col].rolling(52, center=True, min_periods=26).mean()
    iso = series.index.isocalendar()
    for year, part in series.groupby(iso.year.to_numpy()):
        weeks = part.index.isocalendar().week.to_numpy()
        order = np.argsort(weeks)
        if len(part) >= 40:
            ax.plot(weeks[order], 100 * part.to_numpy()[order], lw=1, label=year)
    ax.axhline(0, color="grey", lw=0.6)
    ax.set_title(f"{col}: each year against its own trend")
    ax.set_xlabel("Week of the year")
    ax.set_ylabel("% above trend")
axes[0, -1].legend(fontsize=7, ncol=2)
plt.tight_layout()
plt.show()
../_images/2dee9ba14effcb77efeda4d5c4a61dfd740dbcaa74a895a3dcde3cab71c676a4.png ../_images/72e7082233b3fd673d9d41c9f4a9e675f4040e2159895ddf3cc50e77be41e94d.png

§2 Checks before fitting#

Objective: run the checks before fitting and know which ones need a decision from you.

  • Trends. Sales and brand metrics should trend (I(1)) to share long-run ties. A driver that trends enters as its weekly change.

  • What helps predict what (granger_pretest). The feedback rows ask whether past brand metrics predict spend: if budgets follow performance, the channel’s effect is biased. One hit in a large table can be chance (3% to 10% per test on simulated data). Ask how that budget is set.

  • The same-week link. Its instruments must be strong (first-stage F above 10) and agree (Sargan). Otherwise the link is left out, which is safe for the return per £.

  • Lags from the Hannan-Quinn criterion. Rank from the Johansen test, checked against the funnel: K series sharing one trend give K - 1 ties.

station = check_stationarity(pd.concat([endog, exog[OTHER_DRIVERS]], axis=1))
print(station, "\n")
for col in endog_cols:
    trending = col in station.endog
    check(
        "before fit",
        f"{col} trends",
        "yes" if trending else "no",
        "ok" if trending else "decide",
        ""
        if trending
        else "a series with no trend cannot share a long-run tie: move it to drivers?",
    )

trending_drivers = [c for c in OTHER_DRIVERS if c in station.endog]
for col in trending_drivers:
    check("before fit", f"{col} trends", "yes", "ok", "entered as its weekly change")
exog[trending_drivers] = exog[trending_drivers].diff()
exog[not_saturated] = exog[not_saturated] - exog[not_saturated].mean()
exog = exog.iloc[1:]
endog = endog.iloc[1:]
Stationarity check (ADF test, 5% level)
  regression = 'c'

  variable             p (levels)   p (diff)  order  verdict
  -----------------------------------------------------------------------------------------------
  organic_sales             0.803      0.000   I(1)  trending: endog, or exog after .diff()
  brand_awareness           0.660      0.000   I(1)  trending: endog, or exog after .diff()
  brand_consideration       0.727      0.000   I(1)  trending: endog, or exog after .diff()
  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 

[ok    ] organic_sales trends: yes
[ok    ] brand_awareness trends: yes
[ok    ] brand_consideration trends: yes
[ok    ] interest_rate trends: yes  ->  entered as its weekly change
links = {k: v for k, v in LINKS.items() if v}
pretest = granger_pretest(
    endog, exog, contemporaneous=links or None, excluded=EXCLUDED if links else None
)
print(pretest)

alpha = pretest.alpha
feedback = pretest.tests[
    (pretest.tests["group"] == "metric -> driver")
    & pretest.tests["cause"].isin(endog_cols)
    & pretest.tests["effect"].isin(channels)
    & (pretest.tests["p_value"] < alpha)
]
if feedback.empty:
    check("before fit", "budgets follow performance", "no feedback found", "ok")
for r in feedback.itertuples():
    check(
        "before fit",
        f"feedback {r.cause} -> {r.effect}",
        f"p = {r.p_value:.3f}",
        "decide",
        "ask how this budget is set; one hit in a large table can be chance",
    )

LINKS_USED, EXCLUDED_USED = {}, {}
if links:
    for r in pretest.same_week.itertuples():
        keep = r.verdict in ("same-week link", "no clear evidence")
        check(
            "before fit",
            f"same-week {r.cause} -> {r.effect}",
            f"{r.verdict}, 2SLS {r.estimate:.2f}, F {r.first_stage_f:.0f}, "
            f"Sargan p {r.sargan_p:.2f}",
            "ok" if keep else "look",
            "kept" if keep else "left out of the fit",
        )
        if keep:
            LINKS_USED.setdefault(r.effect, []).append(r.cause)
    EXCLUDED_USED = {k: v for k, v in EXCLUDED.items() if k in LINKS_USED}
    for effect, drop in EXCLUDED_USED.items():
        check(
            "before fit",
            f"exclusions for {effect}",
            ", ".join(drop),
            "decide",
            "confirm each reaches it only through the cause; record why",
        )
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.24     0.627  no clear evidence
  pr_reach -> organic_sales                         1.35     0.246  no clear evidence
  sponsorship_reach -> organic_sales                2.71     0.101  no clear evidence
  interest_rate -> organic_sales                    0.23     0.629  no clear evidence
  consumer_confidence -> organic_sales              0.00     0.977  no clear evidence
  brand_spend -> brand_awareness                    8.21     0.005  helps predict
  pr_reach -> brand_awareness                       8.96     0.003  helps predict
  sponsorship_reach -> brand_awareness              0.37     0.542  no clear evidence
  interest_rate -> brand_awareness                  1.84     0.176  no clear evidence
  consumer_confidence -> brand_awareness            0.02     0.898  no clear evidence
  brand_spend -> brand_consideration                0.25     0.616  no clear evidence
  pr_reach -> brand_consideration                   3.65     0.057  no clear evidence
  sponsorship_reach -> brand_consideration          0.03     0.868  no clear evidence
  interest_rate -> brand_consideration              0.26     0.611  no clear evidence
  consumer_confidence -> brand_consideration       19.33     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.24     0.624  no clear evidence
  pr_reach -> organic_sales                         1.17     0.281  no clear evidence
  sponsorship_reach -> organic_sales                2.64     0.106  no clear evidence
  interest_rate -> organic_sales                    0.07     0.798  no clear evidence
  consumer_confidence -> organic_sales              0.17     0.678  no clear evidence
  brand_spend -> brand_awareness                    3.20     0.075  no clear evidence
  pr_reach -> brand_awareness                       2.13     0.146  no clear evidence
  sponsorship_reach -> brand_awareness              0.00     0.948  no clear evidence
  interest_rate -> brand_awareness                  1.51     0.220  no clear evidence
  consumer_confidence -> brand_awareness            0.33     0.565  no clear evidence
  brand_spend -> brand_consideration                0.02     0.886  no clear evidence
  pr_reach -> brand_consideration                   0.28     0.598  no clear evidence
  sponsorship_reach -> brand_consideration          0.21     0.651  no clear evidence
  interest_rate -> brand_consideration              0.21     0.645  no clear evidence
  consumer_confidence -> brand_consideration        0.44     0.506  no clear evidence

Links: does past X help predict the other brand metric?
  cause -> effect                                      F   p-value  verdict
  --------------------------------------------------------------------------------
  brand_awareness -> organic_sales                  0.04     0.836  no clear evidence
  brand_consideration -> organic_sales             42.25     0.000  helps predict
  organic_sales -> brand_awareness                  0.38     0.540  no clear evidence
  brand_consideration -> brand_awareness            0.48     0.490  no clear evidence
  organic_sales -> brand_consideration              0.07     0.799  no clear evidence
  brand_awareness -> brand_consideration           20.75     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.28     0.596  no clear evidence
  brand_awareness -> brand_spend                    0.00     0.948  no clear evidence
  brand_consideration -> brand_spend                0.15     0.696  no clear evidence
  organic_sales -> pr_reach                         0.55     0.458  no clear evidence
  brand_awareness -> pr_reach                       0.02     0.894  no clear evidence
  brand_consideration -> pr_reach                   0.03     0.852  no clear evidence
  organic_sales -> sponsorship_reach                0.33     0.567  no clear evidence
  brand_awareness -> sponsorship_reach              0.01     0.921  no clear evidence
  brand_consideration -> sponsorship_reach          0.40     0.527  no clear evidence
  organic_sales -> interest_rate                    0.43     0.515  no clear evidence
  brand_awareness -> interest_rate                  0.98     0.323  no clear evidence
  brand_consideration -> interest_rate              6.60     0.011  helps predict
  organic_sales -> consumer_confidence              0.01     0.931  no clear evidence
  brand_awareness -> consumer_confidence            0.08     0.778  no clear evidence
  brand_consideration -> consumer_confidence        0.02     0.879  no clear evidence

Same period: correlation of the VAR residuals (direction unknown)
  pair                                              corr   p-value  verdict
  --------------------------------------------------------------------------------
  organic_sales ~ brand_awareness                   0.38     0.000  move together
  organic_sales ~ brand_consideration               0.38     0.000  move together
  organic_sales ~ brand_spend                      -0.01     0.897  no clear evidence
  organic_sales ~ pr_reach                          0.02     0.715  no clear evidence
  organic_sales ~ sponsorship_reach                 0.03     0.656  no clear evidence
  organic_sales ~ interest_rate                     0.11     0.080  no clear evidence
  organic_sales ~ consumer_confidence              -0.06     0.356  no clear evidence
  brand_awareness ~ brand_consideration             0.49     0.000  move together
  brand_awareness ~ brand_spend                     0.37     0.000  move together
  brand_awareness ~ pr_reach                        0.37     0.000  move together
  brand_awareness ~ sponsorship_reach               0.32     0.000  move together
  brand_awareness ~ interest_rate                  -0.04     0.537  no clear evidence
  brand_awareness ~ consumer_confidence             0.09     0.142  no clear evidence
  brand_consideration ~ brand_spend                 0.12     0.047  move together
  brand_consideration ~ pr_reach                    0.12     0.054  no clear evidence
  brand_consideration ~ sponsorship_reach           0.08     0.205  no clear evidence
  brand_consideration ~ interest_rate              -0.36     0.000  move together
  brand_consideration ~ consumer_confidence         0.43     0.000  move together

Same week: does X move the brand metric in the same period? (2SLS)
  cause -> effect                                    OLS    2SLS   p-value       F  verdict
  ----------------------------------------------------------------------------------------
  brand_awareness -> brand_consideration           0.549   0.249     0.079    17.3  no clear evidence
[ok    ] budgets follow performance: no feedback found
[ok    ] same-week brand_awareness -> brand_consideration: no clear evidence, 2SLS 0.25, F 17, Sargan p 0.60  ->  kept
[DECIDE] exclusions for brand_consideration: brand_spend, pr_reach, sponsorship_reach  ->  confirm each reaches it only through the cause; record why
k_ar_diff = K_AR_DIFF if K_AR_DIFF is not None else max(pretest.lags - 1, 1)
check(
    "before fit",
    "lags (k_ar_diff)",
    f"{k_ar_diff}",
    "ok" if K_AR_DIFF is None else "decide",
    "from Hannan-Quinn" if K_AR_DIFF is None else "set by hand: record why",
)

rank_data = endog
if SEASONAL:
    # The trace test has no seasonal terms, so run it on a deseasonalised copy.
    terms = np.column_stack([np.ones(len(endog)), exog[SEASON_COLS].to_numpy()])
    coef, *_ = np.linalg.lstsq(terms, endog.to_numpy(), rcond=None)
    rank_data = endog - terms[:, 1:] @ coef[1:]
rank_test = select_coint_rank(rank_data, k_ar_diff=k_ar_diff, det_order=0)
print(rank_test)
funnel_rank = len(endog_cols) - 1
coint_rank = COINT_RANK if COINT_RANK is not None else max(min(rank_test.rank, funnel_rank), 1)
agrees = rank_test.rank == funnel_rank
check(
    "before fit",
    "long-run ties (rank)",
    f"test {rank_test.rank}, funnel {funnel_rank}, used {coint_rank}",
    "ok" if agrees else "decide",
    "" if agrees else "test and funnel disagree: fit the other rank too and compare the returns",
)
[ok    ] lags (k_ar_diff): 1  ->  from Hannan-Quinn
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        66.432          29.796      yes
     r <= 1        23.883          15.494      yes
     r <= 2         1.380           3.841       no
  ------------------------------------------------
  Recommended rank: 2
[ok    ] long-run ties (rank): test 2, funnel 2, used 2

§3 Fit and check the sampler#

Objective: fit one model with every option switched on in the configuration, and check it before reading any result.

Good: 0 divergences, r-hat at or below 1.01, bulk ESS in the hundreds. Residual autocorrelation points to too few lags or a missing driver, often seasonality.

model = BayesianVECM(
    k_ar_diff=k_ar_diff,
    coint_rank=coint_rank,
    deterministic="co",
    adstock=ADSTOCK or None,
    saturation=SATURATION or None,
    contemporaneous=LINKS_USED or None,
    excluded=EXCLUDED_USED or None,
    fading=FADING or None,
)
model.fit(
    endog,
    exog=exog,
    draws=DRAWS,
    tune=TUNE,
    chains=CHAINS,
    target_accept=0.95,
    random_seed=SEED,
    progressbar=False,
)

summary = model.summary().apply(pd.to_numeric, errors="coerce")
n_div = int(model.idata_.sample_stats["diverging"].sum())
r_hat, ess = summary["r_hat"].max(), summary["ess_bulk"].min()
check(
    "fit",
    "divergences",
    f"{n_div}",
    "ok" if n_div == 0 else "look",
    "" if n_div == 0 else "raise target_accept to 0.99, then simplify",
)
check(
    "fit",
    "max r-hat",
    f"{r_hat:.3f}",
    "ok" if r_hat <= 1.01 else "look",
    "" if r_hat <= 1.01 else "more draws or chains (FINAL_RUN = True)",
)
check(
    "fit",
    "min bulk ESS",
    f"{ess:.0f}",
    "ok" if ess >= 400 else "look",
    "" if ess >= 400 else "more draws (FINAL_RUN = True)",
)
white = model.test_whiteness(lags=10)
autocorr = list(white.index[white["p_value"] < 0.01])
check(
    "fit",
    "residual autocorrelation",
    ", ".join(autocorr) or "none at 1%",
    "ok" if not autocorr else "look",
    "" if not autocorr else "one more lag, or seasonal terms as drivers",
)
NUTS[nutpie]: [alpha, beta_free, Gamma_centred, Sigma_chol, A0_links, adstock_alpha, B_total_raw, saturation_lam, B_free_raw, fade_share, fade_half_life]
[ok    ] divergences: 0
[ok    ] max r-hat: 1.010
[ok    ] min bulk ESS: 866
[ok    ] residual autocorrelation: none at 1%

§4 What each channel does#

Objective: read each channel’s carryover, saturation and return per £ at current spend.

  • Half-life: weeks until half of a week’s effect has landed, from the adstock decay.

  • Effect on the first brand metric: the total effect of one more unit at average spend, as a log change. The evidence score says whether it is clearly away from zero, not how big it is.

  • Lasting share and fade half-life (channels in FADING): how much of a lift in the brand metrics stays for good, and how fast the rest drains away. Five years of data pin these down only loosely, so read them through their intervals: a lasting share of 0.1 to 0.9 means the data cannot tell. A period when a channel went dark sharpens them most. Guide 09 shows what the fade costs and what the data can settle.

  • Return per £: one more unit for one week at average spend, valued at sales over the last year, summed over 1 and 5 years and discounted at DISCOUNT a year (10% by default, as in Cain 2022). Without FADING the model assumes every lift lasts, so the 5-year figure grows with the window.

post = model.idata_.posterior
names = model.exog_names_
first = BRAND_METRICS[0]
drivers_table = model.granger_causality(ci_prob=LEVEL).exog.set_index(["cause", "effect"])

rows = []
for ch in channels:
    j = names.index(ch)
    row = {"channel": ch}
    if ch in ADSTOCK:
        w = post["adstock_alpha"].values[..., model.adstock_idx_.index(j)].ravel()
        row["decay"] = interval(w)
        row["half-life (weeks)"] = f"{np.median(np.log(0.5) / np.log(w)):.1f}"
    if ch in SATURATION:
        lam = post["saturation_lam"].values[..., model.saturation_idx_.index(j)].ravel()
        row["saturation lam"] = interval(lam, "{:.1f}")
    if ch in FADING:
        k = model.fading_idx_.index(j)
        row["lasting share"] = interval(1.0 - post["fade_share"].values[..., k].ravel())
        row["fade half-life (weeks)"] = interval(
            post["fade_half_life"].values[..., k].ravel(), "{:.0f}"
        )
    effect = drivers_table.loc[(ch, first)]
    row[f"effect on {first}"] = (
        f"{effect['mean']:.4f} ({effect['lower']:.4f} to {effect['upper']:.4f})"
    )
    row["evidence"] = f"{effect['evidence']:.2f}"
    rows.append(row)
channel_table = pd.DataFrame(rows).set_index("channel")

# A channel with no clear effect on any brand metric has no readable curve.
CLEAR = []
for ch in channels:
    best = max(drivers_table.loc[(ch, m), "evidence"] for m in endog_cols)
    if best >= 0.95:
        CLEAR.append(ch)
    else:
        check(
            "results",
            f"{ch} effect",
            f"no clear effect (best evidence {best:.2f})",
            "look",
            "its curve is not drawn: more data, more spend variation, or drop saturation for it",
        )
channel_table
[LOOK  ] sponsorship_reach effect: no clear effect (best evidence 0.68)  ->  its curve is not drawn: more data, more spend variation, or drop saturation for it
decay half-life (weeks) saturation lam lasting share fade half-life (weeks) effect on brand_awareness evidence
channel
brand_spend 0.62 (0.48 to 0.74) 1.5 7.5 (4.6 to 10.9) 0.65 (0.09 to 0.97) 67 (21 to 204) 0.0235 (0.0166 to 0.0309) 1.00
pr_reach 0.45 (0.24 to 0.62) 0.9 5.2 (2.4 to 8.8) 0.37 (0.04 to 0.91) 37 (11 to 158) 0.0152 (0.0095 to 0.0210) 1.00
sponsorship_reach 0.57 (0.11 to 0.96) 1.2 5.1 (1.1 to 12.8) 0.50 (0.04 to 0.95) 52 (16 to 170) 0.0003 (-0.0078 to 0.0067) 0.05

Placebo check. The evidence rule can be fooled: a channel that did nothing passed it about one time in ten on simulated data. The cell below refits once with every channel shifted by a year, which keeps each channel’s pattern but breaks any link to the brand metrics. If a shifted channel still looks clear, treat channels near the threshold as unproven. Set PLACEBO = False to skip it.

placebo_clear = []
if PLACEBO:
    shifted = exog.copy()
    for ch in channels:
        shifted[ch] = np.roll(exog[ch].to_numpy(), 52)
    placebo = BayesianVECM(
        k_ar_diff=k_ar_diff,
        coint_rank=coint_rank,
        deterministic="co",
        adstock=ADSTOCK or None,
        saturation=SATURATION or None,
        contemporaneous=LINKS_USED or None,
        excluded=EXCLUDED_USED or None,
        fading=FADING or None,
    )
    with warnings.catch_warnings():
        # Shifted channels make weak instruments for the same-week link by design.
        warnings.simplefilter("ignore")
        placebo.fit(
            endog,
            exog=shifted,
            draws=500,
            tune=500,
            chains=2,
            target_accept=0.95,
            random_seed=SEED,
            progressbar=False,
        )
    placebo_table = placebo.granger_causality(ci_prob=LEVEL).exog.set_index(["cause", "effect"])
    for ch in channels:
        best = max(placebo_table.loc[(ch, m), "evidence"] for m in endog_cols)
        if best >= 0.95:
            placebo_clear.append(f"{ch} ({best:.2f})")
    check(
        "results",
        "placebo: channels shifted by a year",
        ", ".join(placebo_clear) or "none look clear",
        "ok" if not placebo_clear else "look",
        ""
        if not placebo_clear
        else "a channel that cannot have worked passed the rule: treat evidence near 0.95 as weak",
    )
NUTS[nutpie]: [alpha, beta_free, Gamma_centred, Sigma_chol, A0_links, adstock_alpha, B_total_raw, saturation_lam, B_free_raw, fade_share, fade_half_life]
[ok    ] placebo: channels shifted by a year: none look clear
if SIMULATED:
    tj = {c: list(sim.exog.columns).index(c) for c in channels}
    print("Truth on the simulated data:")
    print(
        pd.DataFrame(
            {
                "decay": [truth.adstock[tj[c]] for c in channels],
                "saturation lam": [truth.saturation[tj[c]] for c in channels],
                "lasting share": [
                    1.0 - truth.fade_share if np.isfinite(truth.fade_half_life[tj[c]]) else 1.0
                    for c in channels
                ],
                "fade half-life": [truth.fade_half_life[tj[c]] for c in channels],
                f"effect on {first}": [
                    truth.marginal_effect(c, spend_mean[c])[endog_cols.index(first)]
                    for c in channels
                ],
            },
            index=channels,
        ).round(4)
    )
Truth on the simulated data:
                   decay  saturation lam  lasting share  fade half-life  effect on brand_awareness
brand_spend          0.5             5.0            0.5            52.0                     0.0186
pr_reach             0.3             3.0            0.5            52.0                     0.0116
sponsorship_reach    0.6             5.0            0.5            52.0                     0.0064
WINDOWS = {"1 year": 52, "5 years": 260}
recent_sales = float(np.exp(endog[SALES].iloc[-52:]).mean())  # £ a week
# Weight of £1 arriving in week t, discounted at DISCOUNT a year.
DISC = (1.0 + DISCOUNT) ** (-np.arange(max(WINDOWS.values()) + 1) / 52.0)
pulse = model.exog_irf(steps=max(WINDOWS.values()))

rows = []
returns = {}
for ch, cost in CHANNELS.items():
    path = pulse.sel(response_variable=SALES, exog_variable=ch)
    path = path.stack(sample=("chain", "draw")).transpose("sample", "horizon").values
    cum = (np.expm1(path) * recent_sales * DISC).cumsum(axis=1)
    per = cost if cost else 1.0
    row = {"channel": ch, "per": "£1" if cost else "unit"}
    for label, w in WINDOWS.items():
        returns[(ch, label)] = cum[:, w - 1] / per
        row[label] = interval(returns[(ch, label)], "£{:,.2f}")
    year1 = np.median(cum[:, 51] / cum[:, -1])
    row["share in year 1"] = f"{year1:.0%}" if ch in CLEAR else "no clear effect"
    rows.append(row)
print(
    f"Return at average spend, valued at £{recent_sales:,.0f} of sales a week, "
    f"discounted at {DISCOUNT:.0%} a year"
)
pd.DataFrame(rows).set_index("channel")
Return at average spend, valued at £1,751 of sales a week, discounted at 10% a year
per 1 year 5 years share in year 1
channel
brand_spend £1 £2.18 (£1.48 to £2.96) £8.33 (£4.47 to £12.60) 25%
pr_reach unit £1,160.42 (£693.32 to £1,716.63) £3,733.48 (£1,373.43 to £6,904.22) 31%
sponsorship_reach unit £-0.96 (£-733.67 to £581.00) £99.89 (£-2,568.65 to £2,279.74) no clear effect

§5 Response curves: what a campaign is worth and how much to spend#

Objective: draw a response curve in £ for a campaign on each channel, see where the data ends, and read off how much to spend.

The plan for each channel: run it at one weekly level for CAMPAIGN_WEEKS weeks (13 by default), then return it to average. Every other driver stays at its average. The curve is the extra revenue against not running the campaign at all (the channel at zero for those weeks), so it starts at £0 and rises. Both paths use the same random draws, so only the effect of the spend is left.

Two lines per chart:

  • Within 1 year: an upper bound on what a media mix model with a few weeks of adstock credits the campaign with (the year also holds some of the brand path).

  • Within 5 years: the same campaign once the lift in the brand metrics has held sales up. The gap between the lines is the long-term effect an MMM misses.

Spend up to (the dash-dot lines, £ channels only): the campaign size where one more £1 stops bringing back the hurdle (HURDLE, £1 by default). Spending past it still adds revenue, but less than it costs. The 1-year line is near where an MMM’s optimiser would stop; the 5-year line is where to stop once the long-term effect is counted. The table after the charts gives both with intervals.

Revenue is discounted at DISCOUNT a year. Channels not in SATURATION get no “spend up to”: in a linear model every £ returns the same, so there is no point where the next £ stops paying back.

The grey bands mark weekly spend below or above any week in the data. There the curve rests on its assumed shape, so read it through its interval.

Channels with no clear effect on any brand metric get a red banner instead of a curve: the data cannot tell their return from zero, so do not plan on this model for them.

HORIZON = 260
WINDOWS = {"1 year": 52, "5 years": HORIZON}
# Weekly level as a multiple of average spend: up to 2.5x, or further if a
# flighted channel's busiest week in the data goes beyond that.
busiest = (raw[channels].max() / spend_mean)[spend_mean > 0]
TOP = float(np.clip(busiest.max() * 1.05, 2.5, 6.0)) if len(busiest) else 2.5
MULTIPLES = np.unique(np.r_[np.linspace(0, TOP, 11), 1.0])  # 1.0: current average
base_row = exog.mean().to_numpy().copy()
base_row[[names.index(c) for c in not_saturated]] = 0.0


def fit_revenue(ch, level):
    """Extra revenue (£) a week against average spend, per posterior draw."""
    j = names.index(ch)
    base = np.tile(base_row, (HORIZON, 1))
    plan = base.copy()
    plan[:CAMPAIGN_WEEKS, j] = level if ch in SATURATION else level - spend_mean[ch]
    paths = []
    for x in (base, plan):
        fc = model.sample_posterior_predictive(HORIZON, exog_future=x, random_seed=0)
        y = fc.posterior_predictive["y"].sel(variable=SALES).values
        paths.append(y.reshape(-1, HORIZON))
    return np.expm1(paths[1] - paths[0]) * recent_sales


def windows(weekly):
    """Extra revenue within each window, against no campaign (the first level)."""
    out = {}
    for label, w in WINDOWS.items():
        total = (weekly[..., :w] * DISC[:w]).sum(axis=-1)
        out[label] = total - total[0]
    return out


curves = {}
for ch in CLEAR:
    weekly = np.array([fit_revenue(ch, x) for x in MULTIPLES * spend_mean[ch]])
    curves[ch] = windows(weekly)  # window -> (level, draw)
    # A log model's losses flatten as sales near zero, and its gains grow without
    # limit, so very large moves say more about the model's form than the data.
    biggest = np.abs(np.median(curves[ch]["5 years"], axis=1)).max()
    five_years = recent_sales * 260
    if biggest > 0.5 * five_years:
        check(
            "results",
            f"{ch} curve size",
            f"up to {biggest / five_years:.0%} of 5 years of sales",
            "look",
            "a campaign moving sales this much leans on the log form: read the far ends with care",
        )


def spend_up_to(campaign, curve, hurdle):
    """Largest campaign spend where the next £ still brings back the hurdle, per draw.

    Takes the last point where the return on the next £ is at or above the hurdle, so
    a curve that rises before it bends (an S shape) is read where it falls through the
    hurdle, not at its start. 0: never pays back. inf: still above it at the top.
    """
    mid = (campaign[1:] + campaign[:-1]) / 2
    marginal = np.diff(curve, axis=0) / np.diff(campaign)[:, None]
    out = np.zeros(marginal.shape[1])
    for d in range(marginal.shape[1]):
        m = marginal[:, d]
        above = np.flatnonzero(m >= hurdle)
        if above.size == 0:
            continue  # the next £ never brings back the hurdle
        i = above[-1]
        if i == len(m) - 1:
            out[d] = np.inf
        else:
            f = (m[i] - hurdle) / (m[i] - m[i + 1])
            out[d] = mid[i] + f * (mid[i + 1] - mid[i])
    return out


def money(x, top):
    if np.isinf(x):
        return f"over £{top:,.0f}"
    return "never" if x == 0 else f"£{x:,.0f}"
[LOOK  ] brand_spend curve size: up to 63% of 5 years of sales  ->  a campaign moving sales this much leans on the log form: read the far ends with care
def true_sales(ch, plan):
    """Log sales gap when channel ``ch`` follows ``plan`` instead of its average.

    The plan is pushed through the true parameters (simulated data only),
    including the fade.
    """
    from bayesian_vecm._saturation import logistic_saturation

    j = tj[ch]
    w, lam, scale = truth.adstock[j], truth.saturation[j], truth.spend_scale[j]
    spend = sim.exog[ch].to_numpy()
    stock = spend[0]
    for x in spend[1:]:
        stock = (1 - w) * x + w * stock

    def growth(spend_path):
        a, out = stock, []
        for x in spend_path:
            a = (1 - w) * x + w * a
            out.append(truth.b_saturation[:, j] * logistic_saturation(a / scale, lam))
        return np.array(out)

    shift = growth(plan) - growth(np.full(len(plan), spend_mean[ch]))
    delta = truth.fade_decay[j]
    share = truth.fade_share if np.isfinite(truth.fade_half_life[j]) else 0.0
    pi = truth.alpha @ truth.beta.T
    y, dy, fade, sales = np.zeros(len(endog_cols)), np.zeros(len(endog_cols)), 0.0, []
    for t in range(len(plan)):
        if t > 0:
            fade = delta * fade + shift[t - 1]
        dy = pi @ y + truth.gamma @ dy + shift[t] - share * (1 - delta) * fade
        y = y + dy
        sales.append(y[0])
    return np.array(sales)


def true_revenue(ch, level):
    """Extra revenue (£) a week from the campaign plan, through the truth."""
    plan = np.full(HORIZON, spend_mean[ch])
    plan[:CAMPAIGN_WEEKS] = level
    return np.expm1(true_sales(ch, plan)) * recent_sales


true_curves = {}
if SIMULATED:
    # Only the default simulated run has a truth. With your own data this stays empty
    # and the charts and tables show the model alone.
    true_curves = {
        ch: windows(np.array([true_revenue(ch, x) for x in MULTIPLES * spend_mean[ch]]))
        for ch in CLEAR
    }
LIGHT, DARK = "#7fb0ea", "#1f5fb4"
LINES = [("1 year", LIGHT, "within 1 year"), ("5 years", DARK, "within 5 years")]
heights = [1 if ch in CLEAR else 0.25 for ch in channels]  # no-effect rows: a short banner
fig, axes = plt.subplots(
    len(channels),
    1,
    figsize=(11, 4.6 * sum(heights)),
    squeeze=False,
    gridspec_kw={"height_ratios": heights},
)
for row, ch in enumerate(channels):
    ax = axes[row, 0]
    if ch not in CLEAR:
        ax.set_axis_off()
        ax.text(
            0.0,
            0.5,
            f"{ch}: NO CLEAR EFFECT on any brand metric, so no curve is drawn.\n"
            "The data cannot tell its return from zero: do not plan its budget on this model.\n"
            "Options: more weeks of data, more variation in its spend, or drop saturation for it.",
            transform=ax.transAxes,
            fontsize=11,
            va="center",
            color="#b42318",
        ).set_in_layout(False)
        continue

    cost = CHANNELS[ch] or 1.0
    unit = "£" if CHANNELS[ch] else "units"
    campaign = MULTIPLES * spend_mean[ch] * CAMPAIGN_WEEKS * cost  # x axis: the whole campaign
    lo_data = raw[ch].min() * CAMPAIGN_WEEKS * cost
    hi_data = raw[ch].max() * CAMPAIGN_WEEKS * cost
    avg = spend_mean[ch] * CAMPAIGN_WEEKS * cost

    for window, colour, label in LINES:
        arr = curves[ch][window]
        lo, hi = np.percentile(arr, TAILS, axis=1)
        ax.fill_between(campaign, lo / 1e3, hi / 1e3, color=colour, alpha=0.2, lw=0)
        ax.plot(campaign, np.median(arr, axis=1) / 1e3, color=colour, lw=2.2, label=label)
        if ch in true_curves:
            ax.plot(
                campaign,
                true_curves[ch][window] / 1e3,
                color=colour,
                ls="--",
                lw=1,
                label=f"truth, {window} (simulated data only)",
            )
        if CHANNELS[ch] and ch in SATURATION:
            # Where the next £1 stops bringing back the hurdle: the most worth spending.
            stop = np.median(spend_up_to(campaign, arr, HURDLE))
            if np.isfinite(stop):
                ax.axvline(stop, color=colour, lw=1.6, ls="-.")
                ax.text(
                    stop,
                    0.97,
                    f" spend up to\n {window}: £{stop / 1e3:,.0f}k",
                    transform=ax.get_xaxis_transform(),
                    color=colour if window == "5 years" else "#4a7fc0",
                    fontsize=9,
                    va="top",
                )
    ax.axvline(avg, color="grey", lw=0.8, ls=":")
    ax.text(
        avg,
        0.03,
        " current\n average",
        transform=ax.get_xaxis_transform(),
        color="grey",
        fontsize=8,
        va="bottom",
    )
    ax.axvspan(campaign[0], lo_data, color="grey", alpha=0.12, lw=0)
    ax.axvspan(hi_data, campaign[-1], color="grey", alpha=0.12, lw=0)
    ax.axhline(0, color="grey", lw=0.6)
    ax.set_title(f"{ch}: what a {CAMPAIGN_WEEKS}-week campaign is worth")
    ax.set_xlabel(f"Campaign spend ({unit}, whole campaign; grey: outside the data)")
    ax.set_ylabel("Extra revenue (£k)")
    ax.legend(fontsize=8, loc="center right")
plt.tight_layout()
plt.show()
../_images/d439eb6ee5fb0c682684e00adf60367122679c923e5f0823f4435f05606d4a18.png
print(f"A {CAMPAIGN_WEEKS}-week campaign at current average spend")
rows = []
for ch in channels:
    if ch not in CLEAR:
        rows.append({"channel": ch, "note": "NO CLEAR EFFECT: no curve"})
        continue
    cost = CHANNELS[ch] or 1.0
    i = int(np.argmin(np.abs(MULTIPLES - 1)))
    spend = MULTIPLES[i] * spend_mean[ch] * CAMPAIGN_WEEKS * cost
    row = {
        "channel": ch,
        "campaign spend": f"£{spend:,.0f}" if CHANNELS[ch] else f"{spend:.1f} units",
    }
    for window in WINDOWS:
        row[f"revenue, {window}"] = interval(curves[ch][window][i], "£{:,.0f}")
        if CHANNELS[ch]:
            row[f"per £, {window}"] = interval(curves[ch][window][i] / spend, "£{:.2f}")
    rows.append(row)
display(pd.DataFrame(rows).set_index("channel").fillna(""))

print(f"\nHow much to spend: the campaign where the next £1 brings back £{HURDLE:g}")
rows = []
for ch in channels:
    if ch not in CLEAR:
        rows.append({"channel": ch, "note": "NO CLEAR EFFECT: do not plan on this model"})
        continue
    if not CHANNELS[ch]:
        rows.append({"channel": ch, "note": "no £ cost: set one in CHANNELS to get a budget"})
        continue
    if ch not in SATURATION:
        rows.append(
            {
                "channel": ch,
                "note": "linear: every £ returns the same, so no stopping point; add to SATURATION",
            }
        )
        continue
    cost = CHANNELS[ch]
    campaign = MULTIPLES * spend_mean[ch] * CAMPAIGN_WEEKS * cost
    lo_data = raw[ch].min() * CAMPAIGN_WEEKS * cost
    hi_data = raw[ch].max() * CAMPAIGN_WEEKS * cost
    best = max(drivers_table.loc[(ch, m), "evidence"] for m in endog_cols)
    row = {
        "channel": ch,
        "evidence": f"{best:.2f}",
        "current average": f"£{spend_mean[ch] * CAMPAIGN_WEEKS * cost:,.0f}",
    }
    for window in WINDOWS:
        x = spend_up_to(campaign, curves[ch][window], HURDLE)
        lo, med, hi = np.percentile(x, [TAILS[0], 50, TAILS[1]], method="nearest")
        row[f"spend up to, {window}"] = (
            f"{money(med, campaign[-1])} ({money(lo, campaign[-1])} to {money(hi, campaign[-1])})"
        )
        if ch in true_curves:
            t = spend_up_to(campaign, true_curves[ch][window][:, None], HURDLE)[0]
            row[f"truth, {window}"] = money(t, campaign[-1])
        if window == "5 years":
            if med < lo_data:
                row["in the data?"] = "no: below any week in the data"
            elif med > hi_data:
                row["in the data?"] = "no: above any week in the data"
            else:
                row["in the data?"] = "yes"
    rows.append(row)
pd.DataFrame(rows).set_index("channel").fillna("")
A 13-week campaign at current average spend
campaign spend revenue, 1 year per £, 1 year revenue, 5 years per £, 5 years note
channel
brand_spend £12,747 £52,442 (£32,097 to £71,801) £4.11 (£2.52 to £5.63) £230,385 (£119,967 to £328,587) £18.07 (£9.41 to £25.78)
pr_reach 13.6 units £24,672 (£12,831 to £45,412) £90,448 (£32,309 to £194,246)
sponsorship_reach NO CLEAR EFFECT: no curve
How much to spend: the campaign where the next £1 brings back £1
evidence current average spend up to, 1 year truth, 1 year spend up to, 5 years truth, 5 years in the data? note
channel
brand_spend 1.00 £12,747 £16,893 (£14,301 to £21,476) £15,912 £24,969 (£19,871 to over £33,190) £26,661 yes
pr_reach no £ cost: set one in CHANNELS to get a budget
sponsorship_reach NO CLEAR EFFECT: do not plan on this model

How to read the tables. The first table is what one campaign at today’s average spend is worth, and the revenue per £ it brings back within 1 and 5 years. The second is how much to spend: the campaign size where one more £1 brings back the hurdle. The 1-year column is near the answer a media mix model’s optimiser gives; the 5-year column adds the long-term effect. “Never” means not even the first £ of the campaign brings back the hurdle. “Over £X” means the return is still above the hurdle at the largest campaign tried, which is past any week in the data, so that is no licence to spend more.

Trust the second table more than the first. “How much to spend” is read where the return on the next £ crosses the hurdle, usually inside the data (the last column says when it is not). “What a campaign is worth” is measured against no campaign at all, and zero spend sits in the grey band below any week in the data, so it leans on the assumed shape of the curve.

On the simulated data (the default run) the dashed truth lines and truth columns let you check the model. Here the spend-up-to levels sit close to the truth, while the value of a whole campaign is overstated, because the model puts too much return on the first few £ (the grey band at the left). With your own data there is no truth, which is why the intervals and the grey bands matter.

§6 Going dark: what happens if a channel stops for a while#

Objective: see how sales move if a channel is switched off for DARK_WEEKS weeks (13 by default) and then returns to average spend, and whether they come back.

Every other driver stays at its average. The line is the gap in weekly sales against carrying on at average, in %, with its 90% interval, followed for FOLLOW_WEEKS weeks from the day the channel stops; dashed is the truth on the simulated data.

What happens after spend resumes depends on whether brand lifts last:

  • If every lift lasts (no FADING), the growth lost while the channel was off never comes back. Sales stop falling when spend resumes but stay below the path they were on, for good.

  • If part of each lift fades (FADING), the brand metrics also slide while the channel is off, because the fading part of past lifts is no longer topped up. When spend resumes that part rebuilds, so sales recover some of the gap; only the lost lasting share stays lost.

The gap left at the end is the cost of going dark that an MMM does not see. Switching a channel off is outside the data for any channel that was never dark, so read the line as a scenario with its interval, not a forecast.

dark = {}
for ch in CLEAR:
    j = names.index(ch)
    base = np.tile(base_row, (FOLLOW_WEEKS, 1))
    plan = base.copy()
    plan[:DARK_WEEKS, j] = 0.0 if ch in SATURATION else -spend_mean[ch]
    paths = []
    for x in (base, plan):
        fc = model.sample_posterior_predictive(FOLLOW_WEEKS, exog_future=x, random_seed=0)
        y = fc.posterior_predictive["y"].sel(variable=SALES).values
        paths.append(y.reshape(-1, FOLLOW_WEEKS))
    dark[ch] = 100 * np.expm1(paths[1] - paths[0])  # (draw, week), % of weekly sales


def dark_truth(ch):
    plan = np.full(FOLLOW_WEEKS, spend_mean[ch])
    plan[:DARK_WEEKS] = 0.0
    return 100 * np.expm1(true_sales(ch, plan))


if CLEAR:
    weeks = np.arange(1, FOLLOW_WEEKS + 1)
    fig, axes = plt.subplots(1, len(CLEAR), figsize=(6.5 * len(CLEAR), 4), squeeze=False)
    for ax, ch in zip(axes[0], CLEAR, strict=True):
        lo, hi = np.percentile(dark[ch], TAILS, axis=0)
        ax.axvspan(0, DARK_WEEKS, color="grey", alpha=0.12, lw=0, label="channel off")
        ax.fill_between(weeks, lo, hi, color="#1f5fb4", alpha=0.2, lw=0)
        ax.plot(weeks, np.median(dark[ch], axis=0), color="#1f5fb4", lw=2, label="model")
        if SIMULATED:
            ax.plot(
                weeks,
                dark_truth(ch),
                color="#1f5fb4",
                ls="--",
                lw=1,
                label="truth (simulated data only)",
            )
        ax.axhline(0, color="grey", lw=0.6)
        ax.set_title(f"{ch} off for {DARK_WEEKS} weeks, then back to average")
        ax.set_xlabel("Weeks after it stops")
        ax.set_ylabel("Weekly sales against carrying on (%)")
        ax.legend(fontsize=8)
    plt.tight_layout()
    plt.show()

rows = []
for ch in channels:
    if ch not in CLEAR:
        rows.append({"channel": ch, "note": "NO CLEAR EFFECT: not shown"})
        continue
    row = {"channel": ch}
    marks = {
        "when it restarts": DARK_WEEKS,
        "1 year on": 52,
        f"{FOLLOW_WEEKS} weeks on": FOLLOW_WEEKS,
    }
    for label, w in marks.items():
        if w <= FOLLOW_WEEKS:
            row[label] = interval(dark[ch][:, w - 1], "{:.1f}%")
    lost = -(dark[ch] / 100 * recent_sales * DISC[:FOLLOW_WEEKS]).sum(axis=1)
    row[f"sales lost over {FOLLOW_WEEKS} weeks (discounted)"] = interval(lost, "£{:,.0f}")
    if SIMULATED:
        row["truth, last week"] = f"{dark_truth(ch)[-1]:.1f}%"
    rows.append(row)
print(f"Weekly sales against carrying on, after {DARK_WEEKS} weeks off")
pd.DataFrame(rows).set_index("channel").fillna("")
../_images/ca7b59b5ecbd0d05086c2a0007efb493cc6eaa0d1e0a2fbda51df95e9ebd029e.png
Weekly sales against carrying on, after 13 weeks off
when it restarts 1 year on 156 weeks on sales lost over 156 weeks (discounted) truth, last week note
channel
brand_spend -58.3% (-89.7% to -33.1%) -71.5% (-95.2% to -42.7%) -63.7% (-93.1% to -29.0%) £153,558 (£86,994 to £212,682) -27.9%
pr_reach -26.8% (-50.7% to -14.0%) -31.0% (-61.0% to -13.2%) -22.9% (-53.0% to -4.3%) £63,982 (£26,111 to £128,742) -13.6%
sponsorship_reach NO CLEAR EFFECT: not shown

On the simulated data (the default run). Both channels show the shape a fading lift gives: sales fall while the channel is off, recover part of the gap once it is back, and settle below where they were heading because the lasting share of the lost lift stays lost. The model overstates the dip for brand spend (about 64% below at three years against a true 28%), for the same reason it overstates a whole campaign in §5: zero spend lies below any week in the data, and the model puts too much return on the first few £. The truth sits outside the band there. PR’s line holds the truth. The simulated brand gets all of its awareness growth from these channels, so the gaps are far larger than a real brand would see; the shape, not the size, is the lesson.

§7 The checks and the decision log#

Objective: keep a record of every check and choice for the write-up.

Every row marked DECIDE needs your judgement, written down before you look at the returns. Rows marked LOOK point to a fix in the agent skill’s reference/diagnostics.md or reference/pitfalls.md.

checks = pd.DataFrame(CHECKS)
print(checks.to_string(index=False))

log = [
    "# Decision log",
    "",
    f"- Data: {'simulated' if SIMULATED else DATA_PATH}, "
    f"{endog.index[0].date()} to {endog.index[-1].date()}, {len(endog)} weeks.",
    f"- Sales: `{SALES}`. Brand metrics: {', '.join(f'`{m}`' for m in BRAND_METRICS)}.",
    f"- Channels: {', '.join(f'`{c}`' for c in channels)}. Other drivers: "
    f"{', '.join(f'`{c}`' for c in OTHER_DRIVERS) or 'none'}.",
    f"- Adstock: {ADSTOCK or 'none'}. Saturation: {SATURATION or 'none'}. "
    f"Fading: {FADING or 'none (every lift lasts)'}.",
    f"- Same-week links used: {LINKS_USED or 'none'}. Exclusions: {EXCLUDED_USED or 'none'}.",
    f"- Yearly terms: {'yes' if SEASONAL else 'no'}. Discount: {DISCOUNT:.0%} a year. "
    f"Hurdle: £{HURDLE:g} per £1.",
    f"- Lags {k_ar_diff}, rank {coint_rank}, deterministic 'co', seed {SEED}, "
    f"{CHAINS} chains x {DRAWS} draws.",
    "",
    "| step | check | result | status | action |",
    "|---|---|---|---|---|",
    *[
        f"| {c['step']} | {c['check']} | {c['result']} | {c['status']} | {c['action']} |"
        for c in CHECKS
    ],
]
if not SIMULATED:
    Path("decision_log.md").write_text("\n".join(log) + "\n")
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")  # zarr notes its format 3 is still settling
        model.idata_.to_zarr("fit.zarr", mode="w")
    print("\nSaved decision_log.md and fit.zarr next to this notebook.")
    print('Reload the draws with xr.open_datatree("fit.zarr", engine="zarr").')
      step                                            check                                            result status                                                                                  action
      data                                    weeks of data                                         260 weeks     ok                                                                                        
      data                                   missing values                                                 0     ok                                                                                        
      data                                   yearly pattern                                        none added decide check the week-of-year chart: SEASONAL = True if each year rises and falls the same way
before fit                             organic_sales trends                                               yes     ok                                                                                        
before fit                           brand_awareness trends                                               yes     ok                                                                                        
before fit                       brand_consideration trends                                               yes     ok                                                                                        
before fit                             interest_rate trends                                               yes     ok                                                            entered as its weekly change
before fit                       budgets follow performance                                 no feedback found     ok                                                                                        
before fit same-week brand_awareness -> brand_consideration no clear evidence, 2SLS 0.25, F 17, Sargan p 0.60     ok                                                                                    kept
before fit               exclusions for brand_consideration          brand_spend, pr_reach, sponsorship_reach decide                              confirm each reaches it only through the cause; record why
before fit                                 lags (k_ar_diff)                                                 1     ok                                                                       from Hannan-Quinn
before fit                             long-run ties (rank)                          test 2, funnel 2, used 2     ok                                                                                        
       fit                                      divergences                                                 0     ok                                                                                        
       fit                                        max r-hat                                             1.010     ok                                                                                        
       fit                                     min bulk ESS                                               866     ok                                                                                        
       fit                         residual autocorrelation                                        none at 1%     ok                                                                                        
   results                         sponsorship_reach effect              no clear effect (best evidence 0.68)   look      its curve is not drawn: more data, more spend variation, or drop saturation for it
   results              placebo: channels shifted by a year                                   none look clear     ok                                                                                        
   results                           brand_spend curve size                     up to 63% of 5 years of sales   look    a campaign moving sales this much leans on the log form: read the far ends with care

How far to trust the answers#

  • Only the long-run return is robust to how base sales were built. Adjustment speeds and half-lives depend on it (guides 06 and 07).

  • The curve for one channel holds the others at average. Channels flighted together are hard to separate. Plan changes to one channel at a time where you can.

  • Outside the grey bands the curve is an assumption. A switch-off or a doubling beyond any week in the data is a guess at the shape. Report its interval, not a single number.

  • Whether brand lifts last is the biggest assumption in the 5-year numbers. With FADING the model estimates the lasting share, but five years of data pin it down only loosely, so the 5-year returns and the going-dark lines carry wide intervals. Without it every lift lasts by assumption. On simulated data where lifts fade, the model without FADING overstated 5-year returns two to six times with intervals that missed the truth (tools/fade_check.py).

  • Exclusions are business assumptions. The same-week link rests on them, and the data can catch only some wrong ones.

  • Prediction is not proof of cause. The evidence scores say what helps predict what, under the assumptions in the decision log.

  • Rerun before reporting with FINAL_RUN = True, and quote numbers from the saved fit.zarr. The sampler is not bit-for-bit reproducible.