Distributed lags in Python: how long marketing keeps working
TL;DR
Difficulty: Advanced
A newsletter or an ad keeps selling for weeks, so measure a curve, not a same week rate.
- Put sends and orders on a complete weekly calendar in local time, then build lag columns with shift (it moves rows, not weeks).
- A same week regression is worse than it looks: 0.17 orders per 1,000 emails on the example data, against a total of 4.26 from the lag model.
- Fit the free lags first, check their VIFs, then the Almon polynomial (W = XH) with HAC errors.
- A rigid send calendar can make the effect impossible to measure. Plant a known curve on your real calendar before you trust the result.
- In the example the newsletter peaks a week after the send and has delivered 93% of its effect after three weeks.
Most marketing does not work on the day it goes out, and if you only count the send week, every slow channel looks weak. This chapter builds the distributed lag model of my Marketing Analytics series in Python, line by line, on 78 weeks of generated newsletter data from an invented Leeds hamper shop: lags, the Almon polynomial, a Koyck comparison, a holdout and a simulation that checks whether your send calendar can be measured at all.
If you only read one section
A newsletter, a catalogue or an ad does not do its work on the day it goes out. It keeps producing orders for weeks. If you measure it in the send week only, every slow channel looks weak, and next month's budget drifts towards whatever works fastest, whether or not that is where the money is.
A distributed lag model fixes the shape of the question. Instead of one number for "the email effect", it estimates one weight for each week after the send: how many extra orders 1,000 emails bring in the week they go out, the week after, the week after that, and so on. Add the weights up and you have the total effect. Find the largest one and you know when the effect peaks. Look at where they fade to nothing and you know when to send again.
This chapter builds that model in Python, step by step, on data you generate yourself so every line runs. Three things in it go beyond the textbook, and they are the ones I would want a manager to remember:
- The same week number is worse than you think. On the example data, a plain regression of orders on emails in the same week says 0.17 extra orders per 1,000 emails. The curve planted in the data has 0.92 in the send week and 4.27 in total, and the lag model in this chapter recovers 0.94 and 4.26. The quiet weeks between sends are full of the previous send's tail, so the comparison itself is rigged against email.
- Your send calendar decides whether the question can be answered at all. If you send on a perfectly rigid rhythm, say every fourth Tuesday, then "emails in the last four weeks" is the same number every single week, and no method on earth can separate the email effect from the baseline. A little irregularity is what makes measurement possible.
- Before you trust a lag curve, plant one. Take your real send calendar, invent a curve you know, add noise of the size your data has, and check that the method finds the curve again. Twenty lines of Python, and it tells you whether your data can carry the answer before anyone acts on it.
The example business, a hamper shop in Leeds, finds that its monthly newsletter peaks one week after the send, has delivered 93% of its effect after three weeks, and brings about 4.26 orders per 1,000 emails in total, roughly 128 orders per send instead of the 28 or so its owner was counting.
The question, and where the concepts are explained
The reader's question for this chapter is simple: how do I measure in Python how long the effect of marketing lasts?
The concepts are explained in my Marketing Analytics chapter Polynomial distributed lags: how long does marketing keep working?. That chapter takes its time over the ideas: why one number has the wrong shape, what the lag weights mean, why the Almon polynomial helps and how the curve turns into a send cadence. Here I build it, and you can type along. This chapter mirrors its example, its numbers and its question, so the two read as a pair: one for the thinking, one for the doing.
If you are new to the Python side, three earlier chapters carry most of the weight. Time series in pandas covers dates, weekly resampling and shift, which is the single most important function in this chapter. Statistical models in Python introduces statsmodels and ordinary least squares. And the previous chapter in this series, price elasticity with regression in Python, fits a regression where cause and effect happen in the same week. This chapter adds time: the cause happens in week 28 and the effect dribbles out over weeks 28 to 33.
Example: Northgate Hampers and the newsletter that looked weak
Priya runs Northgate Hampers, an invented online hamper shop in Leeds at northgatehampers.example. She sends a newsletter roughly once a month to about 30,000 subscribers. Every send is followed by a bump in orders. Priya counts the extra orders in the week of the send, divides by the emails sent and calls that the email conversion rate: just under one order per 1,000 emails. She is about to cut the newsletter to once a quarter.
The analyst's job is to answer three questions with numbers she can defend. How many orders does one newsletter really bring, across every week it brings any? When does the effect peak, and when is it over? And so, how often should she send? Northgate Hampers and every number in this chapter are made up so I can show each step. The data is generated to resemble the example in the Marketing Analytics chapter, and the estimates land within a few hundredths of the figures there.
What you need, as of March 2026
Everything here runs on Python 3.14 with pandas 3.0, NumPy 2.4 and statsmodels 0.14.6, the current releases at the time of writing. If you have not set up Python yet, the setup chapter walks through it.
Two changes in pandas 3.0, released on 21 January 2026, matter for code like this.1 Copy on write is now the only behaviour: any column you pull out of a DataFrame behaves as a copy, so "chained assignment" such as df["a"][3] = 0 changes nothing (pandas now warns you instead). Assign with df.loc[...] or by replacing the whole column, as every block below does. And text columns now get a dedicated str data type by default instead of the old catch all object type. Neither changes the numbers in this chapter, but older tutorials (including the 2022 edition of Wes McKinney's book2) show patterns that no longer behave the same way.
import numpy as np
import pandas as pd
import statsmodels
import statsmodels.api as sm
print(pd.__version__, np.__version__, statsmodels.__version__)
# 3.0.1 2.4.2 0.14.6
Step 1: generate 78 weeks of sends and orders
Every chapter in this programme starts by generating its data, so you can run each block in order in a notebook and get exactly my outputs. The generator plants a known lag curve, the one the Marketing Analytics chapter estimates, inside realistic weekly noise. That is useful twice: you can follow the method, and you can check that it finds the curve we planted.
The weekly table has one row per week and five columns: the week (starting on a Tuesday, the send day), emails sent in thousands, paid search spend in thousands of pounds, a flag for the Christmas run up, and orders.
Example: building Northgate's weekly table
rng = np.random.default_rng(186) # fixed seed: same numbers every run
n = 78 # 78 weeks, as in the Marketing Analytics chapter
weeks = pd.date_range("2024-01-02", periods=n, freq="7D") # weeks start on Tuesday, the send day
# Roughly monthly sends, plus two Father's Day sends in weeks 22 and 24
send_weeks = [2, 6, 11, 15, 19, 22, 24, 28, 32, 37, 41, 45, 50, 54, 58, 63, 67, 72, 76]
emails_k = np.zeros(n)
for w in send_weeks:
emails_k[w - 1] = rng.integers(29, 32) # 29,000 to 31,000 emails per send
paid_search_k = np.round(rng.normal(3.0, 0.5, n), 1) # paid search spend, £000 a week
holiday = ((weeks.month == 12) & (weeks.day <= 24)).astype(int) # the Christmas run up
trend = np.arange(n)
# The true lag curve we plant: extra orders per 1,000 emails, 0 to 5 weeks after the send
true_beta = np.array([0.92, 1.33, 1.13, 0.64, 0.18, 0.07])
# Weekly noise that carries over a little from one week to the next
noise = np.zeros(n)
shocks = rng.normal(0, 8, n)
for t in range(n):
noise[t] = 0.3 * (noise[t - 1] if t else 0) + shocks[t]
email_effect = sum(true_beta[k] * np.r_[np.zeros(k), emails_k[: n - k]] for k in range(6))
orders = 33 + 6 * paid_search_k + 25 * holiday + 0.15 * trend + email_effect + noise
df = pd.DataFrame({
"week": weeks,
"emails_k": emails_k,
"paid_search_k": paid_search_k,
"holiday": holiday,
"orders": np.round(orders).astype(int),
}).set_index("week")
print(df.head(4))
print(df["orders"].describe().round(1))
emails_k paid_search_k holiday orders
week
2024-01-02 0.0 1.7 0 47
2024-01-09 29.0 3.2 0 78
2024-01-16 0.0 3.1 0 98
2024-01-23 0.0 3.0 0 89
...
mean 91.1
std 15.6
min 47.0
max 128.0
Read the first rows the way Priya would. Week 2 has a send of 29,000 emails and 78 orders. Week 3, with no send at all, has 98. The bump arrives a week late, which is exactly the pattern a same week number cannot see. Over the 78 weeks the shop averages about 91 orders a week.
Two details are worth copying. The noise carries over from week to week (each week keeps 30% of the previous week's surprise), as real weekly data does, which matters for the standard errors later. And the curve is planted explicitly in true_beta, so every estimate below can be compared with the truth, a luxury real data never offers. The last part of the chapter shows how to borrow it anyway.
Step 2: shift moves rows, not weeks
The whole model rests on one pandas method: shift(k), which moves a column down by k positions so that each row sees the value from k rows earlier.3 McKinney's chapter on time series covers leading and lagging data in the same way.2 The trap is in the word "rows". shift knows nothing about calendars. If a week is missing from your table, "one row back" is no longer "one week back", and nothing warns you.
A newsletter tool exports one row per campaign, not one row per week. Build the lags on that export and "last week's emails" quietly becomes "the previous campaign's emails", which could be five weeks ago.
Example: the newsletter export that only has send weeks
# The newsletter tool only exports the weeks with a send
sends = df.loc[df["emails_k"] > 0, ["emails_k"]]
print(len(sends)) # 19 rows, not 78
wrong = sends["emails_k"].shift(1) # "last week"? No: the previous SEND
print(wrong.head(3))
# 2024-01-09 NaN
# 2024-02-06 29.0 <- claims 29,000 emails went out the week before 6 February
# 2024-03-12 30.0
# Fix: put the sends on a complete weekly calendar first, empty weeks as 0
full = pd.date_range(df.index.min(), df.index.max(), freq="7D")
sends_full = sends.reindex(full, fill_value=0)
print(len(sends_full)) # 78 rows, one per week
print(sends_full["emails_k"].shift(1).head(3))
# 2024-01-02 NaN
# 2024-01-09 0.0
# 2024-01-16 29.0 <- correct: the send was one week earlier
The wrong version says that in the week before 6 February, 29,000 emails went out. They did not. They went out four weeks earlier. A model built on that column would find a beautiful, completely false "one week lag".
The rule I use: before any shift, check that the index is complete and evenly spaced. len(df) == len(pd.date_range(df.index.min(), df.index.max(), freq="7D")) is a one line test, and it belongs in the pipeline as an assertion, the way the reproducible workflow chapter puts checks next to the code they protect. The same applies to a merge: when you join the weekly orders to the newsletter export, the weeks without a send come back as missing values, and they must become zeros, not be dropped. The chapter on joining and reshaping covers that merge in detail.
Step 3: define the week the way the customer lives it
The second trap sits one step earlier, when you turn order timestamps into weeks. The shop's order export records times in UTC. Priya's newsletter goes out at 7am on a Tuesday, London time. If you cut weeks on UTC, an order placed at half past midnight on a Tuesday in summer lands in the previous week, before the email that caused it.
The Marketing Analytics chapter makes the related point about week boundaries: a Thursday send puts three days of the send week into lag 0 and four into lag 1, so part of a "peak at lag 1" can be a calendar artefact. Start your analysis weeks on the send weekday, and convert the time zone first.
Example: one order, two different weeks
In pandas, a weekly period ending on Monday (W-MON) starts on Tuesday, which is exactly what a Tuesday sender wants.
raw = pd.DataFrame({"created_at": pd.to_datetime([
"2025-06-02 23:30", "2025-06-03 06:15", "2025-06-09 23:45"], utc=True)})
local = raw["created_at"].dt.tz_convert("Europe/London")
raw["week_utc"] = raw["created_at"].dt.tz_localize(None).dt.to_period("W-MON").dt.start_time
raw["week_local"] = local.dt.tz_localize(None).dt.to_period("W-MON").dt.start_time
print(raw)
# created_at week_utc week_local
# 0 2025-06-02 23:30:00+00:00 2025-05-27 2025-06-03
# 1 2025-06-03 06:15:00+00:00 2025-06-03 2025-06-03
# 2 2025-06-09 23:45:00+00:00 2025-06-03 2025-06-10
The first order was placed at 12.30am on Tuesday 3 June, London time, the day of a send. On UTC it belongs to the week of 27 May. The third order, at 12.45am on Tuesday 10 June, is pulled back into the send week when it belongs to the week after. Shift a few hundred late night orders like that and you move the peak of the curve. In winter, London is on UTC and the problem disappears, which is exactly why it survives testing in January and bites in June. The chapter on loading business data and the chapter on cleaning cover the rest of the export: test orders, staff orders and refunds as separate rows all need to go before you count anything.
Step 4: build the lag columns
With a complete weekly index, building the lags is one line per lag. For a lag length of five weeks, you want six columns: this week's emails, last week's, and so on back to five weeks ago.
Example: watching one send walk down the columns
L = 5
lags = pd.concat({f"lag{k}": df["emails_k"].shift(k) for k in range(L + 1)}, axis=1)
print(lags.iloc[26:31]) # weeks 27 to 31: the send in week 28 walks down the columns
lag0 lag1 lag2 lag3 lag4 lag5
week
2024-07-02 0.0 0.0 0.0 31.0 0.0 31.0
2024-07-09 31.0 0.0 0.0 0.0 31.0 0.0
2024-07-16 0.0 31.0 0.0 0.0 0.0 31.0
2024-07-23 0.0 0.0 31.0 0.0 0.0 0.0
2024-07-30 0.0 0.0 0.0 31.0 0.0 0.0
Week 28 (9 July) has a send of 31,000 emails. Follow the 31.0 down and to the right: it is lag0 in week 28, lag1 in week 29, lag2 in week 30, lag3 in week 31. Each row now tells the regression how much was sent in each of the last six weeks.
The first five rows of the table have missing values in the higher lags, because there is no week before the first week. Those rows have to go before fitting, so 78 weeks become 73 usable ones. That is the price of a lag of five, and it is why a long lag on a short history is expensive.
Step 5: the same week regression, and why it misleads
Before building the right model, it pays to see exactly how wrong the obvious one is. Regress weekly orders on the emails sent in the same week, with the controls (paid search spend, the Christmas flag and a linear trend), and read the email coefficient.
Example: what the obvious regression says
controls = df[["paid_search_k", "holiday"]].assign(trend=np.arange(n))
X0 = sm.add_constant(pd.concat([df[["emails_k"]], controls], axis=1))
same_week = sm.OLS(df["orders"], X0).fit(cov_type="HAC", cov_kwds={"maxlags": 4})
print(same_week.params.round(2))
# const 54.71
# emails_k 0.17
# paid_search_k 9.79
# holiday 19.86
# trend 0.14
0.17 extra orders per 1,000 emails. The planted truth is 0.92 in the send week and 4.27 in total. The same week regression does not just miss the later weeks, it gets the send week wrong too.
The reason is the comparison. A regression with only emails_k compares send weeks with non send weeks. But the non send weeks are not a clean baseline: the week after a send is the strongest email week of all, and the two after that are still well above normal. The regression sees "weeks without email" doing nearly as well as "weeks with email" and concludes that email barely matters. Every slow channel suffers from this, and it is the strongest argument I know for never reporting a same week effect for email, catalogues or brand advertising.
Step 6: the unrestricted distributed lag model
The distributed lag model says this week's orders depend on this week's emails and on the emails of the previous weeks, each with its own weight:
Here is orders in week , is the baseline, is the effect of 1,000 emails sent weeks ago on orders this week, is the emails (in thousands) sent weeks before week , is the lag length, holds the controls (paid search, the Christmas flag, the trend), their coefficients and the error. It is an ordinary multiple regression whose inputs happen to be shifted copies of one column. Foundations: regression
"Unrestricted" means each is free to take any value. Fitting it is the lag table from Step 4 plus the controls, with the incomplete rows dropped.
One detail matters: the standard errors. Weekly residuals are autocorrelated, and plain least squares standard errors then look more precise than they are. cov_type="HAC" asks statsmodels for heteroscedasticity and autocorrelation consistent errors, the Newey and West approach, with up to four weeks of autocorrelation allowed.45
Example: six free weights for Northgate
data = pd.concat([df["orders"], lags, controls], axis=1).dropna() # drops the first 5 weeks
X_u = sm.add_constant(data.drop(columns="orders"))
unres = sm.OLS(data["orders"], X_u).fit(cov_type="HAC", cov_kwds={"maxlags": 4})
lag_cols = list(lags.columns)
print(pd.DataFrame({"beta": unres.params[lag_cols], "se": unres.bse[lag_cols]}).round(2))
print("total:", round(unres.params[lag_cols].sum(), 2), "rows used:", int(unres.nobs))
| Lag | Unrestricted | Std. error | Planted truth |
|---|---|---|---|
| 0 | 0.97 | 0.06 | 0.92 |
| 1 | 1.32 | 0.14 | 1.33 |
| 2 | 1.08 | 0.16 | 1.13 |
| 3 | 0.69 | 0.12 | 0.64 |
| 4 | 0.17 | 0.12 | 0.18 |
| 5 | 0.06 | 0.08 | 0.07 |
| Total | 4.29 | 4.27 |
This is where the Python chapter and the concepts chapter part company a little, and the difference is instructive. In the Marketing Analytics chapter the unrestricted weights swing wildly and change sign. Here they are close to the truth. Same calendar, same curve, very different picture. The reason is noise: the generated data here is cleaner than most real exports, with about eight orders of unexplained noise a week. With messier data, or a longer lag, or a channel that runs every week, the same code produces the wild table. The next step shows how to tell which situation you are in, rather than guessing.
Step 7: measure the multicollinearity among the lags
Multicollinearity means that some inputs to a regression are nearly copies of each other, or nearly a combination of each other. The regression then cannot tell which one deserves the credit, so the individual coefficients become unstable while their sum stays reasonable.6 With lags, the risk is built in: the lag columns are the same series shifted.
Two numbers tell you how bad it is. The correlation matrix of the lag columns shows pairs that move together. The variance inflation factor (VIF) of each column says how much its variance is inflated because the other inputs can partly predict it: a VIF of 1 means no inflation, a VIF of 4 means the standard error is twice what it would be without the overlap.7
Here is the variance inflation factor of lag column , and is the share of that column's variation explained by a regression of it on all the other inputs. Its square root is the factor by which the standard error of grows. Foundations: correlation
Example: Northgate's lags against an always on channel
from statsmodels.stats.outliers_influence import variance_inflation_factor
print(data[lag_cols].corr().round(2))
Xv = X_u.to_numpy()
vif = pd.Series([variance_inflation_factor(Xv, i) for i in range(1, 7)], index=lag_cols)
print(vif.round(2))
# Compare: an always on channel whose weekly spend drifts slowly
spend = np.zeros(n)
for t in range(n):
spend[t] = 0.9 * (spend[t - 1] if t else 0) + rng.normal(0, 1)
spend_lags = pd.concat({f"lag{k}": pd.Series(spend).shift(k) for k in range(L + 1)}, axis=1).dropna()
Xs = sm.add_constant(spend_lags).to_numpy()
print(pd.Series([variance_inflation_factor(Xs, i) for i in range(1, 7)], index=lag_cols).round(1))
The correlation matrix of Northgate's email lags has one striking pattern: lag 0 and lag 4 correlate at 0.48, and so do lag 1 and lag 5. Every other pair is mildly negative. That is the monthly calendar showing through: a send is often followed by another one four weeks later, so "emails this week" and "emails four weeks ago" tend to be large together.
| Lag column | VIF, Northgate's newsletter | VIF, an always on channel |
|---|---|---|
| lag0 | 2.4 | 5.9 |
| lag1 | 3.6 | 9.6 |
| lag2 | 4.6 | 9.6 |
| lag3 | 4.6 | 9.5 |
| lag4 | 3.6 | 9.2 |
| lag5 | 2.4 | 5.6 |
The newsletter lags are inflated, but moderately: standard errors roughly two times what they would be with no overlap. The always on channel, a weekly spend that drifts slowly the way paid social budgets do, is roughly twice as bad again, with standard errors about three times as wide. That is the situation where unrestricted lags fall apart, and where the next step earns its keep.
Step 8: the Almon polynomial, implemented explicitly
Shirley Almon's idea, published in 1965, is to stop estimating each weight separately and assume instead that the weights lie on a smooth, low order polynomial in the lag.8
Here is the weight at lag , is the degree of the polynomial (3 in the second form), and to are the polynomial's coefficients. Instead of free weights you estimate coefficients. A cubic can draw a quick rise, a hump and a tail, which is the shape most marketing effects have. Foundations: regression
The trick that makes it practical is that it is still ordinary least squares. In matrix form, write the six weights as a vector and the four coefficients as a vector . Then
Here is a fixed matrix with one row per lag (0 to ) and one column per power (0 to ), and each entry is the lag raised to that power. If is the table of lag columns, the model's email part is , so you build new columns , regress orders on them, and recover the weights as .9 Foundations: matrices
I build it by hand rather than reach for a package. It takes ten lines and leaves nothing hidden, which matters when someone asks where a number came from.
Example: the matrix H and one constructed column
def almon_matrix(L, p):
"""H[k, j] = k**j: turns p+1 polynomial coefficients into L+1 lag weights."""
k = np.arange(L + 1)
return np.vander(k, p + 1, increasing=True).astype(float)
p = 3
H = almon_matrix(L, p)
print(H)
W = pd.DataFrame(lags.to_numpy() @ H, index=lags.index, columns=[f"w{j}" for j in range(p + 1)])
print(W.loc["2024-07-23"]) # week 30: only the send in week 28 (two weeks ago) is in the window
[[ 1. 0. 0. 0.]
[ 1. 1. 1. 1.]
[ 1. 2. 4. 8.]
[ 1. 3. 9. 27.]
[ 1. 4. 16. 64.]
[ 1. 5. 25. 125.]]
w0 31.0
w1 62.0
w2 124.0
w3 248.0
Row of H is . Now take week 30. The only send in its six week window is the 31,000 emails of week 28, two weeks earlier, so only lag2 is non zero. The four constructed columns are that send weighted by :
Here is the week 30 value of constructed column . One send two weeks ago becomes four numbers that tell the regression both how much was sent and how long ago. A send one week ago would have given 31, 31, 31 and 31, because , and so the regression can tell the two apart.
Step 9: fit the Almon model and read the curve
Fitting is the same sm.OLS call, with the four w columns in place of the six lags. The step that is easy to get wrong comes after: turning the coefficients back into weights, and doing the same for their uncertainty. The weights are . Their covariance matrix is , where is the covariance matrix of the coefficients, and the square roots of its diagonal are the standard errors of the weights.
Example: Northgate's lag curve
data_a = pd.concat([df["orders"], W, controls], axis=1).dropna()
X_a = sm.add_constant(data_a.drop(columns="orders"))
almon = sm.OLS(data_a["orders"], X_a).fit(cov_type="HAC", cov_kwds={"maxlags": 4})
w_cols = list(W.columns)
a = almon.params[w_cols].to_numpy()
V = almon.cov_params().loc[w_cols, w_cols].to_numpy()
beta = H @ a # the lag weights
beta_se = np.sqrt(np.diag(H @ V @ H.T)) # their standard errors
print("a:", a.round(3))
curve = pd.DataFrame({"beta": beta, "se": beta_se}, index=lag_cols)
curve["cumulative"] = curve["beta"].cumsum()
curve["share"] = curve["cumulative"] / curve["beta"].sum()
print(curve.round(2))
# a: [ 0.94 0.725 -0.417 0.047]
| Lag (weeks after send) | Almon (orders per 1,000 emails) | Std. error | Cumulative | Share of total |
|---|---|---|---|---|
| 0 | 0.94 | 0.08 | 0.94 | 22% |
| 1 | 1.30 | 0.14 | 2.24 | 52% |
| 2 | 1.10 | 0.16 | 3.34 | 78% |
| 3 | 0.64 | 0.14 | 3.98 | 93% |
| 4 | 0.21 | 0.10 | 4.19 | 98% |
| 5 | 0.07 | 0.07 | 4.26 | 100% |
To see where one weight comes from, evaluate the cubic at lag 2 with the four coefficients:
Here is the weight two weeks after the send, built from the four coefficients times , , and . The same sum at every lag fills the table. Read it line by line. In the send week, 1,000 emails bring 0.94 extra orders, a fifth of everything they will ever bring. The week after is the peak at 1.30, and by its end just over half the effect is in. Week 2 is still strong. By the end of week 3, 93% has arrived. Weeks 4 and 5 are small, and the standard error at lag 5 is as large as the estimate, so I read it as close to zero. These are the figures of the Marketing Analytics chapter to within a few hundredths: 0.92, 1.33, 1.13, 0.64, 0.18 and 0.07 there.
The chart shows the estimated weight for each week after the send next to the curve we planted. The horizontal axis counts weeks since the newsletter went out, week 0 being the send week, and the vertical axis is extra orders per 1,000 emails in that week. The takeaway: the method recovers the planted hump, with its peak one week after the send. If you want to draw the chart yourself, the chapter on charts in Python covers grouped bars, and showing time honestly covers why weeks belong on the horizontal axis.
Step 10: the total, the peak and the mean lag, with honest error bars
Three summaries carry the decision. The total effect is the sum of the weights. The peak lag is the lag with the largest weight. The mean lag is the average delay, weighted by how much effect arrives in each week:
Here is the orders that 1,000 emails eventually bring, the weight at lag , the lag length and the mean lag in weeks, a weighted mean with the weights in place of counts. Foundations: the mean
The total needs a standard error too, and here is a neat shortcut. Because every weight is a linear combination of the coefficients, so is their sum: the total is , which is the column sums of times . statsmodels' t_test takes exactly such a combination and returns its estimate, standard error and confidence interval, using the same HAC covariance as the fit.
Example: Northgate's three numbers
k = np.arange(L + 1)
total = beta.sum()
peak = int(np.argmax(beta))
mean_lag = (k * beta).sum() / total
# The total is a linear combination of the a's: sum over k of k**j, for each j
R = np.zeros(len(almon.params))
R[[almon.params.index.get_loc(c) for c in w_cols]] = H.sum(axis=0)
tt = almon.t_test(R)
lo, hi = np.asarray(tt.conf_int()).ravel()
print(f"total {total:.2f}, se {float(np.asarray(tt.sd).ravel()[0]):.2f}, 95% interval {lo:.2f} to {hi:.2f}")
print(f"peak at lag {peak}, mean lag {mean_lag:.2f} weeks")
# total 4.26, se 0.59, 95% interval 3.12 to 5.41
# peak at lag 1, mean lag 1.56 weeks
By hand, with the rounded weights from the table:
For the mean lag, multiply each weight by its lag and add up: . Then
so is 1.55 weeks. The code prints 1.56 because it works with unrounded weights. Either way, the average delay between sending and ordering is about a week and a half.
The total is 4.26 orders per 1,000 emails with a standard error of 0.59, so a 95% confidence interval of roughly 3.1 to 5.4. Foundations: confidence intervals On a send of 30,000 emails that is orders per newsletter, somewhere between about 94 and 162. Priya was counting 28.
Step 11: choosing the lag length and the degree
Two choices are still open: how many weeks back to look () and how bendy the polynomial may be (). The Marketing Analytics chapter gives the reasoning: start generous, cut back where the tail dies, prefer degree 2 or 3, and compare fits with an information criterion. AIC and BIC both reward fit and penalise parameters, BIC more harshly.
In code there is one trap almost every tutorial walks into. A model with loses ten rows to the lags, a model with loses three. If you compare their AIC values as they come, you compare fits on different data, and the shorter lag wins partly because it had more weeks to explain. Fix the sample first: drop the first rows for every candidate.
Example: a fair grid search over L and p
LMAX = 10
rows = []
for L_try in range(2, LMAX + 1):
lag_try = pd.concat({f"lag{k}": df["emails_k"].shift(k) for k in range(L_try + 1)}, axis=1)
for p_try in (2, 3):
if p_try > L_try:
continue
W_try = pd.DataFrame(lag_try.to_numpy() @ almon_matrix(L_try, p_try), index=df.index)
d = pd.concat([df["orders"], W_try, controls], axis=1).iloc[LMAX:] # same weeks for every model
f = sm.OLS(d["orders"], sm.add_constant(d.drop(columns="orders"))).fit()
total_try = (almon_matrix(L_try, p_try) @ f.params.iloc[1:p_try + 2].to_numpy()).sum()
rows.append({"L": L_try, "p": p_try, "aic": f.aic, "bic": f.bic, "total": total_try})
grid = pd.DataFrame(rows)
print(grid.sort_values("bic").head(6).round(1))
| AIC | BIC | Total effect | ||
|---|---|---|---|---|
| 5 | 3 | 469.9 | 487.6 | 4.3 |
| 3 | 2 | 472.4 | 487.9 | 3.7 |
| 4 | 3 | 470.3 | 488.1 | 4.1 |
| 4 | 2 | 474.2 | 489.7 | 4.2 |
| 3 | 3 | 472.4 | 490.2 | 3.7 |
| 6 | 3 | 475.3 | 493.1 | 4.6 |
Lower is better for both criteria. with a cubic is best on AIC and on BIC, but look at the second row: with a quadratic is only 0.3 BIC points behind and puts the total at 3.7 instead of 4.3. A difference that small is not a verdict. The tail settles it: at the lag 4 weight is 0.21 with a standard error of 0.10, clearly above zero, so cutting at lag 3 would push real orders into the baseline. Too short a lag is the expensive mistake, because it understates the channel quietly.
The rule of thumb I take from this: rank by the criterion, then read the total effect across the top few rows. If it barely moves, the choice does not matter. If it moves by 15%, as it does here, decide on the tail weights and say so in the write up.
Example: testing the polynomial against the free lags
The Almon model is the unrestricted model with linear restrictions on the weights, so an F test between the two nested models asks whether the polynomial is too rigid for the data.9 It must run on identical rows, so I build both from one table.
d = pd.concat([df["orders"], lags, W, controls], axis=1).dropna()
y = d["orders"]
restricted = sm.OLS(y, sm.add_constant(d[w_cols + list(controls.columns)])).fit()
full_fit = sm.OLS(y, sm.add_constant(d[lag_cols + list(controls.columns)])).fit()
f_value, p_value, df_diff = full_fit.compare_f_test(restricted)
print(f"F = {f_value:.2f}, p = {p_value:.2f}, restrictions = {df_diff:.0f}")
# F = 0.45, p = 0.64, restrictions = 2
A p value of 0.64 means the free weights fit no better than the cubic, so the restriction costs nothing here. Foundations: hypothesis tests compare_f_test compares the residual sums of squares of plain least squares fits and assumes no autocorrelation, so the statsmodels documentation warns it is not valid when the errors are correlated.10 With residuals as autocorrelated as weekly sales usually are, treat a borderline result with suspicion either way.
Step 12: the geometric decay (Koyck) as a comparison
The most common alternative to the Almon curve assumes the effect shrinks by the same proportion every week, a geometric decay. It is the idea behind adstock in media mix modelling, and in econometrics it is known as the Koyck model:
Here is the effect at lag , the effect in the send week, the retention rate between 0 and 1 (the share of this week's effect that survives into the next), and the sum over all future weeks. It is compounding run backwards. Foundations: compounding
Two ways to estimate it are common, and they behave very differently. The first is the Koyck transformation: subtract times last week's equation from this week's, and the infinite lag collapses into . One regression with last week's orders as an input. It looks elegant, but its error term is correlated with by construction, so least squares is biased.9 The second is direct: build the decayed "adstock" series for a grid of values and keep the one that fits best.
Example: Koyck and adstock against Priya's curve
# Koyck form: this week's orders on this week's emails and last week's orders
k_data = pd.concat([df["orders"], df["emails_k"], df["orders"].shift(1).rename("orders_lag1"),
controls], axis=1).dropna()
koyck = sm.OLS(k_data["orders"], sm.add_constant(k_data.drop(columns="orders"))).fit()
b0, lam = koyck.params["emails_k"], koyck.params["orders_lag1"]
print(f"beta0 {b0:.2f}, lambda {lam:.2f}, long run total {b0 / (1 - lam):.2f}")
print("implied weights:", (b0 * lam ** np.arange(L + 1)).round(2))
# beta0 0.47, lambda 0.45, long run total 0.85
# implied weights: [0.47 0.21 0.09 0.04 0.02 0.01]
def adstock(x, lam):
out = np.zeros(len(x))
for t in range(len(x)):
out[t] = x[t] + (lam * out[t - 1] if t else 0)
return out
fits = {}
for lam_try in np.round(np.arange(0.0, 0.95, 0.05), 2):
ad = pd.Series(adstock(df["emails_k"].to_numpy(), lam_try), index=df.index, name="adstock")
d = pd.concat([df["orders"], ad, controls], axis=1).iloc[L:]
fits[lam_try] = sm.OLS(d["orders"], sm.add_constant(d.drop(columns="orders"))).fit()
best_lam = min(fits, key=lambda l: fits[l].ssr)
g = fits[best_lam]
b0_g = g.params["adstock"]
print(f"best lambda {best_lam}, beta0 {b0_g:.2f}, total {b0_g / (1 - best_lam):.2f}")
print("geometric weights:", (b0_g * best_lam ** np.arange(L + 1)).round(2))
print(f"R squared: geometric {g.rsquared:.3f}, Almon {almon.rsquared:.3f}")
# best lambda 0.8, beta0 0.80, total 4.01
# geometric weights: [0.8 0.64 0.51 0.41 0.33 0.26]
# R squared: geometric 0.536, Almon 0.778
| Method | Send week | Week 1 | Week 3 | Week 5 | Total |
|---|---|---|---|---|---|
| Almon cubic | 0.94 | 1.30 | 0.64 | 0.07 | 4.26 |
| Adstock, best | 0.80 | 0.64 | 0.41 | 0.26 | 4.01 |
| Koyck regression | 0.47 | 0.21 | 0.04 | 0.01 | 0.85 |
The Koyck regression is the cautionary tale. Last week's orders soak up the email effect along with everything else that carries over, and the total comes out at 0.85, a fifth of the truth. The adstock grid does much better on the total, 4.01, but look at its shape: the effect is largest in the send week and then decays slowly, with a quarter of an order still arriving in week 5. No value of below 1 can make week 1 larger than week 0, so a geometric curve can never draw Priya's hump.11 It explains 54% of the weekly variation in orders against 78% for the Almon model.
For the cadence decision that difference is everything. The geometric curve says much of the effect is still to come after week 3. The Almon curve says 7%. One tells Priya to wait, the other tells her she can send again.
Step 13: hold out the last twelve weeks
A curve that fits the past is a hypothesis. Before acting on it, fit on the first 66 weeks, forecast the last 12, and compare with what actually happened. The yardstick is the same model without email, so you can see what the email terms add.
The mean absolute percentage error (MAPE) averages the size of the misses as a share of the actual figure:
Here is the number of holdout weeks (12), the actual orders in week and the forecast. Foundations: percentages
Example: twelve weeks the model never saw
cut = 66
train = data_a.iloc[: cut - L] # weeks 6 to 66 (the first five went into the lags)
test = data_a.iloc[cut - L:] # weeks 67 to 78
X_train = sm.add_constant(train.drop(columns="orders"))
X_test = sm.add_constant(test.drop(columns="orders"), has_constant="add")
m = sm.OLS(train["orders"], X_train).fit()
forecast = m.predict(X_test)
# The same model without email, as the yardstick
ctrl = list(controls.columns)
m0 = sm.OLS(train["orders"], sm.add_constant(train[ctrl])).fit()
forecast0 = m0.predict(sm.add_constant(test[ctrl], has_constant="add"))
def mape(actual, pred):
return float((abs(actual - pred) / actual).mean() * 100)
out = pd.DataFrame({"week": range(cut + 1, n + 1), "emails_k": df["emails_k"].iloc[cut:].to_numpy(),
"actual": test["orders"].to_numpy(), "forecast": forecast.round().to_numpy(),
"no_email": forecast0.round().to_numpy()})
print(out.to_string(index=False))
print(f"MAPE with email {mape(test['orders'], forecast):.1f}%, without {mape(test['orders'], forecast0):.1f}%")
# MAPE with email 6.7%, without 8.9%
| Week | Emails (000s) | Actual orders | Forecast | Without email |
|---|---|---|---|---|
| 67 | 30 | 98 | 100 | 94 |
| 68 | 0 | 114 | 110 | 98 |
| 69 | 0 | 89 | 99 | 95 |
| 70 | 0 | 80 | 83 | 92 |
| 71 | 0 | 67 | 68 | 89 |
| 72 | 30 | 103 | 96 | 94 |
| 73 | 0 | 112 | 106 | 96 |
| 74 | 0 | 95 | 100 | 94 |
| 75 | 0 | 92 | 88 | 97 |
| 76 | 31 | 88 | 100 | 92 |
| 77 | 0 | 95 | 111 | 96 |
| 78 | 0 | 95 | 101 | 94 |
Week 67's miss, for instance, is . Averaged over the twelve weeks, the model with the lag curve misses by 6.7%, the model without email by 8.9%.
The shape matters more than the average. The weeks straight after a send (68 and 73) are among the highest in the forecast and in the actual figures. Week 71, four weeks after a send, is the lowest in both: 67 actual orders, 68 forecast, while the model without email expected 89. The model has the timing right, and the timing is what Priya is going to act on. It also overshoots weeks 76 to 78. That is worth a look in the real data (a soft send, a delivery problem, a competitor's sale) before the curve goes into a memo.
Plant a curve before you trust one
Here is the check I would add to every lag analysis, and the one tutorials skip. On real data you never know the true curve, so you cannot tell whether the method recovered it. But you can borrow the truth: take your real send calendar, plant a curve you choose, add noise as large as your model's residuals, refit a few hundred times, and measure how far the estimates land from the curve you planted. If they land far away, your data cannot answer the question, however neat the regression output looks.
The same simulation answers a planning question the Marketing Analytics chapter raises: would a different send calendar make the effect easier to measure?
Example: four calendars, three hundred simulations each
def simulate(calendar, n_sims=300, sd=8, L_fit=5, seed=1):
"""Plant the true curve on a send calendar, refit many times, measure the error."""
r = np.random.default_rng(seed)
T = len(calendar)
H_fit = almon_matrix(L_fit, 3)
lagX = np.column_stack([np.r_[np.zeros(k), calendar[: T - k]] for k in range(L_fit + 1)])
effect = lagX[:, :6] @ true_beta
errs = {"unrestricted": [], "almon": []}
for _ in range(n_sims):
e = np.zeros(T)
s = r.normal(0, sd, T)
for t in range(T):
e[t] = 0.3 * (e[t - 1] if t else 0) + s[t]
y = 90 + effect + e
keep = slice(L_fit, T)
Xu = sm.add_constant(lagX[keep])
bu = np.linalg.lstsq(Xu, y[keep], rcond=None)[0][1:7]
Xa = sm.add_constant(lagX[keep] @ H_fit)
ba = (H_fit @ np.linalg.lstsq(Xa, y[keep], rcond=None)[0][1:])[:6]
errs["unrestricted"].append(np.sqrt(((bu - true_beta) ** 2).mean()))
errs["almon"].append(np.sqrt(((ba - true_beta) ** 2).mean()))
return {key: round(float(np.mean(v)), 2) for key, v in errs.items()}
cal_now = df["emails_k"].to_numpy()
cal_rigid = np.zeros(n); cal_rigid[1::4] = 30 # exactly every 4 weeks
r2 = np.random.default_rng(7)
cal_jitter = np.zeros(n)
t = 1
while t < n:
cal_jitter[t] = 30
t += int(r2.integers(2, 7)) # gaps of 2 to 6 weeks
cal_on = np.clip(30 + np.cumsum(r2.normal(0, 3, n)), 0, None) # sent every week, slowly drifting
# Why the rigid calendar is hopeless: every four week window holds exactly one send
print(pd.Series(cal_rigid).rolling(4).sum().iloc[4:].unique())
# [30.]
for name, cal in [("current", cal_now), ("rigid 4 weeks", cal_rigid),
("jittered", cal_jitter), ("every week", cal_on)]:
print(name, simulate(cal))
print("current, fitted with L = 10:", simulate(cal_now, L_fit=10))
The simulation leaves out the controls to stay short, so treat its numbers as a comparison between calendars, not as the error of the full model. The measure is the root mean squared error of the six weights: on average, how far each estimated weight lands from the planted one, in orders per 1,000 emails.
| Send calendar | Unrestricted lags | Almon cubic |
|---|---|---|
| Northgate's current calendar | 0.14 | 0.13 |
| Rigidly every four weeks | 2.15 | 2.21 |
| Jittered, gaps of 2 to 6 weeks | 0.09 | 0.09 |
| Sent every week, volume drifting | 0.93 | 0.58 |
| Current calendar, fitted with | 0.17 | 0.29 |
The chart shows, for four send calendars, how far the estimated lag weights land from the truth on average, lower being better. Four lessons sit in it.
The rigid calendar is hopeless for both methods, and the one line check explains why. If a send goes out exactly every fourth week, every four week window contains exactly one send, so "emails in the last four weeks" is always 30. That column is a constant, indistinguishable from the baseline, and the regression cannot separate the email effect from the orders that would have happened anyway. No estimator fixes an identification problem. Only the calendar does.
A jittered calendar, with gaps between two and six weeks, is the best of the four: errors a third lower than Northgate's current near monthly rhythm. The Marketing Analytics chapter recommends moving the send date by a week now and then. The simulation puts a number on that advice.
The always on channel is where the Almon restriction earns its keep, cutting the error from 0.93 to 0.58. That is the paid social or display budget that runs every week and drifts slowly, exactly the case where the VIFs in Step 7 were highest.
And the last row is the warning: fitting with a cubic on data whose effect dies after five weeks makes the Almon estimate worse than the free one. A cubic stretched over eleven lags cannot bend to a flat zero tail, so it bends the early weights instead. The Almon model trades variance for bias. When the variance is small, as with Northgate's clean pulses, the trade can go the wrong way. That is why Step 11 checks the tail and the F test rather than assuming the polynomial is free.
From the curve to the send cadence
The Marketing Analytics chapter turns the curve into a decision, and the numbers here support the same conclusion. On the current near monthly calendar, a send lands every four to five weeks. By then 93% to 98% of the previous send has arrived, and for the last week or so the list produces almost nothing from email.
At a three week cadence, the next send goes out when 78% of the previous one is in, so only about a fifth of it overlaps with the new one. At a fortnightly cadence only 52% has arrived when the next email lands, so nearly half overlaps, and a fresh message reaches readers who have not finished responding to the last. Three weeks removes the idle weeks while keeping the overlap small.
Example: what a three week cadence might add
Twelve sends a year become , call it 17. If each kept its full effect of about 128 orders:
that is orders against , so 640 extra orders a year. The model cannot promise that, because it has only ever seen monthly sends and knows nothing about fatigue and unsubscribes at a higher frequency. If each of the five extra sends delivered only 60% of the current effect, the gain would be . So the honest range is roughly 380 to 640 extra orders a year, and the way to narrow it is a split test: half the list on three weekly sends, half on monthly, for twelve weeks. Designing and reading that test is the subject of the A/B testing chapter later in this series.
One caution about using the total for a budget decision. 4.26 orders per 1,000 emails is the average effect at the volumes and frequency Northgate has run. The value of one more send is a marginal question, and a later chapter on media mix modelling returns to the difference between average and marginal returns. Foundations: marginal against average
The whole pipeline in one picture
The flow runs from the weekly table to the write up. The one loop is the tail check: if the last weights are not close to zero, lengthen the lag and start again from the lag columns. In real work the first box, with its time zones, test orders and missing send weeks, takes longer than every model in this chapter put together.
Pitfalls that only show up in code
The Marketing Analytics chapter lists the conceptual pitfalls: smooth curves cannot draw a cliff, an unrecorded event creates a phantom bump, and sends timed to expected demand get credit for demand that was coming anyway. These are the ones that hide in the code.
- Shifting a table with gaps.
shiftmoves rows. Reindex to a complete weekly calendar withfill_value=0for the sends, and assert that the index is evenly spaced. - Shifting across groups. If your table stacks two lists or two markets, a plain
shiftlets the last week of one leak into the first week of the next. Usedf.groupby("market")["emails_k"].shift(k). - UTC weeks. Convert order timestamps to the shop's time zone before cutting weeks, and cut them on the send weekday.
- Comparing models on different rows. AIC, BIC and F tests are only meaningful on identical samples. Drop the first rows for every candidate.
- Forgetting the covariance when you transform. The Almon weights are , and their standard errors come from , not from the standard errors of .
- Plain standard errors on weekly data. Use
cov_type="HAC"for the reported intervals. Plain errors look tighter than they deserve. - Chained assignment under pandas 3.0.
df["emails_k"][df["emails_k"] < 0] = 0no longer changes anything. Writedf.loc[df["emails_k"] < 0, "emails_k"] = 0.
For the person who commissions this
If you are the person paying for this analysis rather than running it, you do not need to read the code. You need to recognise a good answer and a weak one. A good answer is a curve, not a rate: the share of the effect in each week after the action, with the total, the peak and the point where it is over. It comes with an interval on the total, a holdout that shows the timing is right, and a sentence on whether your calendar is regular enough to make the measurement shaky.
Questions worth asking whoever does it:
- How many weeks after a send do you keep counting, and what happens to the total if you count one more?
- Show me the same week figure next to the curve's total. How far apart are they?
- Did you put the newsletter export on a full weekly calendar before building the lags?
- Which time zone and which weekday define the weeks?
- What do the lag VIFs look like, and did you plant a known curve on our calendar to check the method can find it?
- What did the holdout show, and in which weeks did the model miss?
- Does the recommendation allow for fatigue and unsubscribes, or only for the curve?
Building this kind of analysis, and the dashboards that keep it current, is a core part of my Data Science work. The client owns the code, the accounts and the data, and my prices are published on the pricing transparency page.
My view
My view: the lag curve is one of the most useful models a marketing team can own, and one of the least used, because the same week number is so easy to produce and so convincingly wrong. If you report anything for email or any channel with a slow effect, report the curve.
I would build the unrestricted model first, every time, and look at it before reaching for Almon. If the free weights already form a sensible shape, as they do on Northgate's clean pulses, the polynomial adds little and the unrestricted table is easier to explain. If they zigzag, check the VIFs: high values mean the restriction will help, and an always on channel almost always needs it. I would leave the Koyck regression in the textbooks, because on business data its total is too easily wrong by a factor of five. And I would never ship a curve without the planted curve check. It is the only test that tells you whether your data could have given a different answer, and it costs twenty lines.
The most valuable change is often not in the code at all. Moving a send date by a week now and then costs nothing and turns a calendar that can barely be measured into one that can.
Conclusion
A distributed lag model replaces one misleading number with a curve, and in Python it is a short pipeline: a complete weekly table in local time, lag columns with shift, an unrestricted fit to see the raw shape, VIFs to judge how much the lags overlap, the Almon columns for a smooth and stable curve, standard errors carried through with , a fair comparison of lag lengths on a fixed sample, a holdout, and a planted curve to prove the data can carry the answer.
For Northgate Hampers the answer is clear: the newsletter peaks one week after the send, has delivered 93% of its effect after three weeks, and brings about 4.26 orders per 1,000 emails, roughly 128 per send. That is more than four times what Priya was counting, and it argues for sending more often, not less, with a split test to find out how much more. The next chapter in this series moves from weekly totals to counts of individual customer actions, with Poisson regression.
