Simultaneous equations in Python: two stage least squares, step by step
TL;DR
Difficulty: Advanced
When the ad budget is set from sales, a single regression credits the ads with every good month. On 36 simulated months it says £2.12 per pound; two stage least squares says £1.52, band £0.75 to £2.28.
- Plant a number, then find it: run your pipeline on simulated data with a known effect before you touch real data.
- IV2SLS from linearmodels is ten lines. The checks are the work: classic first stage F above 10, Sargan, Wu Hausman, Ljung Box.
- The first stage statistic changes with cov_type: 20 classic, 106 with kernel on the same data. Compare the classic F with 10.
- A passing Sargan test can mean one instrument is too weak to disagree. Check each instrument's own F.
- Lag by month, not by row, and use the figures known when the budget was set.
If next month's ad budget comes from this month's sales, a regression of sales on ad spend answers confidently and wrongly. This chapter rebuilds the Marketing Analytics chapter on simultaneous equations in Python: a simulated feedback loop with a known answer, the reduced form, two stage least squares by hand and with linearmodels, and the checks that decide whether the number deserves a budget.
If you only read one section
When a business sets next month's advertising budget from this month's sales, sales and advertising cause each other. A single regression of sales on ad spend then gives the ads the credit for every good month, and it does so with a small standard error and a convincing t statistic. Two stage least squares (2SLS) fixes the direction of causation by using only the part of ad spend that was decided for reasons unrelated to this month's sales, such as the written budget rule.
In Python the estimation itself is about ten lines with the linearmodels package. The work that decides whether the number is worth anything is elsewhere:
- An instrument you can defend in a sentence. Something that moves ad spend and reaches sales only through ad spend. Last month's sales under a written budget rule usually qualify. Cost per click and competitors' spend usually do not.
- Four checks, every time. A first stage F statistic above 10, an overidentification test that does not reject, a Wu Hausman test that tells you whether 2SLS differs from plain regression at all, and residuals without autocorrelation.
- A known answer test. Simulate your own business's feedback loop with an advertising effect you choose, run your exact pipeline on it, and check that it finds the number you planted. If your code cannot find a number you hid, it will not find the one the world hid.
For the person who commissions this work, the practical test is three questions. "What made ad spend move, other than sales?" "What is the first stage F, computed the classic way?" "Did you run the pipeline on simulated data with a known answer first?" An analyst who answers all three in plain words has done the work. In this chapter's example, the single regression says each pound of ads brings £2.12 of new bookings. Two stage least squares says £1.52, with a 95% band from £0.75 to £2.28. The first number would have doubled the budget. The second suggests a careful step up and a holdout test.
The idea that carries this chapter: plant a number, then find it
Here is the reader's question in full: how do I handle the case where marketing drives sales and sales drive marketing, in Python?
The concepts are explained in my Marketing Analytics chapter on simultaneous equations, when marketing causes sales and sales cause marketing. It covers why the single regression is biased, the reduced form, identification and the logic of instruments. Here I build all of it in Python, line by line, and add one habit that tutorials on instrumental variables rarely show.
The habit: before you estimate anything on real data, simulate data with the same feedback loop and an effect you chose, and run your pipeline on it. Instrumental variable code fails quietly. A lag aligned to the wrong month, an instrument column swapped for a control, a covariance option you did not mean, and the output still looks like a regression table. With real data you never know the true answer, so you cannot tell. With simulated data you do. I call it the known answer test, and every step below is built on it: the whole chapter runs on a simulated business whose true advertising effect is 1.50, so you can watch each method either find it or miss it.
Example: the agency's number against a planted 1.50
Vanlog is the invented software business of the Marketing Analytics series: a Rails SaaS from Manchester that gives plumbers, joiners and electricians one place for their calendar, quotes and invoices. Its founder sets next month's Google and Meta budget at roughly 25% of this month's new bookings and tops campaigns up mid month when things go well. His agency regressed bookings on ad spend and reported £2.10 of bookings per pound.
Plant the truth in a simulation of that loop: each pound of ads adds £1.50 of bookings, the founder's mid month reaction is 11p per pound of bookings, and the budget rule passes on 24p of every pound of last month's bookings. Then run both methods on 3,600 simulated months, far more than any business will ever have. Plain regression returns 1.96. Two stage least squares returns 1.50. The single regression does not get closer to the truth with more data. It just gets more certain about the wrong answer. That one run tells you which method your pipeline should use before you have looked at a single real booking, and the code that does it is in the final steps of this chapter.
Where this chapter sits, and what you need
This is chapter 21 of the Python programme and the ninth chapter of the series that rebuilds the Marketing Analytics models in Python. Read price elasticity with regression in Python first. Price and quantity are the textbook case of two variables that settle each other at the same time, and this chapter extends the regression workflow from there. The previous chapter, forecasting demand in Python, matters too, because autocorrelated shocks are what break lagged instruments. The modelling basics, formulas in statsmodels and reading a results table, are in statistical models in Python.
The data in this chapter are generated to resemble the example in the Marketing Analytics chapter: 36 months of Vanlog, averaging about £18,400 of new bookings, £4,600 of ad spend, 31 organic trial signups and an opening cash balance near £41,000 a month. The headline numbers land close to that chapter's (2.12 against 2.10 for the single regression, 1.52 against 1.50 for 2SLS), and where my simulated sample tells a slightly different story, I say so, because the differences are instructive.
The versions current on 27 May 2026, and the ones every output below comes from: Python 3.14, NumPy 2.4.6, pandas 3.0.3, statsmodels 0.14.6 and linearmodels 7.0.1 pandas 3.0, released in January 2026, made copy on write the default and removed the old month end alias "M". The code below avoids both traps.2 If you have not set up an environment before, chapter 1 of the foundations series walks through it.
python -m pip install numpy==2.4.6 pandas==3.0.3 statsmodels==0.14.6 linearmodels==7.0
Pinning exact versions is not pedantry. Instrumental variable statistics depend on small choices inside the library, and a pinned environment means the numbers in your memo can be rebuilt next year.
Step 1: write the system down before you write code
Two equations, one for each variable that is both a cause and an effect. The bookings equation says what drives new bookings:
Here is new bookings in pounds in month , is ad spend in the same month, is the number of organic trial signups, is a January indicator (one in January, zero otherwise), and is everything else that moved bookings that month and that nobody recorded. is the intercept, and are the effects of signups and January, and is the number the founder wants: pounds of bookings per pound of ads. The regression behind it is in Foundations: regression.
The spend equation says how the founder sets the budget:
Here is the intercept, is the mid month top up per pound of this month's bookings, is the budget rule applied to last month's bookings , is the effect of , the cash balance at the start of the month, and is the founder's mood, holidays and anything else that nudges spend. It is a second regression, as in Foundations: regression, and two equations at once are the bookkeeping of Foundations: matrices.
The point of writing this down first is not mathematics. It forces you to say which variables appear in which equation, and every later step, from the reduced form to the choice of instruments, follows from that one decision.
Example: the numbers planted for Vanlog
These are the structural values the simulation uses, taken from the Marketing Analytics chapter so the two read as a pair:
| Coefficient | Meaning | Planted value |
|---|---|---|
| Bookings in a month with no ads, signups or January | £7,830 | |
| Bookings per pound of ads | 1.50 | |
| Bookings per organic signup | £112 | |
| Extra bookings in January | £2,410 | |
| Intercept of the spend equation | minus £2,410 | |
| Mid month top up per pound of this month's bookings | 0.11 | |
| Budget rule per pound of last month's bookings | 0.24 | |
| Extra spend per pound in the bank | 0.014 |
Read the spend row by row and you have the founder's behaviour: about a quarter of last month's bookings, a modest top up when this month looks good, a little more when the account is healthy.
Step 2: simulate the feedback loop with a known answer
The simulation has one subtle line. In each month, bookings depend on spend and spend depends on bookings, so you cannot compute one and then the other. You solve both equations at once. Substitute the spend equation into the bookings equation and collect the terms on the left:
Every symbol is as above. The denominator is the loop's amplification: with the planted values it is , so any shock to bookings is multiplied by before the month settles. Once is known, spend follows from the spend equation. Ratios like this are explained in Foundations: ratios and rates.
First the imports and the planted values:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from linearmodels.iv import IV2SLS
# The truth we plant. Vanlog and every number here are invented.
# Bookings equation: what drives new bookings (in pounds)
A0, A_AD, A_SIGNUP, A_JAN = 7_830, 1.50, 112, 2_410
# Spend equation: how the founder sets ad spend
B0, B_NOW, B_LAST, B_CASH = -2_410, 0.11, 0.24, 0.014
Then a function that simulates any number of months. It takes the random generator as an argument, so the same function serves the main example, the simulation study and the test at the end. Seeded generators are covered in the NumPy chapter.
def simulate_vanlog(rng, n_months=36, ad_effect=A_AD, n_warm=24):
"""Simulate months of Vanlog in which bookings and ad spend cause each other."""
T = n_warm + n_months + 1 # warm up, the months we keep, one for the lag
months = pd.date_range(end="2026-04-01", periods=T, freq="MS")
signups = rng.poisson(31, T) # organic trial signups
jan = (months.month == 1).astype(int) # January indicator
u = rng.normal(0, 3_000, T) # booking shocks nobody records
v = rng.normal(0, 750, T) # the founder's mood and holidays
cash = np.empty(T)
cash[0] = 41_000
for t in range(1, T): # cash drifts around £41,000
cash[t] = 41_000 + 0.6 * (cash[t - 1] - 41_000) + rng.normal(0, 3_200)
bookings = np.empty(T)
ad_spend = np.empty(T)
bookings[0], ad_spend[0] = 18_400, 4_600
for t in range(1, T):
# the part of spend that is fixed before this month's bookings are known
planned = B0 + B_LAST * bookings[t - 1] + B_CASH * cash[t] + v[t]
# solve both equations at once: bookings need spend, spend needs bookings
bookings[t] = (A0 + ad_effect * planned + A_SIGNUP * signups[t]
+ A_JAN * jan[t] + u[t]) / (1 - ad_effect * B_NOW)
ad_spend[t] = planned + B_NOW * bookings[t] # the mid month top up
df = pd.DataFrame({"bookings": bookings, "ad_spend": ad_spend,
"organic_signups": signups, "opening_cash": cash,
"jan": jan}, index=months)
return df.iloc[n_warm:].round(0) # drop the warm up months
Two design choices are worth a sentence each. The 24 warm up months let the loop forget its arbitrary starting value of £18,400 before anything is kept. And the loop over months is a plain Python loop on purpose: each month depends on the one before, which is exactly the case where vectorisation does not apply.
Example: 36 months that look like Vanlog's
rng = np.random.default_rng(55411)
df = simulate_vanlog(rng)
df["bookings_lag1"] = df["bookings"].shift(1, freq="MS") # last month's bookings, matched by date
df = df.dropna()
print(len(df), df.index.min().date(), df.index.max().date())
print(df[["bookings", "ad_spend", "organic_signups", "opening_cash"]].mean().round(0))
# 36 2023-05-01 2026-04-01
# bookings 18456.0
# ad_spend 4598.0
# organic_signups 32.0
# opening_cash 41332.0
Thirty six months, May 2023 to April 2026, with averages of £18,456 of bookings, £4,598 of ad spend, 32 signups and £41,332 in the bank. That is Vanlog as the Marketing Analytics chapter describes it.
Notice shift(1, freq="MS") instead of a bare shift(1). The first moves the dates forward by one month start and lets pandas match the values by date. The second moves values down by one row. On a complete monthly series they agree. On a real export with a missing month they do not, and the section on data traps shows what happens then. Wes McKinney's book draws the same distinction, noting that "naive shifts leave the index unmodified", which is why some data is discarded.3 The book's examples pass freq="M", an alias pandas 3.0 no longer accepts. Month end is now "ME", month start "MS".
Step 3: the single regression is confidently wrong
Start with what the agency did, a plain regression with the controls:
ols = smf.ols("bookings ~ ad_spend + organic_signups + jan", data=df).fit()
print(ols.params.round(2))
print(ols.bse.round(2))
print(round(ols.rsquared, 2))
# Intercept 5461.79
# ad_spend 2.12
# organic_signups 91.92
# jan 3850.10
#
# Intercept 2572.92
# ad_spend 0.26
# organic_signups 72.10
# jan 1547.17
#
# 0.7
£2.12 of bookings per pound of ads, a standard error of 0.26, an R squared of 0.70. Every number looks healthy, and the main one is about 40% too high. The reason is in the spend equation. A month with a positive booking shock has higher bookings, so the founder tops up, so spend is higher in the same month. The regression sees high spend next to high bookings and hands the credit to the ads. Ordinary least squares (OLS) settles on
where is the probability limit, the value the estimate settles on as the sample grows without end, is the OLS estimate, the true effect, the part of ad spend that signups and January do not explain, its covariance with the booking shock and its variance. The second term is the simultaneity bias, and it is positive whenever . Covariance is in Foundations: correlation. The sample size does not appear anywhere in that formula, which is the whole problem.
Example: more data, same wrong answer
A simulation study makes the formula visible. The function below estimates the ad effect both ways with plain NumPy, which is fast enough to run thousands of times. The line Z @ np.linalg.lstsq(Z, X, rcond=None)[0] replaces each regressor with its fitted value from the instruments, which is the first stage for all columns at once. Step 6 builds the same thing step by step.
def ols_and_2sls(d):
"""Ad effect by OLS and by 2SLS, with plain NumPy (fast enough for thousands of runs)."""
one = np.ones(len(d))
X = np.column_stack([one, d["ad_spend"], d["organic_signups"], d["jan"]])
Z = np.column_stack([one, d["organic_signups"], d["jan"],
d["bookings_lag1"], d["opening_cash"]])
y = d["bookings"].to_numpy()
b_ols = np.linalg.lstsq(X, y, rcond=None)[0][1]
X_hat = Z @ np.linalg.lstsq(Z, X, rcond=None)[0] # project X onto Z
b_2sls = np.linalg.lstsq(X_hat, y, rcond=None)[0][1]
return b_ols, b_2sls
def monte_carlo(n_months, runs=400, seed=1):
rng = np.random.default_rng(seed)
out = []
for _ in range(runs):
d = simulate_vanlog(rng, n_months)
d["bookings_lag1"] = d["bookings"].shift(1)
out.append(ols_and_2sls(d.dropna()))
return pd.DataFrame(out, columns=["ols", "tsls"])
rows = {}
for n in (36, 360, 3_600):
mc = monte_carlo(n)
rows[n] = {"OLS mean": mc["ols"].mean(), "OLS sd": mc["ols"].std(),
"2SLS median": mc["tsls"].median(), "2SLS sd": mc["tsls"].std()}
print(pd.DataFrame(rows).T.round(2))
# OLS mean OLS sd 2SLS median 2SLS sd
# 36 1.91 0.26 1.41 0.43
# 360 1.95 0.08 1.48 0.13
# 3600 1.96 0.02 1.50 0.04
The run takes about 20 seconds on a laptop. Inside the simulation a plain shift(1) is safe, because simulated months never have gaps.
Read the two columns of spread. OLS narrows from 0.26 to 0.02 around 1.96, a number about 30% too high. Two stage least squares narrows from 0.43 to 0.04 around the truth. At 36 months it is noisy and its median of 1.41 sits a little low, which is the small sample behaviour the Marketing Analytics chapter describes: consistent, but not unbiased in small samples. In this system the average OLS bias is about 0.46. Vanlog's particular 36 months drew an OLS estimate of 2.12, a little above that average, which is exactly the kind of variation a single history gives you.
My simulated loop is a little gentler than the one in the Marketing Analytics chapter, where OLS averaged about 2.1. The reason is instrument strength. To keep the first stage F near 20, as in that chapter's table, the founder's own whims () have to be fairly large, and they dilute the bias. That trade between bias and instrument strength is real, and it is the subject of Step 8.
Step 4: the reduced form in two regressions
The reduced form writes each endogenous variable (the ones the system itself determines, bookings and spend) through the exogenous ones only, the variables decided outside the loop:
Here , , , and mean what they meant in Step 1, is the intercept, to are the total effects of each outside driver on bookings once the loop has run its course, and is a mixture of the two shocks and . It is an ordinary regression, see Foundations: regression.
Here is ad spend, the intercept, to the total effects of the same drivers on spend, and another mixture of and (Foundations: regression). Both right hand sides contain only exogenous variables, so plain regression is fine here. The Marketing Analytics chapter shows that and , so their ratio is , the ad effect. The budget rule moves spend for a reason unrelated to this month's shock, and whatever bookings do in response is the ad effect, cleanly.
Example: recovering about 1.5 from a ratio
rf_bookings = smf.ols("bookings ~ organic_signups + jan + bookings_lag1 + opening_cash", data=df).fit()
rf_spend = smf.ols("ad_spend ~ organic_signups + jan + bookings_lag1 + opening_cash", data=df).fit()
for z in ["bookings_lag1", "opening_cash"]:
print(z, round(rf_bookings.params[z], 4), round(rf_spend.params[z], 4),
round(rf_bookings.params[z] / rf_spend.params[z], 2))
# bookings_lag1 0.4264 0.2789 1.53
# opening_cash 0.0001 -0.0174 -0.0
Each pound of last month's bookings adds 28p to this month's ad spend and 43p to this month's bookings. The 43p arrive only because of the 28p, so a pound of ads is worth . The planted values give and , so the estimates sit close to the truth.
The cash ratio is nonsense, and that is the useful part of this example. In these 36 months the cash balance barely moved spend: its coefficient is even slightly negative, against a planted 0.014. A ratio with a denominator near zero can be anything. The Marketing Analytics chapter's data had cash pulling its weight. Mine does not, and a later section shows why that matters for a test you might otherwise trust.
Step 5: identification, counted on paper and then checked in the data
An equation can be estimated only if enough exogenous variables are excluded from it. The order condition says it as a count:
where is the number of exogenous variables in the whole system, the number in the equation you want to estimate, and the number of endogenous variables in that equation, including the one on the left. With more excluded variables than needed the equation is overidentified, with exactly enough it is exactly identified, and with fewer it cannot be estimated. Counting like this is the bookkeeping of Foundations: matrices.
Vanlog has exogenous variables: signups, January, last month's bookings and cash. The bookings equation contains two of them, so : overidentified by one. The spend equation contains the other two and excludes signups and January, so it also passes, .
The count is necessary and not sufficient. The excluded variables must actually move the endogenous variable they stand in for, and that is a question for the data, not the page.
Example: the spend equation passes the count and fails the data
Estimate the spend equation the same way, with signups and January as the instruments for this month's bookings. The linearmodels formula puts the endogenous variable and its instruments in square brackets:
spend_iv = IV2SLS.from_formula(
"ad_spend ~ 1 + bookings_lag1 + opening_cash + [bookings ~ organic_signups + jan]",
data=df).fit(cov_type="unadjusted", debiased=True)
print(spend_iv.params.round(3))
print(spend_iv.first_stage.diagnostics[["partial.rsquared", "f.stat"]].round(2))
# Intercept -817.580
# bookings_lag1 0.238
# opening_cash -0.018
# bookings 0.094
#
# partial.rsquared f.stat
# bookings 0.14 2.53
The budget rule comes back as 0.238, almost exactly the planted 0.24. Tempting. But the first stage F is 2.53, far below the rule of thumb of 10. Signups and January move bookings, but in 36 months not by enough to tell the founder's reaction apart from noise. The order condition said yes. The data say: not with this sample.
This is the second original point of this chapter, and it is easy to state. Identification on paper is not identification in data. The order condition counts columns. Only the first stage F tells you whether those columns carry information. In Vanlog's case it means the ad effect can be estimated with some confidence and the founder's mid month reaction hardly at all, and a memo should say exactly that.
Step 6: two stage least squares by hand
Building 2SLS manually once is the best way to understand what the package does, and it shows a trap that catches people who stop halfway.
Stage one regresses ad spend on every exogenous variable in the system and keeps the fitted values. That is precisely the spend reduced form from Step 4. Stage two regresses bookings on the fitted spend and the controls:
df["ad_spend_hat"] = rf_spend.fittedvalues # stage one = the spend reduced form
stage2 = smf.ols("bookings ~ ad_spend_hat + organic_signups + jan", data=df).fit()
print(round(stage2.params["ad_spend_hat"], 2), round(stage2.bse["ad_spend_hat"], 2))
# 1.52 0.55
The coefficient is right: 1.52. The standard error of 0.55 is wrong. The second regression thinks the fitted spend is ordinary data, measured without error, and computes its residuals from the fitted spend rather than the real one.4 The correct calculation uses the matrix form of 2SLS:
Here is the vector of estimated coefficients of the bookings equation, is the vector of monthly bookings, holds the regressors of the bookings equation (a constant, ad spend, signups, January), holds all exogenous variables plus the constant, the prime is the transpose, the power is the matrix inverse, and is the projection onto the space the instruments span. Multiplying by replaces the spend column with its first stage fit and leaves the other columns as they are. Matrix multiplication is explained in Foundations: matrices.
Example: same coefficient, different standard error
y = df["bookings"].to_numpy()
X = np.column_stack([np.ones(len(df)), df[["ad_spend", "organic_signups", "jan"]]])
Z = np.column_stack([np.ones(len(df)), df[["organic_signups", "jan", "bookings_lag1", "opening_cash"]]])
P = Z @ np.linalg.solve(Z.T @ Z, Z.T) # projection onto the instruments
theta = np.linalg.solve(X.T @ P @ X, X.T @ P @ y)
resid = y - X @ theta # residuals with the REAL spend
n, k = X.shape
sigma2 = resid @ resid / (n - k)
se = np.sqrt(np.diag(sigma2 * np.linalg.inv(X.T @ P @ X)))
print(theta.round(2), se.round(2))
# [8.07758e+03 1.52000e+00 9.72200e+01 3.76796e+03] [2.97948e+03 3.80000e-01 7.78700e+01 1.67065e+03]
The same coefficients, in the order constant, ad spend, signups and January: £8,078, 1.52, £97 and £3,768. The standard error on ad spend is 0.38, not 0.55. The only difference is the line marked "REAL spend": the residuals use the spend the founder actually paid. Here the shortcut overstated the uncertainty. In other data it understates it, which is the more dangerous direction. Either way, do the two stages by hand once to understand them, then never report their standard errors.
Step 7: the same model with linearmodels
linearmodels is a package by Kevin Sheppard for instrumental variable, panel and system models, and its IV2SLS class does exactly what Step 6 did, with the standard errors done properly.5 There are two ways to call it. The array interface names each role explicitly:
exog = df[["organic_signups", "jan"]].assign(const=1.0)
iv = IV2SLS(dependent=df["bookings"], exog=exog, endog=df["ad_spend"],
instruments=df[["bookings_lag1", "opening_cash"]]).fit(cov_type="unadjusted", debiased=True)
print(iv.params.round(2))
print(iv.std_errors.round(2))
print(round(iv.rsquared, 2))
print(iv.conf_int().loc["ad_spend"].round(2))
# organic_signups 97.22
# jan 3767.96
# const 8077.58
# ad_spend 1.52
#
# organic_signups 77.87
# jan 1670.65
# const 2979.48
# ad_spend 0.38
#
# 0.65
#
# lower 0.75
# upper 2.28
exog are the controls that are their own instruments, endog the variable the loop contaminates, and instruments the excluded exogenous variables. The constant has to be added by hand in this interface, which .assign(const=1.0) does. Forget it and the model is estimated through the origin without complaint, one more reason for the known answer test.
The formula interface says the same in one string, with the bracket syntax you met in Step 5:
iv_f = IV2SLS.from_formula(
"bookings ~ 1 + organic_signups + jan + [ad_spend ~ bookings_lag1 + opening_cash]",
data=df).fit(cov_type="unadjusted", debiased=True)
print(round(iv_f.params["ad_spend"], 2))
# 1.52
I use cov_type="unadjusted", debiased=True here so the numbers match the textbook calculation from Step 6 and the classic first stage F in Step 8. The default is "robust", standard errors that allow the size of the shocks to vary from month to month.6 Step 8 compares the options, because the choice changes more than you would expect.
Example: reading Vanlog's table line by line
| Term | OLS estimate | OLS std error | 2SLS estimate | 2SLS std error |
|---|---|---|---|---|
| Intercept (£) | 5,462 | 2,573 | 8,078 | 2,979 |
| Ad spend (£ of bookings per £) | 2.12 | 0.26 | 1.52 | 0.38 |
| Organic trial signups (£ per signup) | 92 | 72 | 97 | 78 |
| January (£) | 3,850 | 1,547 | 3,768 | 1,671 |
| R squared | 0.70 | 0.65 |
The ad row is the headline. The single regression overstated the effect by , close to the 40% of the Marketing Analytics chapter. The standard error rose from 0.26 to 0.38: that is the price of consistency. The 95% band for 2SLS runs from 0.75 to 2.28. The band for OLS runs from 1.59 to 2.65, narrower and centred on the wrong place. Bands are explained in Foundations: confidence intervals.
The intercept rises under 2SLS because the ads get less credit, so more of a normal month stays in the baseline. Both versions pass through the averages. For 2SLS: , exactly the average month. That identity is a quick check that you have read the table correctly.
R squared falls, as it should. 2SLS does not try to maximise fit, and a higher R squared is no argument for OLS. The signups and January rows barely move, because nothing in the feedback loop is about the calendar or the directory listing.
What it means for the budget: at £1.52 of first year bookings per pound and the 80% gross margin assumed in the Marketing Analytics chapter, a pound of ads returns , so £1.22 of contribution in year one. Fine, not a licence to double the budget. The bottom of the band, 0.75, would not even pay for itself. A linear model also says nothing about whether the next pound earns as much as the average one, see Foundations: marginal versus average.
Step 8: the checks before you trust the number
Four checks, each one line of code. The results object in linearmodels carries them.7
fs = iv.first_stage.diagnostics
print(fs[["partial.rsquared", "f.stat", "f.pval", "f.dist"]].round(3))
print(iv.sargan)
print(iv.wu_hausman())
# partial.rsquared f.stat f.pval f.dist
# ad_spend 0.564 20.09 0.0 F(2,31)
#
# Sargan's test of overidentification
# H0: The model is not overidentified.
# Statistic: 0.0511
# P-value: 0.8211
# Distributed: chi2(1)
#
# Wu-Hausman test of exogeneity
# H0: All endogenous variables are exogenous
# Statistic: 8.5427
# P-value: 0.0064
# Distributed: F(1,31)
And the residuals, with the Ljung Box test from statsmodels, which asks whether residuals are correlated with their own past values at the lags you name:8
from statsmodels.stats.diagnostic import acorr_ljungbox
print(acorr_ljungbox(iv.resids, lags=[1, 3, 6]).round(2))
# lb_stat lb_pvalue
# 1 0.85 0.36
# 3 4.95 0.18
# 6 5.09 0.53
Example: four checks on Vanlog's 36 months
- First stage F: 20.1. The two instruments together explain 56% of the variation in ad spend that the controls leave over (the partial R squared). The usual rule of thumb treats an F below 10 as weak, meaning 2SLS is biased and its standard errors cannot be trusted.9 20.1 passes.
- Sargan test: p value 0.82. It asks whether the two instruments tell the same story about the ad effect. They do not contradict each other. Hold that thought for two sections. The wording of the null hypothesis in the printout is the package's own, and it means "the overidentifying restrictions hold".
- Wu Hausman test: p value 0.006. It asks whether ad spend could be treated as exogenous, in effect whether OLS and 2SLS differ by more than noise. They do. Had this test not rejected, I would keep the simpler OLS model and say so.
- Ljung Box: p values 0.36, 0.18 and 0.53. No sign that this month's residual carries last month's. That matters doubly here, because the lagged bookings instrument is valid only if the booking shocks do not linger. If they did, last month's bookings would carry this month's shock and the instrument would be contaminated. The forecasting chapter in this series covers autocorrelation in detail.
Add one picture to the four numbers: fitted spend from stage one against actual spend, as a scatter plot. It shows at a glance how much of the movement in spend the instruments explain. The design choices for that kind of chart are in showing relationships with scatter plots.
The F you compare with 10 depends on one keyword
Here is a trap that tutorials rarely mention. The first stage statistic that linearmodels reports depends on the covariance option you pass to fit, and the rule of thumb of 10 was written for the classic F statistic, the one that assumes shocks of constant size.9
for cov in ["unadjusted", "robust", "kernel"]:
r = IV2SLS(df["bookings"], exog, df["ad_spend"], df[["bookings_lag1", "opening_cash"]]).fit(cov_type=cov)
d = r.first_stage.diagnostics.loc["ad_spend"]
print(cov, round(r.std_errors["ad_spend"], 2), round(d["f.stat"], 1), d["f.dist"])
# unadjusted 0.36 23.3 F(2,31)
# robust 0.33 65.4 chi2(2)
# kernel 0.2 211.3 chi2(2)
Three things happen. Without debiased=True the unadjusted statistic is scaled by and reads 23.3 instead of the classic 20.1.6 With "robust" or "kernel" the statistic is a Wald statistic distributed as chi squared, so it must be divided by the number of instruments, two here, to be on the F scale at all. And even then the numbers diverge: 32.7 for robust and 105.7 for kernel. The kernel option estimates standard errors that allow for heteroskedasticity and autocorrelation (HAC), choosing its bandwidth from the data. On 36 months there is very little data to choose from, and here it produced a standard error of 0.20, about half the others, while the Ljung Box test found no autocorrelation to correct.
Example: one dataset, four first stage statistics
The data did not change between the four bars. Only one keyword did. Had Vanlog's instruments been borderline, with a classic F of 7, the kernel version could easily have shown 30 and waved them through. My rule: for the weak instrument check, report the classic F from cov_type="unadjusted", debiased=True. For the standard errors in the memo, use robust ones on monthly data, and keep the kernel option for histories long enough to estimate autocorrelation, with the Ljung Box check telling you whether you need it at all. The Marketing Analytics chapter's code fits with "kernel" for the standard errors, which is a reasonable choice on a longer history. On 36 months, compare it with the others before you trust it.
A quiet overidentification test is not always good news
The Sargan test compares instruments with each other. If one instrument is so weak that it carries almost no information, it cannot disagree with the other, and the test passes because it has nothing to compare. A high p value then means "no evidence of conflict", not "both instruments are fine".
Example: what the cash balance alone can tell you
Fit the model with the opening cash balance as the only instrument:
weak = IV2SLS(df["bookings"], exog, df["ad_spend"], df[["opening_cash"]]).fit(cov_type="unadjusted", debiased=True)
print(round(weak.params["ad_spend"], 2), round(weak.std_errors["ad_spend"], 2))
print(weak.first_stage.diagnostics[["f.stat"]].round(2))
# 1.03 2.68
# f.stat
# ad_spend 0.48
An estimate of 1.03 with a standard error of 2.68 and a first stage F of 0.48. Cash, on its own, knows nothing about the ad effect in these 36 months. The Sargan p value of 0.82 in Step 8 was not two instruments agreeing. It was one instrument talking and one too quiet to object. This is the third practical point of the chapter: when the overidentification test passes, check each instrument's own first stage F before you call it agreement. It costs one line per instrument.
It is also a reminder of what weak instruments do in general. With a weak first stage, 2SLS can be badly biased even in large samples, and with many weak instruments it drifts back towards the OLS answer, the very thing you were escaping.10 Here the lagged bookings carry the identification. That is fine, as long as the memo says so.
Data traps that break instruments in real exports
The simulation is clean. Real exports are not, and three traps in them go straight to the heart of instrumental variables, because they quietly break the claim that the instrument has nothing to do with this month's shock.
The lag must be the previous month, not the previous row
Shop and accounting exports drop months with no activity, or someone deletes a broken month and forgets. A plain shift(1) then pairs a month with whatever row came before it.
Example: a December that went missing
gappy = df[["bookings"]].drop(pd.Timestamp("2024-12-01")) # one month missing in the export
gappy["lag_wrong"] = gappy["bookings"].shift(1) # previous ROW
gappy["lag_right"] = gappy["bookings"].shift(1, freq="MS") # previous MONTH
print(gappy.loc["2024-11-01":"2025-02-01"])
# bookings lag_wrong lag_right
# 2024-11-01 13930.0 19208.0 19208.0
# 2025-01-01 12460.0 13930.0 NaN
# 2025-02-01 7974.0 12460.0 12460.0
With December missing, lag_wrong tells the model that January's budget was set from November's bookings of £13,930. It was not. lag_right leaves January empty, which is honest, and dropna() removes it. Under pandas 3.0 the new columns on gappy never touch df, because every subset behaves as a copy.2 The time series chapter of the foundations series covers date indexes in depth.
The lag must be the number the founder saw
The budget rule uses last month's bookings as the founder saw them when he set the budget. Today's export shows last month's bookings as they stand today, after refunds, cancellations and corrections processed since. That difference is not cosmetic. Cancellations processed this month often come from this month's events, a competitor's offer or a bug in the onboarding flow, which are exactly the shocks the instrument must not know about. Use the restated figure and the instrument contains a piece of this month's shock.
Example: March as seen on 31 March and as exported in May
On 31 March the dashboard showed £21,300 of March bookings, and April's budget was set at roughly 25% of that. In April a rival launches a free tier, and £1,400 of March sign ups cancel during their trial, recorded against March. The May export shows March at £19,900. The rival's launch also depresses April's new bookings. Now the lagged instrument, built from the export, is low in exactly the month when the booking shock is negative: correlated with , which is precisely what an instrument must not be. The fix is unglamorous: keep a monthly snapshot of the figure used for the budget decision, or rebuild it from booking dates and the refund dates that were known at month end. Loading business data into pandas covers the exports themselves.
Spend and bookings must share a month boundary
An ad platform's report and a shop or SaaS export do not necessarily cut the day in the same time zone: one may follow the account's settings, the other store times in UTC. Near midnight on the last day of the month, a pound of spend and the booking it produced can land in different months. With monthly data the effect is usually small, but it is systematic, and in a model whose whole point is timing, it is worth five minutes to make both sides use the same calendar.
Finding an instrument: say the exclusion out loud
Python cannot tell you whether an instrument is valid. The first stage F tells you whether it is strong, and the overidentification test whether instruments agree. Neither can tell you whether the instrument reaches sales by some route other than ad spend. That is an argument about the business, and the way to test it is to say the exclusion as a sentence: "X changes bookings only through how much we spend on ads."
| Candidate | The sentence | Verdict |
|---|---|---|
| Last month's bookings, under a written budget rule | Last month's bookings change this month's bookings only through the budget, once organic signups are in the model | Good, if shocks do not linger (check Ljung Box) |
| Opening cash balance | The money in the bank changes bookings only through the ads it pays for | Plausible, often weak |
| Financial year budget reset | A new budget in April changes bookings only through the spend it releases | Good, if nothing else changes in April |
| Platform accidents: a suspended account, a tracking outage | The outage changes bookings only through the spend it stopped | Good, and rare |
| Cost per click in the category | Fails: at a fixed budget a higher cost per click buys fewer clicks, so it moves bookings directly | Not an instrument |
| Competitors' spend | Fails: it changes your demand directly | Not an instrument |
| Weather | Fails for most seasonal businesses: it moves demand and spend | Not an instrument |
Example: the bookkeeper's cost per click and the founder's holiday
Vanlog's bookkeeper suggests a third instrument: the monthly Google cost per click for "job management software". Say it out loud: "the cost per click changes bookings only through how much the founder spends". It does not. At an unchanged budget, a higher cost per click buys fewer clicks and fewer trials, so it moves bookings with spend held still. It fails before any data is loaded, and adding it would push the estimate in an unknown direction while the Sargan test might well stay quiet.
The founder's fortnight away each August passes the sentence test: "the founder being on holiday changes bookings only because nobody tops up the campaigns". That holds for a business whose customers neither know nor care where he is, as long as nothing else at Vanlog stops while he is away. In code it is one indicator column added to the instruments. Check its own first stage F before celebrating: two weeks a year is not much variation. The Marketing Analytics chapter lists more candidates, and my earlier article on causal inference in marketing with propensity scores and instruments puts instruments next to the other tools.
Above every instrument sits the one that needs no argument: a randomised holdout. If you can switch spend off in a random set of regions or weeks, do that, and use 2SLS to make sense of the years when nobody did.
Make the known answer test permanent
The idea from the top of this chapter becomes a test function that runs with the rest of your analysis. It plants three different effects, simulates a long history for each, and checks that the estimator finds them. The reproducible workflow chapter shows how to run functions like this with pytest on every change.
def test_pipeline_recovers_a_planted_effect():
for planted in (0.5, 1.5, 2.5):
d = simulate_vanlog(np.random.default_rng(7), n_months=3_600, ad_effect=planted)
d["bookings_lag1"] = d["bookings"].shift(1)
_, estimate = ols_and_2sls(d.dropna())
print(planted, round(estimate, 3))
assert abs(estimate - planted) < 0.1, (planted, estimate)
test_pipeline_recovers_a_planted_effect()
# 0.5 0.492
# 1.5 1.49
# 2.5 2.48
Example: what the test catches
Planted 0.5, found 0.492. Planted 1.5, found 1.49. Planted 2.5, found 2.48. The pipeline passes. Now break it on purpose, the way real code breaks: take the first value that ols_and_2sls returns instead of the second, which is the OLS estimate, and the test fails on every planted value, because OLS finds 1.21, 1.95 and 2.62. That is a mistake caught before it reaches a budget decision. When you extend the simulation with a trap from your own data, such as cancellations that follow this month's shock, the same test tells you whether your pipeline survives it. It is ten lines, runs in a few seconds, and I would not send a 2SLS estimate to anyone without it.
Not every slip is caught, and it helps to know which. Leaving the constant out of the instrument matrix, for instance, still passes here (0.47, 1.48 and 2.47), because the other instruments happen to carry the level. The test proves that the pipeline can find the truth in a world like the one you simulated. It cannot prove that your world is like the simulation. That part stays with the sentence test for instruments.
Planting several values matters. A pipeline that always returns about 1.5, for example because a column was hard coded during debugging, would pass a test with a single planted 1.5. It cannot pass with 0.5 and 2.5 as well.
The whole workflow on one page
Top to bottom, the known answer test comes before any real data, and both exits that stop the work are legitimate results. "The data cannot answer this" is a finding, not a failure.
For the person who commissions this
You do not need to read the code to judge the work. Ask these questions, and listen for plain answers:
- Is anything in our business, written or habitual, setting marketing spend from sales? How did the model account for it?
- What are the instruments, and what is the sentence that says they reach sales only through spend?
- What is the first stage F, computed the classic way, and what is each instrument's own F?
- How far did the answer move between the single regression and 2SLS, and did the Wu Hausman test say the move was real?
- Was the pipeline run on simulated data with a known answer first, and did it find it?
- Were the lagged figures the ones known at the time, or today's restated export?
- What is the band, and does the recommendation survive its lower end?
Turning questions like these into a model you own, in your own repository, is the kind of Data Science work I do. The fees are published on my transparent pricing page.
My view
My view: two stage least squares in Python is easy to run and easy to run wrongly, and the difference never shows in the output. The ten lines of linearmodels are the least of it. The value is in four things that take longer: a written down system before any code, an exclusion you can say in one sentence, the classic first stage F next to every instrument's own, and a known answer test that proves the pipeline can find a number you planted.
I would also be honest about what 36 months can carry. In Vanlog's data the ad effect is estimable and the founder's own reaction is not, the cash balance is a passenger, and the band runs from 0.75 to 2.28. That is enough to stop a budget from doubling on the strength of 2.12. It is not enough to fine tune spend to the pound. For that, design the next year so the data answer the question: a planned holdout, or a step change in spend committed in advance. The best instrument is the one you designed.
Conclusion
When ads drive sales and sales drive the ad budget, a single regression is biased in a predictable direction, and more data only makes it more sure of itself. In Python, the cure is short: simulate the loop, find the planted effect, fit IV2SLS with the instruments the budget rule gives you, and run the four checks. On Vanlog's simulated 36 months that turns a flattering £2.12 per pound into an honest £1.52, with a band wide enough to keep everyone careful.
Three habits carry beyond this example. Plant a number before you look for one. Treat identification as something the first stage F confirms, not something the order condition grants. And when the overidentification test smiles, check that both instruments were actually in the room.
