Media mix modelling in Python: adstock, saturation and where the budget goes
TL;DR
Difficulty: Advanced
A media mix model turns two years of weekly spend and revenue into a marginal ROI per channel, and in Python it needs only NumPy and SciPy.
- Put spend in the week people saw it and orders in local weeks, and load extra months of spend to warm up the adstock.
- Adstock is a first order filter, a Hill curve gives diminishing returns, and priors are simply extra residuals in least_squares.
- Bound the optimiser by the spend range each channel has seen: free, it cut search to zero and promised €4,833 a week. Bounded, it moved 15% of the budget for €2,520 (planted truth €2,373).
- The decision is surer than the numbers: search's total contribution ranged eightfold across 200 refits, yet its next euro fell below break even in every one.
A media mix model tells you where the next euro of marketing budget should go, using nothing but weekly totals. This chapter builds the model from my Marketing Analytics series in Python, line by line, on 104 weeks of generated data from an invented Cork hamper shop, and because the true answer is planted in the data, it also shows which of the model's outputs you can trust and which you cannot.
If you only read one section
A media mix model takes two years of weekly totals, spend per channel and revenue, and estimates how much revenue each channel caused. It gives every channel a memory (adstock) and a curve of diminishing returns (saturation), and from those it computes the number that decides a budget: the marginal return on investment, the revenue the next euro would bring.
This chapter builds one in Python from scratch, on data you generate yourself, so every line runs. Because the data is generated, the right answer is known, and that lets me check what a media mix model can and cannot tell you. Three findings from that check are the reason to read on, and they matter more than any line of code:
- The decision is surer than the numbers behind it. I refitted the model 200 times on resampled versions of the same data. The weekly revenue it credits to paid search swung from €630 to €5,580 across the middle 80% of refits, an eightfold range. Yet in every one of the 200 refits the next euro in search returned less than break even, and in 199 of them less than the next euro in social and in email. The recommended budget move added between €1,330 and €3,210 a week. Report the move and its interval. Do not report the pie chart of who caused what.
- A channel that never stops cannot tell you what it is worth in total. Search never dropped below €2,860 a week, so the data has never seen what happens without it. The model handed a large part of search's work to the baseline: it estimated search at €2,800 a week when the true figure planted in the data was €6,770. The catalogue, which sits idle for months between drops, was estimated within a few hundred euro. The interval did not even contain the truth for search, because a bootstrap measures noise, not a wrong assumption about zero spend.
- Let history set the optimiser's limits. Left to itself, the optimiser cut search to zero and promised €4,833 more revenue a week. Held to the spend range each channel has actually seen, it moved 15% of the budget and promised €2,520. The planted truth for that move is €2,373.
Two data traps come before any of that, and both take a few lines of pandas to fix: spend belongs to the week people saw it, not the week finance booked the invoice, and the adstock needs a few months of earlier spend to warm up, or the first weeks of the model have no memory.
The question, and where the concepts are explained
The reader's question for this chapter: how do I build a simple media mix model in Python with adstock and saturation, and use it to split a budget?
The concepts are explained in my Marketing Analytics chapter Media mix modelling: adstock, saturation and where the next euro goes. That chapter takes its time over the ideas: why attribution cannot see a catalogue, what a half life means for a channel, why the Hill curve bends, why branded search collects demand that other channels create, and how a geo test keeps the model honest. Here I build it, line by line. The two chapters use the same shop, the same four channels and the same planted parameters, so they read as a pair: one for the thinking, one for the doing.
Several earlier chapters carry weight here. Time series in pandas covers weekly periods and time zones, which decide which week a euro and an order belong to. Distributed lags in Python measured how long one channel keeps working, with a flexible lag curve. This chapter replaces that curve with the simpler geometric memory, so four channels can be modelled at once. Statistical models in Python introduced statsmodels, and simultaneous equations in Python is the full answer to search spend that follows the other channels. A/B tests in Python is the experimental side that a media mix model needs as its referee.
Example: Northgate Hampers and the budget nobody can settle
Priya runs Northgate Hampers, an invented online hamper shop in Cork at northgatehampers.example, the shop from the Marketing Analytics chapter. Nothing about it is real, and every number is made up so I can show each step. She spends about €8,000 a week on four channels: paid search about €4,000, paid social about €2,000, email about €700 in tooling and creative, and a printed catalogue that goes to 40,000 households twice a year and works out at about €1,300 a week. Gross margin on hampers is 45%.
Her attribution report gives paid search most of the tracked revenue and the catalogue nothing, because nobody clicks on paper. Her question is the analyst's standing question in this programme, applied to one shop: which channel really pays back, and what should next month's budget look like?
The data below is generated to resemble the example in the Marketing Analytics chapter. The true half lives, saturation points and maximum effects planted in it are exactly the ones in that chapter's table. The noise, the spend pattern and a catalogue that goes quiet between drops are mine, which is why the average week here brings about €35,900 of revenue rather than the €38,000 there.
What you need, as of August 2026
Everything here runs on Python 3.14 with pandas 3.0, NumPy 2.5, SciPy 1.18 and statsmodels 0.14.6, the current releases at the time of writing. If you have not set Python up yet, the setup chapter walks through it. The model itself needs only NumPy and SciPy: no probabilistic programming library, no GPU. That is deliberate. You should be able to see every moving part before you hand the job to a package.
One pandas change matters for code like this. Since pandas 3.0, released on 21 January 2026, copy on write is the only behaviour, so a column you pull out of a DataFrame behaves as a copy and "chained assignment" such as df["revenue"][0] = 0 changes nothing.1 Assign with df.loc[...], as the blocks below do. Wes McKinney's book, whose 2022 edition is the standard introduction to these libraries, predates that change.2
import numpy as np
import pandas as pd
import scipy
import statsmodels
import statsmodels.api as sm
from scipy.signal import lfilter
from scipy.optimize import least_squares, minimize
print(pd.__version__, np.__version__, scipy.__version__, statsmodels.__version__)
3.0.5 2.5.2 1.18.0 0.14.6
Spend belongs to the week people saw it
A media mix model is a regression of weekly revenue on weekly spend. If a euro lands in the wrong week, the model learns the wrong timing, and no amount of statistics afterwards can repair it. The most common way a euro lands in the wrong week is that the spend comes from the finance export, which records when an invoice was booked, not when anyone saw the advert.
For digital channels the difference is small: Google Ads and Meta report spend by the day the ads ran. For anything printed, posted or prepaid it is large. A catalogue is invoiced when it is printed, weeks before it lands on a doormat. An email tool bills monthly, whatever you send. Loading the ad platform reports themselves, with their header blocks, totals rows and account currencies, is covered in loading business data into pandas. Here the job is to put every euro into its exposure week.
Example: the catalogue invoice that arrived three weeks early
Northgate's October catalogue cost €34,000 for print and post. Finance booked the invoice on Friday 20 September 2024. The catalogue landed on Monday 7 October. Weeks run Monday to Sunday and are labelled by their Monday, which in pandas is the weekly period ending on Sunday.
# What finance exports: the catalogue invoice and the email tool's monthly bill
costs = pd.DataFrame({
"booked": pd.to_datetime(["2024-09-20", "2024-10-01"]),
"item": ["Catalogue print and post, October drop", "Email tool, October"],
"amount": [34000.0, 700.0],
})
# What the marketing calendar knows: when people actually saw it
costs["exposed"] = pd.to_datetime(["2024-10-07", "2024-10-01"])
# Weeks run Monday to Sunday, labelled by their Monday
costs["week_booked"] = costs["booked"].dt.to_period("W-SUN").dt.start_time
costs["week_exposed"] = costs["exposed"].dt.to_period("W-SUN").dt.start_time
print(costs[["item", "week_booked", "week_exposed"]])
item week_booked week_exposed
0 Catalogue print and post, October drop 2024-09-16 2024-10-07
1 Email tool, October 2024-09-30 2024-09-30
Booked, the catalogue sits in the week of 16 September, three weeks before any household had it. A model fed that column would see €34,000 of spend followed by three ordinary weeks and conclude the catalogue does nothing, then see the October bump arrive with no spend and credit it to whatever else was running. The fix is not statistical. It is a drop calendar, one row per mailing with the date it landed, kept by whoever sends the catalogue. The email tool is the opposite case: a flat monthly fee has no weekly variation at all, so it cannot be measured as spend. For email, model sends or emails delivered per week, and convert to euro afterwards.
Orders belong to the week the customer lived it
Revenue has its own version of the trap. Shop exports store order times in UTC (Coordinated Universal Time), and a week that starts at midnight UTC is not the week your customer lived. In Irish summer time, everything between 11pm and midnight UTC on a Sunday belongs to the next week in local time.
Example: one late Sunday order
# One order from the shop export, stored in UTC
order_utc = pd.Timestamp("2025-06-29 23:30", tz="UTC")
order_local = order_utc.tz_convert("Europe/Dublin")
print(order_utc.tz_localize(None).to_period("W-SUN").start_time.date(),
order_local.tz_localize(None).to_period("W-SUN").start_time.date())
2025-06-23 2025-06-30
In UTC the order falls in the week of 23 June. In Cork it was 12.30am on Monday 30 June, the next week. One order is neither here nor there. A newsletter sent on Sunday evenings moves a slice of every send's revenue into the wrong week, every week, and the model learns a memory the channel does not have. Convert to local time first, then build the weeks, as time series in pandas does in full.3 And use revenue net of refunds, booked to the week of the original order, so a returns wave in January does not look like a January slump in media.
Adstock: give each channel a memory
A catalogue keeps selling for weeks after it lands. A search click mostly converts the same week. Adstock turns raw spend into a stock that builds up when you spend and decays when you stop. The simplest form is the geometric recursion that Google's researchers used in their 2017 paper on Bayesian media mix models:4
is the adstock in week , is the spend in that week, is last week's adstock, is the retention rate, the share of last week's stock that survives into this week, and is the half life in weeks, the time it takes a burst to lose half its effect (Foundations: percentages). A half life of one week means , half the stock survives each week. A half life of four weeks means . The Marketing Analytics chapter explains why I talk to clients in half lives and never in . Here the point is how little code it takes.
Example: one burst of 100, two half lives
def adstock(x, half_life):
"""Geometric adstock: A[t] = x[t] + lam * A[t-1], with lam = 0.5 ** (1 / half_life)."""
lam = 0.5 ** (1 / half_life)
a = np.zeros(len(x))
for t in range(len(x)):
a[t] = x[t] + (lam * a[t - 1] if t > 0 else 0.0)
return a
burst = np.zeros(13)
burst[0] = 100
print(adstock(burst, 1).round(1)[:5])
print(adstock(burst, 4).round(1)[:5])
[100. 50. 25. 12.5 6.2]
[100. 84.1 70.7 59.5 50. ]
With a one week half life the effect halves every week. With a four week half life it takes four weeks to reach 50. Those are the numbers in the Marketing Analytics chapter's adstock chart, now produced by eight lines of Python.
The loop is easy to read, but it runs once per week per channel, and a model fit calls it thousands of times. The same recursion is a first order linear filter, which SciPy computes in compiled code: lfilter(b, a, x) solves , so b = [1] and a = [1, -lam] give exactly the adstock.5
def adstock_fast(x, half_life):
lam = 0.5 ** (1 / half_life)
return lfilter([1.0], [1.0, -lam], x)
x = np.random.default_rng(1).uniform(0, 5000, 200)
print(np.allclose(adstock(x, 0.6), adstock_fast(x, 0.6)))
True
Keep the loop version for explaining, and use the fast one inside the model.
Saturation: the second euro buys less than the first
The second ingredient is diminishing returns. Most media mix models use the Hill curve, which the same Google paper uses for the shape effect:4
is the saturated response between 0 and 1, is the adstock, is the half saturation point, the adstock at which a channel delivers half its maximum effect, and sets the shape: at or below 1 the curve bends from the first euro, above 1 it starts slowly and then flattens, an S shape. A channel's weekly revenue is , where is the most weekly revenue the channel could ever add. Where the curve flattens, each extra euro adds less than the one before, which is the difference between the marginal and the average return (Foundations: marginal versus average).
One more piece of algebra turns this into budget language. If you spend the same every week, the adstock settles at , because each week's euro is joined by what is left of all the earlier ones. That steady state is what "spend €4,000 a week" means to the model. Worked through for search at the planted values: , so a steady €4,000 a week gives an adstock of , and . Search runs at 72% of its €9,500 maximum.
Example: the Marketing Analytics table, reproduced
The parameters below are the ones in the Marketing Analytics chapter: half life, , and for each channel. They are also the answer I will plant in the generated data.
def hill(a, K, alpha):
"""Hill saturation: 0 at no adstock, 0.5 at a = K, approaching 1 far above K."""
return a ** alpha / (a ** alpha + K ** alpha)
def steady_state(spend_per_week, half_life, K, alpha, beta):
lam = 0.5 ** (1 / half_life)
a = spend_per_week / (1 - lam) # adstock of a constant weekly spend
return a, beta * hill(a, K, alpha)
# The answer planted in the data: half life (weeks), K, alpha, beta (max weekly revenue in euro)
TRUE = {
"search": (0.6, 2800, 1.3, 9500),
"social": (2.0, 9000, 1.6, 17000),
"email": (1.0, 2600, 1.5, 7000),
"catalogue": (5.0, 2000, 2.2, 5000),
}
for c, x in [("search", 4000), ("social", 2000), ("email", 700), ("catalogue", 1300)]:
a, rev = steady_state(x, *TRUE[c])
print(f"{c:<10} spend {x:>5} adstock {a:>7,.0f} share of max {rev / TRUE[c][3]:.0%} revenue {rev:>6,.0f}")
search spend 4000 adstock 5,839 share of max 72% revenue 6,861
social spend 2000 adstock 6,828 share of max 39% revenue 6,652
email spend 700 adstock 1,400 share of max 28% revenue 1,983
catalogue spend 1300 adstock 10,043 share of max 97% revenue 4,860
Every figure matches the Marketing Analytics chapter: search at 72% of its maximum and €6,860 a week, social at 39% and €6,650, email at 28%, the catalogue at 97%. Search is far up its curve and social is still on the steep part. That gap is the whole reason a reallocation can pay.
Step 1: generate two years of weekly data, plus a warm up
Every chapter in this programme generates its own data, so you can copy the blocks in order into a notebook and get my outputs. The generator plants the parameters above inside realistic weekly noise and adds the things that move revenue regardless of media: the run up to Christmas, two promotion weeks, a price rise in the second year and one week of checkout trouble.
It also builds in the second data trap. Adstock is a running sum, so in the first week of your data it knows nothing about the spend before it. A catalogue that landed a month before your window starts is still selling, and the model will credit those sales to something else. The fix is to load spend from a few months before the revenue window and use those weeks only to warm the memory up. Here that is 16 extra weeks, enough for even the catalogue's five week half life to settle (after 16 weeks, about 11% of a burst is left).
Example: 104 weeks of spend and revenue at Northgate
rng = np.random.default_rng(63) # fixed seed: the same numbers on every run
warm, n = 16, 104 # 16 warm up weeks of spend, then 104 modelled weeks
N = warm + n
weeks = pd.date_range("2024-04-15", periods=N, freq="W-MON") # each week starts on a Monday
# Calendar controls
christmas = (((weeks.month == 11) & (weeks.day >= 10)) |
((weeks.month == 12) & (weeks.day <= 21))).astype(int)
promo = np.zeros(N, dtype=int)
promo[[warm + 30, warm + 82]] = 1 # two promotion weeks
price_change = (np.arange(N) >= warm + 60).astype(int) # prices up from week 61
site_outage = np.zeros(N, dtype=int)
site_outage[warm + 47] = 1 # one week of checkout trouble
# Spend per week in euro, already in exposure weeks
drops = pd.to_datetime(["2024-10-07", "2024-11-25", "2025-10-06", "2025-11-24"])
catalogue = np.where(weeks.isin(drops), 34000.0, 0.0) # four catalogue drops
after_drop = np.zeros(N)
for d in drops: # search bids go up when a catalogue lands
i = weeks.get_loc(d)
after_drop[i:i + 3] = 1
social = np.round(rng.uniform(1150, 2850, N), -1)
email = np.round(rng.uniform(280, 1120, N), -1)
search = np.round(rng.uniform(2810, 4700, N) + 1300 * christmas + 500 * after_drop, -1)
spend = {"search": search, "social": social, "email": email, "catalogue": catalogue}
base = (17000 + 9000 * christmas + 5000 * promo
- 1200 * price_change - 6000 * site_outage)
media = sum(b * hill(adstock(spend[c], h), K, al) for c, (h, K, al, b) in TRUE.items())
revenue = base + media + rng.normal(0, 1300, N)
weekly = pd.DataFrame({
"week": weeks, **spend,
"christmas": christmas, "promo": promo,
"price_change": price_change, "site_outage": site_outage,
"revenue": np.round(revenue, -1),
}).set_index("week")
weekly.loc[weekly.index[:warm], "revenue"] = np.nan # no revenue in the warm up weeks
model_weeks = weekly.iloc[warm:]
print(model_weeks[["search", "social", "email", "catalogue", "revenue"]]
.describe().round(0).loc[["mean", "min", "max"]])
search social email catalogue revenue
mean 3930.0 2028.0 681.0 1308.0 35875.0
min 2860.0 1180.0 280.0 0.0 27040.0
max 6360.0 2850.0 1110.0 34000.0 49240.0
Read the table the way Priya would. Search never went below €2,860 a week, so nobody has seen Northgate without search. Social moved between €1,180 and €2,850, email between €280 and €1,110. The catalogue is zero in 100 weeks and €34,000 in four. Revenue averages about €35,900 a week, of which the planted baseline, the revenue with no media at all, is about €17,600.
Two details in the generator are worth noticing. Search spend rises in the three weeks after each catalogue drop, because Priya raises her bids when branded searches jump. And search rises at Christmas, as do sales. Both are true of real shops, and both make search hard to measure, as you will see.
Step 2: the obvious regression, and why it misleads
Before building anything clever, look at what the plain approach says: regress revenue on this week's raw spend, with the controls. It is what a spreadsheet trend line does, and it is the number someone in the room will already have.
Example: revenue on raw spend
y = model_weeks["revenue"]
naive_X = sm.add_constant(model_weeks[["search", "social", "email", "catalogue",
"christmas", "promo", "price_change", "site_outage"]])
naive = sm.OLS(y, naive_X).fit()
print(naive.params[["search", "social", "email", "catalogue"]].round(2))
search 0.28
social 1.27
email 2.71
catalogue -0.00
dtype: float64
The catalogue earns nothing per euro, because the regression only sees €34,000 in the drop week and none in the five weeks of sales that follow. Social looks barely profitable at €1.27 per euro, because half its effect lands in later weeks. These coefficients are not wrong arithmetic. They answer a question nobody asked: what happens to this week's revenue when this week's spend changes, with no memory and no curve. Every number in the rest of the chapter exists to replace them.
Step 3: a quick OLS version, and what it cannot settle
The fastest real media mix model keeps ordinary least squares (OLS) and moves the nonlinear parts outside it. Pick a half life for each channel from a small grid, transform spend with adstock and a log curve, fit OLS with the controls, and keep the combination with the best fit. The log curve , with the average adstock, is a common stand in for saturation when data is thin, because it has no parameters to estimate. It is the kind of model you can build in an afternoon, and it is worth building first, because of what it shows you.
Example: 120 regressions and a grid that runs off its edge
from itertools import product
controls = model_weeks[["christmas", "promo", "price_change", "site_outage"]]
grid = {"search": [0.5, 1], "social": [1, 2, 3], "email": [0.5, 1, 2], "catalogue": [2, 3, 5, 8, 12]}
results = []
for hl in product(*grid.values()):
cols = {}
for c, h in zip(grid, hl):
a = adstock_fast(weekly[c].to_numpy(), h)[warm:] # warm up, then cut
cols[c] = np.log1p(a / a.mean()) # log saturation
Xg = sm.add_constant(pd.concat([pd.DataFrame(cols, index=model_weeks.index), controls], axis=1))
fit = sm.OLS(y, Xg).fit()
results.append({**dict(zip(grid, hl)), "sse": fit.ssr, "aic": fit.aic})
results = pd.DataFrame(results).sort_values("aic")
print(results.head(3).round(1))
print(results.groupby("catalogue")["aic"].min().round(1))
search social email catalogue sse aic
34 0.5 3 0.5 12 278168555.8 1852.3
79 1.0 3 0.5 12 279694506.4 1852.8
39 0.5 3 1.0 12 281218980.6 1853.4
catalogue
2 1905.3
3 1892.7
5 1871.4
8 1854.8
12 1852.3
Name: aic, dtype: float64
AIC, the Akaike information criterion, scores the fit with a penalty for complexity, and lower is better. The best catalogue half life is 12 weeks, the largest on the grid, and social's best is 3, also the largest. The planted values are five and two. A best value on the edge of a grid is a warning, not a result. Here the cause is the curve: the log form never saturates, so the model cannot express "the catalogue is already at 97% of its maximum", and it compensates with a memory that is far too long. The memory and the curve trade off against each other, and a wrong curve buys a wrong memory.
That is the lesson of the quick version: with 104 weeks, the data alone cannot pin a half life and a curve for four channels at once. The full model needs the curve and something to hold the parameters in a sensible region.
Step 4: priors are extra rows of residuals
The full model has four parameters per channel (half life, , , ), a baseline and four controls: 21 numbers from 104 weeks, most of them quiet summer weeks. Least squares on its own will happily return a 40 week half life or a shape no channel could have. The Marketing Analytics chapter fits it the Bayesian way, with priors: what you believed before seeing the data, written down. You do not need a Bayesian library to use that idea. A prior can be written as one more residual.
is the list of all parameters, is revenue in week , is the model's prediction for that week, is the number of modelled weeks (104), and is the typical size of the weekly noise. The second sum runs over the parameters that have a prior, each with a prior centre and a prior spread . The first sum is ordinary least squares. The second says: every step away from what you believed costs as much as a weekly miss of one noise unit per prior spread. With normal priors, the minimum of this sum is the posterior mode, the single most probable set of parameters, and in the linear case it is exactly ridge regression.6 Regression itself is built from scratch on the Foundations page.
SciPy's least_squares minimises a sum of squared residuals with bounds on each parameter, so the whole model is one function that returns the weekly residuals with the prior residuals appended.7
Example: Priya's priors, written as code
Priya's beliefs before looking at the data: search carryover is short, a half life around 0.7 weeks. Social around two weeks, email around one, the catalogue around five. Each within a factor of about 1.6 either way. For the half saturation point she has no view, so the prior sits at each channel's median weekly adstock with a wide spread, a neutral "half way" guess. For the shape, around 1.5. The bounds keep every effect positive.
CHANNELS = ["search", "social", "email", "catalogue"]
X_spend = {c: weekly[c].to_numpy() for c in CHANNELS}
Z = np.column_stack([np.ones(N), christmas, promo, price_change, site_outage])
y_all = weekly["revenue"].to_numpy()
fit_rows = np.arange(warm, N) # the 104 modelled weeks
# Priors: what Priya believed before looking at the data
PRIOR_HALF_LIFE = {"search": 0.7, "social": 2.0, "email": 1.0, "catalogue": 5.0}
# K prior: the median weekly adstock, a neutral "half way" guess
PRIOR_K = {c: np.median(adstock_fast(X_spend[c], PRIOR_HALF_LIFE[c])[warm:]) for c in CHANNELS}
NOISE_SD = 1300.0 # rough weekly noise, from a first simple fit
def unpack(p):
pars = {c: (np.exp(p[4 * i]), np.exp(p[4 * i + 1]), p[4 * i + 2], p[4 * i + 3])
for i, c in enumerate(CHANNELS)}
return pars, p[16:]
def predict(p, parts=False):
pars, gamma = unpack(p)
contrib = {c: b * hill(adstock_fast(X_spend[c], h), K, al) for c, (h, K, al, b) in pars.items()}
base = Z @ gamma
return (base, contrib) if parts else base + sum(contrib.values())
def residuals(p, y_obs, rows):
data = (y_obs[rows] - predict(p)[rows]) / NOISE_SD
prior = []
for i, c in enumerate(CHANNELS):
log_h, log_K, alpha = p[4 * i], p[4 * i + 1], p[4 * i + 2]
prior += [(log_h - np.log(PRIOR_HALF_LIFE[c])) / 0.5, # half life within about x1.6
(log_K - np.log(PRIOR_K[c])) / 1.0, # K within about x2.7
(alpha - 1.5) / 0.5] # shape around 1.5
return np.r_[data, prior]
p0, lo, hi = [], [], []
for c in CHANNELS:
p0 += [np.log(PRIOR_HALF_LIFE[c]), np.log(PRIOR_K[c]), 1.5, 8000]
lo += [np.log(0.2), np.log(200), 0.5, 0]
hi += [np.log(12), np.log(60000), 3.5, 60000]
p0 += [15000, 5000, 3000, 0, 0]
lo += [-np.inf] * 5
hi += [np.inf] * 5
print({c: round(k) for c, k in PRIOR_K.items()})
{'search': 6096, 'social': 6907, 'email': 1408, 'catalogue': 3617}
Three choices in that block are worth copying. The half life and are estimated on the log scale, so "within a factor of 1.6" is a symmetric spread and neither can turn negative. The adstock is computed over all 120 weeks, warm up included, but only the 104 modelled weeks enter the residuals. And the noise scale is fixed at a rough value from a first fit. It only sets how strongly the priors pull, so being roughly right is enough.
Step 5: fit the model and compare it with the planted truth
Example: Northgate's fitted parameters
fit = least_squares(residuals, p0, bounds=(lo, hi), args=(y_all, fit_rows))
pars, gamma = unpack(fit.x)
est = pd.DataFrame(pars, index=["half_life", "K", "alpha", "beta"]).T
est["half_life_true"] = [TRUE[c][0] for c in CHANNELS]
est["beta_true"] = [TRUE[c][3] for c in CHANNELS]
print(fit.status, est.round(2))
print(dict(zip(["base", "christmas", "promo", "price_change", "site_outage"], gamma.round(0).tolist())))
2 half_life K alpha beta half_life_true beta_true
search 0.49 4615.20 1.52 5198.71 0.6 9500
social 2.36 9756.07 1.52 18060.15 2.0 17000
email 0.82 1963.22 1.58 5461.84 1.0 7000
catalogue 5.13 1837.51 1.82 5487.96 5.0 5000
{'base': 19889.0, 'christmas': 8695.0, 'promo': 4401.0, 'price_change': -1103.0, 'site_outage': -5403.0}
The fit takes a fraction of a second. Status 2 means it stopped because the improvement became negligible, which is what you want. Now read it against the truth, which in real life you never see.
The half lives are close: 0.49 against 0.6 for search, 2.36 against 2 for social, 0.82 against 1 for email, 5.13 against 5 for the catalogue. The controls are close too: Christmas adds €8,695 against a planted €9,000, the outage costs €5,403 against €6,000. The shapes all sit near 1.5, which is simply the prior: 104 weeks of data cannot tell an of 1.3 from 1.6, and the honest reading is that the shape came from Priya, not from the data.
The interesting miss is search. Its maximum effect is €5,199 against a true €9,500, and the baseline is €19,889 against a true €17,000. The model has moved roughly €2,900 a week of search's work into the baseline. Hold that thought until the decomposition.
Step 6: check the model on weeks it never saw
A model that cannot forecast cannot allocate. The Marketing Analytics chapter's first check is to hold out the last twelve weeks, fit on the rest and see whether the model predicts them within about 10%. The second is to look at the residuals for structure, which would mean a missing control.
Example: twelve hidden weeks and the residuals
train = np.arange(warm, N - 12)
test = np.arange(N - 12, N)
fit_train = least_squares(residuals, p0, bounds=(lo, hi), args=(y_all, train))
forecast = predict(fit_train.x)[test]
mape = np.mean(np.abs(forecast - y_all[test]) / y_all[test])
print(f"Holdout error, last 12 weeks: {mape:.1%}")
res = y_all[fit_rows] - predict(fit.x)[fit_rows]
from statsmodels.stats.stattools import durbin_watson
print(f"Lag 1 autocorrelation of residuals: {np.corrcoef(res[:-1], res[1:])[0, 1]:.2f}")
print(f"Durbin Watson: {durbin_watson(res):.2f}")
Holdout error, last 12 weeks: 4.2%
Lag 1 autocorrelation of residuals: -0.26
Durbin Watson: 2.50
The model misses the twelve hidden weeks by 4.2% on average, measured as the mean absolute percentage error, well inside 10%. The residuals show no positive carryover from week to week: the Durbin Watson statistic is 2.5, and values well below 2 would mean a slow effect the model is missing, such as a trend or a channel with too short a memory.8 On real data I also plot the residuals by week and look hard at the Christmas weeks. Showing time in the data storytelling series covers how to draw that so the pattern is visible.
Notice what the holdout did not catch. The model forecasts well while crediting search with half its true effect. Good forecasts only prove that the model's total is right. They say nothing about how the total is split between the baseline and a channel that is always on.
Step 7: decompose revenue into base and channels
The decomposition is the chart everyone asks for: how much of an average week came from the baseline and how much from each channel. In code it is the model's prediction split into its parts.
Example: estimated against planted
base_hat, contrib_hat = predict(fit.x, parts=True)
decomp = pd.DataFrame({"base": base_hat, **contrib_hat}, index=weekly.index).iloc[warm:]
true_contrib = {c: b * hill(adstock_fast(X_spend[c], h), K, al) for c, (h, K, al, b) in TRUE.items()}
planted = pd.DataFrame({"base": base, **true_contrib}, index=weekly.index).iloc[warm:]
print(pd.DataFrame({"estimated": decomp.mean(), "planted": planted.mean()}).round(-1))
estimated planted
base 20460.0 17570.0
search 2800.0 6770.0
social 7620.0 6710.0
email 1690.0 1910.0
catalogue 3310.0 2900.0
The catalogue, social and email land within €1,000 of the truth. Search does not: €2,800 against €6,770. The reason is in the spend table from step 1. Search never dropped below €2,860. Every week of data has search running, so "revenue with no search" is an extrapolation along the curve to a point nobody has observed, and the baseline and the search curve can trade revenue between them with almost no change in fit. The catalogue is the opposite: it is zero for months at a time, so the data shows exactly what the shop does without it.
That gives a rule I use for every decomposition: a channel's total contribution is only as trustworthy as the variation you have seen down to zero. An always on channel's share of revenue is a modelling assumption. Show it, if you must, with that sentence next to it. And show it as bars, not a pie: a pie claims the parts are known and add up, which here they do only in total (showing amounts and proportions has the longer argument).
Step 8: response curves and the marginal return
The decision number is not the share. It is the marginal return on investment (marginal ROI): how much revenue the next euro of weekly spend brings, at today's spend. With the steady state adstock , it is the derivative of the channel's revenue with respect to its weekly spend:
is the channel's weekly revenue, its weekly spend, the steady state adstock at that spend, , and the Hill parameters and the retention rate. The middle factor is the slope of the Hill curve, and the last factor converts one more euro a week into its steady state adstock. It is the gap between the marginal and the average return (Foundations: marginal versus average).
A euro of spend has to bring back more than one euro of gross profit. At a 45% gross margin that means the break even return in revenue is (Foundations: ratios and rates). Any channel whose next euro returns less than €2.22 of revenue is losing money at the margin, however good its average looks.
Example: Northgate's marginal returns at today's plan
The plan Priya is about to repeat: €4,000 search, €2,000 social, €700 email, €1,300 catalogue. The check column computes the same thing numerically, as the revenue from one extra euro, which catches any slip in the algebra.
def response(x, c, pars):
return steady_state(x, *pars[c])[1]
def marginal_roi(x, c, pars):
h, K, al, b = pars[c]
lam = 0.5 ** (1 / h)
a = x / (1 - lam)
return b * al * K ** al * a ** (al - 1) / (a ** al + K ** al) ** 2 / (1 - lam)
plan = {"search": 4000, "social": 2000, "email": 700, "catalogue": 1300}
table = pd.DataFrame({
"spend": plan,
"revenue": {c: response(plan[c], c, pars) for c in CHANNELS},
"avg_roi": {c: response(plan[c], c, pars) / plan[c] for c in CHANNELS},
"marginal_roi": {c: marginal_roi(plan[c], c, pars) for c in CHANNELS},
"check": {c: response(plan[c] + 1, c, pars) - response(plan[c], c, pars) for c in CHANNELS},
})
print(table.round(2))
spend revenue avg_roi marginal_roi check
search 4000 2863.91 0.72 0.49 0.49
social 2000 7563.50 3.78 3.34 3.33
email 700 1765.15 2.52 2.69 2.69
catalogue 1300 5257.95 4.04 0.31 0.31
The estimates sit close to the Marketing Analytics chapter's: search 0.49 against 0.62 there, social 3.34 against 3.24, email 2.69 against 3.05, the catalogue 0.31 against 0.23. The ranking is identical. Social and email return more than break even on the next euro. Search returns 49 cent, which at a 45% margin is about 22 cent of gross profit for every euro spent. The catalogue's marginal number deserves the Marketing Analytics chapter's warning: it only ever varied between nothing and a full drop, so its curve between those points is mostly prior. Leave it alone and test it.
Notice that search's marginal ROI, the number the decision rests on, is much closer to the truth than its contribution. The slope at €4,000 is something the data has seen, because spend moved between €2,860 and €6,360. The level at zero is not.
Step 9: reallocate within the range history has seen
With the curves in hand, the budget question becomes an optimisation: split the movable budget between search, social and email so that total modelled revenue is as high as possible, with the catalogue fixed at €1,300 because a print run cannot change in a month. SciPy's minimize with the SLSQP method handles bounds and an equality constraint, here "the three channels add up to €6,700".9
The question is which bounds. An optimiser trusts the curve everywhere, including at spend levels nobody has ever tried. So I give it the range each channel has actually seen, rounded inward to the nearest €100, and I run it both ways to show the difference.
Example: the free optimiser and the bounded one
movable = ["search", "social", "email"]
budget = sum(plan[c] for c in movable) # 6,700 a week, the catalogue stays at 1,300
def neg_revenue(x, pars):
return -sum(response(xi, c, pars) for xi, c in zip(x, movable))
def optimise(bounds, pars):
out = minimize(neg_revenue, x0=[plan[c] for c in movable], args=(pars,),
method="SLSQP", bounds=bounds,
constraints=[{"type": "eq", "fun": lambda x: x.sum() - budget}])
return dict(zip(movable, out.x.round(-1).tolist()))
free = optimise([(0, budget)] * 3, pars)
hist = model_weeks[movable].agg(["min", "max"])
history_bounds = [(float(hist.loc["min", c] // 100 * 100), float(hist.loc["max", c] // 100 * 100))
for c in movable]
safe = optimise(history_bounds, pars)
print("free:", free)
print("history bounds:", history_bounds)
print("within history:", safe)
def total(alloc, pars):
return sum(response(alloc[c], c, pars) for c in movable)
print(round(total(free, pars) - total(plan, pars)), round(total(safe, pars) - total(plan, pars)))
for c in movable:
print(c, round(marginal_roi(safe[c], c, pars), 2))
free: {'search': 0.0, 'social': 4930.0, 'email': 1770.0}
history bounds: [(2800.0, 6300.0), (1100.0, 2800.0), (200.0, 1100.0)]
within history: {'search': 2800.0, 'social': 2800.0, 'email': 1100.0}
4833 2520
search 0.69
social 2.43
email 1.96
The free optimiser switches search off entirely and promises €4,833 more revenue a week. It is answering the question the data cannot: what Northgate looks like without search, and with social at €4,930, almost twice anything Priya has ever spent there. Nobody should sign that.
Within history the answer is the Marketing Analytics chapter's reallocation, to the euro: search down from €4,000 to €2,800, social up to €2,800, email up to €1,100. That moves €1,200 a week, 15% of the €8,000 budget, and the model expects €2,520 more revenue a week, about €131,000 a year for the same spend. The planted truth for that exact move is €2,373, so the bounded estimate is within about 6%. After the move, the marginal returns are 0.69, 2.43 and 1.96: closer together, which is what a better budget looks like, and still unequal, which is the model asking for another step next quarter. The same logic under uncertainty, without the time dimension, is in optimisation under uncertainty.
All three bounds bind. That is not a flaw. It is the message. The model wants to go further than the data can support, and the honest response is to move to the edge, measure, refit and move again.
Step 10: put an interval on the move, and see what it cannot see
A lift without an interval is a slogan. The Bayesian route gets the interval from the posterior. The route that fits this chapter is the bootstrap: build new versions of the data from the fitted model plus resampled residuals, refit each one, and look at the spread of whatever you care about.10 Weekly residuals are not independent, a bad week tends to sit next to another, so I resample them in blocks of four weeks rather than one at a time, the moving block bootstrap.11 The interval this produces is a confidence interval in the frequentist sense (Foundations: confidence intervals).
Example: 200 refits of Northgate's model
boot_rng = np.random.default_rng(7)
fitted = predict(fit.x)
lifts, search_contrib, search_mroi_below, ranking_holds = [], [], [], []
for b in range(200):
# resample the residuals in blocks of four weeks, so runs of good and bad weeks survive
starts = boot_rng.integers(0, len(res) - 3, size=26)
block_res = np.concatenate([res[s:s + 4] for s in starts])[:len(res)]
y_boot = y_all.copy()
y_boot[fit_rows] = fitted[fit_rows] + block_res
p_b, _ = unpack(least_squares(residuals, fit.x, bounds=(lo, hi), args=(y_boot, fit_rows)).x)
lifts.append(total(safe, p_b) - total(plan, p_b))
search_contrib.append(response(plan["search"], "search", p_b))
m = {c: marginal_roi(plan[c], c, p_b) for c in movable}
search_mroi_below.append(m["search"] < 1 / 0.45) # below break even
ranking_holds.append(m["search"] < min(m["social"], m["email"]))
print(np.percentile(lifts, [10, 50, 90]).round(-1))
print(np.percentile(search_contrib, [10, 50, 90]).round(-1))
print(np.mean(search_mroi_below), np.mean(ranking_holds))
print(round(total(safe, TRUE) - total(plan, TRUE)), round(response(plan["search"], "search", TRUE)))
[1330. 2270. 3210.]
[ 630. 2650. 5580.]
1.0 0.995
2373 6861
It runs in about five seconds. Read the four lines in order.
The lift from the bounded move has an 80% interval of €1,330 to €3,210 a week, around a median of €2,270. The whole interval is above zero and the planted truth, €2,373, sits in the middle of it. That is a decision you can take to a board, in the form the Marketing Analytics chapter recommends: the move, the expected lift and the interval, in one sentence.
Search's weekly contribution at €4,000 of spend has an 80% interval from €630 to €5,580. The truth is €6,861, outside the interval altogether. This is the most important output of the chapter. The bootstrap rebuilds the data from the fitted model, so it inherits the fitted model's story about zero spend. It measures how much noise could move the estimate. It cannot detect that the story itself is wrong about a region with no data. No resampling can. Only an experiment that actually switches search off can.
The last two lines are why the decision survives anyway. In 100% of refits search's next euro returned less than break even, and in 199 of 200 less than the next euro in both social and email. The ranking of marginal returns is solid even though the total contribution is not.
When search spend follows the other channels
One more check before the memo. The single equation model assumes each channel's spend is set independently. At Northgate it is not: Priya raises search bids when the catalogue lands, because branded searches jump. The Marketing Analytics chapter calls this the biggest single correction in the exercise, and simultaneous equations in Python builds the full two stage least squares fix. The first step is a diagnostic you should always run: a second regression, with search spend on the left and the other channels' adstock on the right.
Example: does search follow the catalogue?
# Does search spend follow the other channels? Branded searches react within days,
# so the catalogue gets a short memory here (one week), social keeps its two weeks.
second = pd.DataFrame({
"search": search,
"social_adstock": adstock_fast(social, 2.0),
"catalogue_adstock": adstock_fast(catalogue, 1.0),
"christmas": christmas,
}, index=weekly.index).iloc[warm:]
eq2 = sm.OLS(second["search"], sm.add_constant(second.drop(columns="search"))).fit()
print(pd.DataFrame({"coef": eq2.params, "p_value": eq2.pvalues}).round(3))
coef p_value
const 3255.638 0.000
social_adstock 0.065 0.405
catalogue_adstock 0.025 0.004
christmas 1370.466 0.000
Each euro of catalogue adstock lifts search spend by 2.5 cent, so a €34,000 drop adds about €850 of search spend in its week and half that the week after, with a p value of 0.004. Social shows no such link (p = 0.405). In this generated data the link is in the spending, not in the sales, so the revenue model is not biased by it, only made noisier by the overlap. In real data you cannot know that: branded search that rises after a catalogue may be collecting sales the catalogue created. When this diagnostic shows a link, the search estimate is suspect, and the fix is the two stage model or, better, a test.
The model needs a referee: a geo test
Everything above points at one test. Search is the channel with the shakiest total, the biggest planned cut and a spend that follows the catalogue. The Marketing Analytics chapter's loop is: fit the model, find the least certain channel, run a geo holdout on it, turn the measured lift into a tighter prior, refit. A geo holdout assigns regions at random to keep a channel running or switch it off for a few weeks and compares total revenue between them.12 Sample size, randomisation and the significance test for that comparison are the subject of A/B tests in Python, and the design side is in statistical testing: sample size, lift and full factorial designs.
In the code of this chapter, a test result plugs straight into the residuals function. If a four week holdout says search's maximum effect is around €9,000 with a standard error of €1,500, that is one more prior residual, (beta_search - 9000) / 1500, and the baseline and the search curve can no longer trade revenue as freely. That is the whole mechanism by which experiments calibrate a media mix model, in one line.
The open source tools, as of August 2026
Building it yourself, as above, is the best way to understand a media mix model. For production work with geo level data, many channels and full posteriors, three open source projects are worth knowing. Each is a serious piece of work, and each ships default priors and settings that are opinions, so read them the way you read Priya's.
- Meridian, from Google, is a Python framework built on Bayesian causal inference. It encourages geo level data, supports calibration with experiments and other prior information, and can optimise ad frequency from reach and frequency data. It is licensed under Apache 2.0. Version 1.8.0 came out on 15 August 2026, and its README states that it requires Python 3.11 to 3.13, so with Python 3.14 it needs its own environment.13
- PyMC Marketing, from PyMC Labs, reached version 1.0.0 on 7 August 2026, which its release notes describe as the stable API after two years of 0.x releases. It offers adstock and saturation functions you can swap or write yourself, budget optimisation and calibration with lift tests, under Apache 2.0. The 1.0 release notes also describe a workflow for upper funnel media whose demand converts later through lower funnel channels, which is this chapter's branded search problem.14
- Robyn, from Meta Marketing Science, is an R package that calls itself experimental. It uses ridge regression with hyperparameters searched by an evolutionary algorithm through the Nevergrad library, and its last CRAN release is 3.12.1 from July 2025. A native Python version exists in beta, which the README says may have bugs, alongside a Python API that needs the R package installed.15
If you take one thing from the code in this chapter into any of them: check the range of spend each channel has seen before you trust its optimiser, and ask how the tool's decomposition handles a channel that never stops.
Pitfalls that only show up in code
The warm up that nobody loaded. If your spend export starts on the same day as your revenue, the first weeks of adstock are too low, most of all for a slow channel. The model compensates by crediting those weeks' sales to the baseline or a fast channel. Load three to six months of earlier spend and cut after the transformation, never before.
Exposure week against booking week. Anything invoiced ahead of time, print, post, sponsorship, prepaid placements, must go through a calendar of when people saw it. A catalogue in the wrong week reads as a channel that does nothing.
Starting values that decide the answer. Nonlinear least squares finds a minimum, not necessarily the minimum. Start from the priors, as above, and refit from two or three other starting points. If the answers differ much, the data does not identify the model and the priors are doing the work.
Parameters on the edge. A half life at its upper bound, a at its lower bound or a best grid value on the last column means the model wants to leave the region you allowed. Find out why before widening it: usually a wrong curve, a missing control or a channel that never varied.
Units that change between tools. The adstock here is a running sum, so its scale is "euro of stock". Meridian, for one, normalises the adstock weights, so a from one tool cannot be copied into another, a point the Marketing Analytics chapter makes too.
Daily data that looks like more data. Seven times as many rows is not seven times as much information when day of week noise and the delay between click and order dominate. Weekly totals in local time are usually the better unit for a shop of Northgate's size.
For the person who commissions this
You do not need to read the code to judge a media mix model. You need its outputs in a form that shows what the data supports. Ask for these, and be wary of any model that cannot provide them:
| Ask for | Good sign | Warning sign |
|---|---|---|
| Spend source per channel | Exposure weeks, drop calendar for print | Finance export by invoice date |
| Holdout of the last 12 weeks | Misses by under about 10% | Not done, or only in sample fit shown |
| Priors | Written down, with reasons, before fitting | "The tool's defaults" |
| Contribution per channel | Shown with a note for always on channels | A pie chart with no interval |
| Marginal ROI at today's spend | Compared with break even (1 divided by margin) | Only average ROI |
| Recommended move | Within the spend range history has seen | Switches a channel off or doubles one |
| Interval on the lift | Stated, and above zero | Missing |
| Next test | Named channel, region design, duration | None |
The one question that cuts through all of it: "Which channel has never been switched off, and how did you decide what it is worth?" If the answer is a confident number with no mention of the baseline, the decomposition is a guess dressed up.
Building this kind of model, and the dashboard that answers "where should next month's budget go" every month, is a core part of my Data Science work. The client owns the code, the accounts and the data, and my prices are on the pricing transparency page.
My view
My view: a small media mix model you can read line by line beats a large one you cannot, for any shop with four to eight channels and two years of weekly data. The adstock is eight lines, the curve is one, the priors are a residual each and the whole fit runs in under a second. With that in hand you understand what the big packages do, and you can tell when their defaults are making your decision for you.
I would never present the decomposition as the result. On Northgate's data it was wrong by a factor of two for the channel that mattered most, while the holdout looked fine and the bootstrap looked confident. The marginal returns, the bounded move and the interval on its lift were right. That pattern is not a fluke of one seed: it follows from the fact that the data contains slopes for every channel and a zero point only for the channels you have switched off. So I report the move, the lift and the interval, I bound the optimiser by history every time, and I treat the first geo test on the always on channel as part of the model rather than an optional extra.
Conclusion
A media mix model in Python is a short pipeline once the data is right: spend in the weeks people saw it, orders in local weeks, a warm up for the adstock, geometric adstock with lfilter, a Hill curve, priors written as extra residuals and fitted with least_squares, a twelve week holdout, a decomposition read with care, marginal returns against break even, an optimiser bounded by history, and a block bootstrap for the interval.
For Northgate Hampers the answer matches the Marketing Analytics chapter: the next euro in search returns about 49 cent against a break even of €2.22, social and email return more than break even, and moving €1,200 a week from search to social and email should add about €2,500 a week, with an 80% interval of €1,330 to €3,210. What the model cannot say is how much search is worth in total, and the right response to that is the geo test, not a more confident chart. If you want to work through your own weekly data this way, bring two years of spend and revenue to the free workshop.
