Instrumental Variables in Python: 2SLS with linearmodels

Estimate a causal effect when a confounder you can't measure biases OLS, using an instrument and two-stage least squares in Python with linearmodels IV2SLS.

Instrumental variables (IV) estimate a causal effect when an unmeasured confounder biases a regression. In Python, IV2SLS.from_formula("y ~ 1 + controls + [treatment ~ instrument]", data) from the linearmodels package runs two-stage least squares (2SLS). An instrument is a variable that shifts the treatment but affects the outcome only through it, such as a randomly sent email that encourages users to try a feature. The code targets linearmodels 7.1 and statsmodels 0.14.

Quick Example

Users who adopt a feature tend to be more motivated, and motivated users spend more anyway, so a regression of spend on adoption is biased. A randomly sent email nudge gives an instrument. This runs without downloads (pip install linearmodels statsmodels):

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from linearmodels.iv import IV2SLS

rng = np.random.default_rng(23)
n = 5000
motivation = rng.normal(size=n)                      # unobserved confounder
tenure = rng.normal(24, 8, size=n).clip(1)           # observed control
nudge = rng.integers(0, 2, size=n)                   # instrument: randomly sent email
p_adopt = 1 / (1 + np.exp(-(-0.8 + 1.6 * nudge + 1.0 * motivation)))
adopt = (rng.random(n) < p_adopt).astype(int)        # treatment: adopted the feature
spend = 20 + 5.0 * adopt + 6.0 * motivation + 0.3 * tenure + rng.normal(0, 8, size=n)  # true effect = 5
df = pd.DataFrame({"spend": spend, "adopt": adopt, "nudge": nudge, "tenure": tenure})

ols = smf.ols("spend ~ adopt + tenure", df).fit(cov_type="HC1")
iv = IV2SLS.from_formula("spend ~ 1 + tenure + [adopt ~ nudge]", df).fit(cov_type="robust")

print("OLS :", round(ols.params["adopt"], 2), ols.conf_int().loc["adopt"].round(2).to_list())
print("2SLS:", round(iv.params["adopt"], 2), iv.conf_int().loc["adopt"].round(2).to_list())

The true effect is 5.0. OLS gives 9.53 (95% interval 8.99 to 10.07), nearly double, because adopters are the motivated users. 2SLS gives 3.45 (1.67 to 5.22), an interval that covers the truth. It is noisy: the price of IV is a wider interval.

Point estimates and 95 percent intervals: OLS at 9.53 far above the true effect of 5, 2SLS at 3.45 with an interval that contains 5

What Makes a Valid Instrument?

Condition Meaning Can you test it?
Relevance The instrument moves the treatment Yes: the first-stage F statistic
Independence The instrument is as good as random, unrelated to the confounders Only by design (randomization is best)
Exclusion The instrument affects the outcome only through the treatment No, it has to be argued

Here the email is randomized, so independence holds. Exclusion requires that the email does not change spending by itself, which would fail if the email contained a discount.

How Does Two-Stage Least Squares Work?

The first stage regresses the treatment on the instrument. The second stage regresses the outcome on the predicted treatment. The predicted part of adoption is driven only by the random nudge, so it is free of the confounder.

Two bar charts: adoption is 36 percent without the email and 67 percent with it, and average spend is 29.22 without and 30.30 with

With a binary instrument, the 2SLS estimate is the Wald ratio: the effect of the email on spend divided by its effect on adoption. Here that is (30.30 - 29.22) / (0.673 - 0.356) = 3.41, close to the 3.45 from the regression that also adjusts for tenure.

You can run the two stages by hand to see the mechanics, but do not use the standard errors from the second stage:

first = smf.ols("adopt ~ nudge + tenure", df).fit()
df["adopt_hat"] = first.fittedvalues
second = smf.ols("spend ~ adopt_hat + tenure", df).fit()
print("manual 2SLS coefficient:", round(second.params["adopt_hat"], 2))
print("first-stage F on the instrument:", round(float(first.tvalues["nudge"] ** 2), 1))

The coefficient matches IV2SLS at 3.45. The second-stage standard errors treat the fitted values as if they were data and are wrong, so use IV2SLS for inference.

How Strong Must the Instrument Be?

Check the first-stage F statistic for the instrument. linearmodels reports it:

print(iv.first_stage.diagnostics.T)

Here the first-stage F statistic is about 557. A common rule of thumb is that an F below 10 signals a weak instrument. Weak instruments make 2SLS estimates unstable and biased toward OLS. To see this, the same experiment was simulated 400 times with a strong nudge (+1.6 on the log-odds of adoption) and with a nearly useless one (+0.05):

Histogram of 2SLS estimates over 400 simulations: the strong instrument clusters tightly around the true effect of 5, the weak instrument is spread from below minus 40 to above 50

Instrument Median estimate Interquartile range Median first-stage F
Strong 5.02 1.30 569
Weak 7.65 33.4 0.8

The strong instrument is centered on the truth with a narrow spread. The weak one has a median of 7.65 and an interquartile range 25 times wider, so any single estimate is close to meaningless.

What Does IV Actually Estimate?

IV gives the local average treatment effect (LATE): the effect for users whose adoption was changed by the instrument, the "compliers". It says nothing about users who would adopt regardless, or never adopt. In this simulation the effect is the same for everyone, so LATE equals the average effect. In real data it may not.

Practical Tips

  • Prefer instruments that come from randomization (encouragement designs, randomized offers, lotteries). Natural instruments need an argument for the exclusion restriction, and readers will challenge it.
  • Report the first-stage F statistic next to the estimate.
  • Expect wide intervals. Compare the OLS and IV intervals before deciding the IV result is worth the noise.
  • With an A/B test where only some users take up the treatment, the assignment is the instrument and 2SLS gives the effect on those who took it.
  • Use robust standard errors (cov_type="robust"), or clustered ones if units repeat.

Similar Topics