Instrumental Variables
Module 3 adjusted for every confounder it could measure and worried about the ones it could not. Instrumental variables (IV) promise something better: a source of variation in treatment that is unrelated to the patient's prognosis. That variation answers the question even when confounders are unmeasured. The classic instrument in pharmacoepidemiology is physician prescribing preference: some doctors start almost everyone eligible, others almost no one, and which doctor you have is close to random. Today you learn IV where the answer is known, then try it on Renavex and find out why it is harder than it looks.
By the end of today you can
- state the three IV conditions and the monotonicity assumption, and say who the compliers are
- check first-stage strength and know that a strong F does not guarantee precision
- compute preference instruments leave-one-out
- test the exclusion restriction's consequences: later treatment, co-treatments
- compare IV with the other designs and argue which assumptions are most credible
Today's 5.5-hour plan
In this lesson
36.1 IV where the answer is known (40 min)
An instrument Z must satisfy three conditions:
- relevance: Z changes treatment D;
- independence: Z is as good as random with respect to the outcome's other causes;
- exclusion: Z affects the outcome Y only through D.
The IV estimate is then the ratio of two intention-to-treat effects of Z: on the outcome (the reduced form) and on treatment (the first stage). With heterogeneous effects and a binary instrument, that ratio estimates the local average treatment effect (LATE): the effect among compliers, people whose treatment depends on the instrument. This assumes monotonicity: no one is treated because their doctor is low-preference.
def tsls(d, y, endog, instruments, exog, cluster):
"""Two-stage least squares with an intercept and exogenous covariates (a formula right-hand side), SEs
clustered by `cluster`. Returns dict(estimate, se, first_stage F (clustered Wald), n)."""
import statsmodels.formula.api as smf
from formulaic import model_matrix
W = model_matrix(f"1 + {exog}", d).to_numpy() if exog else np.ones((len(d), 1))
Z = np.column_stack([d[i].to_numpy(float) for i in instruments])
X = np.column_stack([d[endog].to_numpy(float), W])
ZZ = np.column_stack([Z, W])
Xh = ZZ @ np.linalg.lstsq(ZZ, X, rcond=None)[0]
b = np.linalg.lstsq(Xh, d[y].to_numpy(float), rcond=None)[0]
u = d[y].to_numpy(float) - X @ b
groups = pd.factorize(d[cluster])[0]
sg = pd.DataFrame(Xh * u[:, None]).groupby(groups).sum().to_numpy()
bread = np.linalg.pinv(Xh.T @ Xh)
G, n, k = len(sg), len(d), X.shape[1]
v = bread @ (sg.T @ sg) @ bread * G / (G - 1) * (n - 1) / (n - k)
fs = smf.ols(f"{endog} ~ {' + '.join(instruments)}" + (f" + {exog}" if exog else ""), d).fit(
cov_type="cluster", cov_kwds={"groups": groups})
F = float(fs.wald_test(" = 0, ".join(instruments) + " = 0", scalar=True).statistic) / len(instruments)
return {"estimate": float(b[0]), "se": float(np.sqrt(v[0, 0])), "first_stage_F": F, "n": n,
"first_stage": {i: float(fs.params[i]) for i in instruments}}
"""Day 36.1: instrumental variables where the answer is known - an unmeasured confounder, an instrument,
heterogeneous effects, and who the IV estimate is about (the compliers)."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from corridor.quasi import tsls # noqa: E402
rng = np.random.default_rng(36)
n = 200_000
u = rng.normal(size=n) # unmeasured severity: raises treatment and outcome
z = rng.binomial(1, 0.5, n) # high-preference prescriber
v = rng.normal(size=n)
d0 = (-1.2 + 0.0 + 0.8 * u + v > 0).astype(int) # treated if the prescriber were low-preference
d1 = (-1.2 + 1.0 + 0.8 * u + v > 0).astype(int) # ... if high-preference
d = np.where(z == 1, d1, d0)
tau = -2.0 - 1.5 * u # sicker patients benefit more
y = 10 + 3.0 * u + tau * d + rng.normal(size=n)
s = pd.DataFrame({"y": y, "d": d, "z": z, "g": np.arange(n)})
complier = (d1 == 1) & (d0 == 0)
print(f"shares: always-takers {np.mean(d0 == 1):.2f}, compliers {complier.mean():.2f}, never-takers {np.mean(d1 == 0):.2f}")
print(f"true average effect (everyone) {tau.mean():+.2f}; treated {tau[d == 1].mean():+.2f}; compliers {tau[complier].mean():+.2f}")
print(f"naive difference in means: {y[d == 1].mean() - y[d == 0].mean():+.2f}")
print(f"OLS (cannot adjust for u): {smf.ols('y ~ d', s).fit().params.d:+.2f}")
wald = (y[z == 1].mean() - y[z == 0].mean()) / (d[z == 1].mean() - d[z == 0].mean())
print(f"Wald estimator = reduced form / first stage = {y[z == 1].mean() - y[z == 0].mean():+.3f} / "
f"{d[z == 1].mean() - d[z == 0].mean():.3f} = {wald:+.2f}")
r = tsls(s, "y", "d", ["z"], "", "g")
print(f"2SLS: {r['estimate']:+.2f} (SE {r['se']:.3f}), first-stage F {r['first_stage_F']:,.0f}")
shares: always-takers 0.17, compliers 0.26, never-takers 0.56
true average effect (everyone) -2.00; treated -2.99; compliers -2.48
naive difference in means: -0.14
OLS (cannot adjust for u): -0.14
Wald estimator = reduced form / first stage = -0.639 / 0.264 = -2.43
2SLS: -2.43 (SE 0.047), first-stage F 17,762
Sicker patients are both treated more and do worse, so OLS finds almost no effect (−0.14) when the true average is −2.0. IV recovers −2.43, which is not the average effect for everyone (−2.0) or for the treated (−2.99), but the compliers' effect (−2.48). The IV answer is about a specific, usually unobservable, group. Always say which one.
36.2 Weak instruments (30 min)
"""Day 36.2: weak instruments - as the first stage weakens, 2SLS drifts towards OLS and its intervals lie."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
rng = np.random.default_rng(362)
n, reps, true = 2_000, 500, -2.0
print(f"{'first-stage strength':>21}{'median F':>10}{'median 2SLS':>13}{'middle 90% of 2SLS':>21}{'OLS':>7}{'CI covers':>11}")
for pi in (0.02, 0.05, 0.1, 0.2, 0.5):
est, F, cover, ols = [], [], 0, []
for _ in range(reps):
u, z = rng.normal(size=n), rng.normal(size=n)
d = pi * z + u + rng.normal(size=n)
y = true * d + 2 * u + rng.normal(size=n)
zc, dc, yc = z - z.mean(), d - d.mean(), y - y.mean()
b = (zc @ yc) / (zc @ dc)
fs = (zc @ dc) / (zc @ zc)
rf = dc - fs * zc
F.append(fs ** 2 / (rf @ rf / (n - 2) / (zc @ zc)))
e = yc - b * dc
se = np.sqrt((e @ e / (n - 2)) * (zc @ zc) / (zc @ dc) ** 2)
cover += abs(b - true) < 1.96 * se
est.append(b)
ols.append((dc @ yc) / (dc @ dc))
lo, hi = np.quantile(est, [0.05, 0.95])
print(f"{pi:>21}{np.median(F):>10.1f}{np.median(est):>+13.2f}{f'{lo:+.1f} to {hi:+.1f}':>21}{np.median(ols):>+7.2f}{cover / reps:>11.0%}")
print(f"(truth {true}; n = {n:,}, {reps} simulations each)")
first-stage strength median F median 2SLS middle 90% of 2SLS OLS CI covers
0.02 0.7 -1.32 -8.6 to +5.1 -1.00 96%
0.05 2.4 -1.94 -6.2 to -0.4 -1.00 95%
0.1 10.1 -1.98 -3.3 to -1.3 -1.00 94%
0.2 40.2 -2.01 -2.5 to -1.6 -1.02 96%
0.5 246.9 -2.01 -2.2 to -1.9 -1.11 97%
(truth -2.0; n = 2,000, 500 simulations each)
As the first stage weakens, 2SLS drifts towards the OLS estimate (−1.32 at F ≈ 1) and its spread explodes: 90% of estimates fall between −8.6 and +5.1. With F above about 10, the median is right and the spread is moderate. Stock and Yogo's "F > 10" is the old rule of thumb. Recent work (Lee, McCrary, Moreira and Porter, 2022) shows that standard t-tests need F above about 104 for a true 5% test, so report weak-instrument-robust intervals (Anderson–Rubin) when F is modest.
36.3 Prescriber preference in the sequential trials (40 min)
Each person in the RWE extract has a usual prescriber (275 in all). The prescriber's preference is the share of their other eligible person-trials that started Renavex: a leave-one-out rate, so a person's own decision is not part of their instrument.
def prescriber_preference(t):
"""Add each person-trial's usual prescriber and the prescriber's preference: the share of the prescriber's
OTHER eligible person-trials that started Renavex (leave-one-out), and an above-median indicator."""
import duckdb
from corridor.rwe import D
p = duckdb.sql(f"SELECT person_id, usual_prescriber FROM read_csv('{D}/rwe_persons.csv')").df()
t = t.merge(p, on="person_id")
g = t.groupby("usual_prescriber").start.agg(["sum", "count"])
t = t.join(g, on="usual_prescriber")
t["pref"] = (t["sum"] - t.start) / (t["count"] - 1)
t["pref_high"] = (t.pref > t.pref.median()).astype(int)
return t.drop(columns=["sum", "count"])
"""Day 36.3: the usual prescriber's preference as an instrument for starting Renavex, in the sequential trials."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import pandas as pd # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from corridor.quasi import prescriber_preference, tsls # noqa: E402
from corridor.tte import COVARIATES, load # noqa: E402
t = prescriber_preference(load())
X = COVARIATES + " + C(trial)"
print(f"{t.usual_prescriber.nunique()} prescribers; leave-one-out preference: median {t.pref.median():.4f}, "
f"10th-90th percentile {t.pref.quantile(0.1):.4f}-{t.pref.quantile(0.9):.4f} starts per person-trial")
q = pd.qcut(t.pref, 5, labels=False)
print("\nby fifth of prescriber preference: starts, and the measured confounders (they should not differ):")
print(t.groupby(q)[["start", "egfr", "albuminuria", "nephrology_care", "age", "qc"]].mean().round(3).to_string())
r = tsls(t, "kf24", "start", ["pref"], X, "usual_prescriber")
ols = smf.ols(f"kf24 ~ start + {X}", t).fit(cov_type="cluster", cov_kwds={"groups": t.usual_prescriber.factorize()[0]})
print(f"\nfirst stage F (clustered by prescriber): {r['first_stage_F']:.0f}")
print(f"24-month kidney failure, effect of starting (percentage points):")
print(f" OLS with covariates {100 * ols.params.start:+.2f} (95% CI {100 * ols.conf_int().loc['start', 0]:+.2f} to {100 * ols.conf_int().loc['start', 1]:+.2f})")
print(f" 2SLS {100 * r['estimate']:+.2f} (95% CI {100 * (r['estimate'] - 1.96 * r['se']):+.2f} to "
f"{100 * (r['estimate'] + 1.96 * r['se']):+.2f})")
275 prescribers; leave-one-out preference: median 0.0095, 10th-90th percentile 0.0011-0.0239 starts per person-trial
by fifth of prescriber preference: starts, and the measured confounders (they should not differ):
start egfr albuminuria nephrology_care age qc
pref
0 0.005 44.198 0.229 0.328 72.390 0.552
1 0.006 44.163 0.231 0.329 71.888 0.430
2 0.011 44.799 0.211 0.316 72.010 0.331
3 0.014 44.251 0.211 0.328 72.242 0.330
4 0.022 44.701 0.227 0.289 71.997 0.403
first stage F (clustered by prescriber): 309
24-month kidney failure, effect of starting (percentage points):
OLS with covariates -0.23 (95% CI -1.40 to +0.94)
2SLS -17.82 (95% CI -44.46 to +8.82)
The instrument is strong (F = 309) and looks independent: across fifths of preference, starts rise fourfold while eGFR, albuminuria and age barely move (province does: Quebec prescribers started later). But the 2SLS estimate is useless: −18 percentage points, with a confidence interval from −44 to +9. A strong F does not mean a precise answer. Starting in any given month is rare (about 1%), preference moves it by about 2 percentage points between low and high prescribers, and dividing a small outcome difference by a small treatment difference amplifies the noise.
36.4 A person-level design (30 min)
Make the treatment more common: a person-level landmark design (like Day 21's) on 1 July 2026. Treatment is starting Renavex in January–June 2026 (8%); the outcome is kidney failure from July 2026 to December 2028; the instrument is the prescriber's leave-one-out share of early starters. Build the file first:
"""Day 36 setup: the person-level landmark file for the IV analysis (m3/landmark_iv.parquet, git-ignored)."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
from corridor.db import warehouse # noqa: E402
from corridor.exposure import M3 # noqa: E402
from corridor.quasi import landmark_frame # noqa: E402
b = landmark_frame(warehouse())
path = os.path.join(M3, "landmark_iv.parquet").replace("\\", "/")
con = duckdb.connect()
con.register("b", b)
con.execute(f"COPY b TO '{path}' (FORMAT parquet)")
print(f"{len(b):,} people at 1 July 2026; {int(b.early.sum())} started Renavex in January-June 2026; "
f"{int(b.kf.sum())} kidney failures by December 2028 (m3/landmark_iv.parquet)")
8,736 people at 1 July 2026; 681 started Renavex in January-June 2026; 332 kidney failures by December 2028 (m3/landmark_iv.parquet)
"""Day 36.4: a person-level design - early start (first half of 2026) instrumented by prescriber preference."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from corridor.exposure import M3 # noqa: E402
from corridor.quasi import IV_COVARIATES, tsls # noqa: E402
b = duckdb.sql(f"SELECT * FROM read_parquet('{M3}/landmark_iv.parquet')").df()
print(f"{len(b):,} people; preference: median {b.pref.median():.3f}, 10th-90th percentile "
f"{b.pref.quantile(0.1):.3f}-{b.pref.quantile(0.9):.3f} early starters per patient")
for y, lab in (("kf", "kidney failure, Jul 2026-Dec 2028"), ("died", "death, Jul 2026-Dec 2028")):
r = tsls(b, y, "early", ["pref"], IV_COVARIATES, "usual_prescriber")
o = smf.ols(f"{y} ~ early + {IV_COVARIATES}", b).fit(cov_type="cluster", cov_kwds={"groups": b.usual_prescriber.factorize()[0]})
print(f"\n{lab} (percentage points): first-stage F {r['first_stage_F']:.0f}")
print(f" OLS {100 * o.params.early:+.1f} (95% CI {100 * o.conf_int().loc['early', 0]:+.1f} to {100 * o.conf_int().loc['early', 1]:+.1f})")
print(f" 2SLS {100 * r['estimate']:+.1f} (95% CI {100 * (r['estimate'] - 1.96 * r['se']):+.1f} to "
f"{100 * (r['estimate'] + 1.96 * r['se']):+.1f})")
8,736 people; preference: median 0.062, 10th-90th percentile 0.000-0.170 early starters per patient
kidney failure, Jul 2026-Dec 2028 (percentage points): first-stage F 111
OLS +0.1 (95% CI -2.0 to +2.2)
2SLS -11.4 (95% CI -19.6 to -3.3)
death, Jul 2026-Dec 2028 (percentage points): first-stage F 111
OLS +0.3 (95% CI -2.1 to +2.8)
2SLS -9.2 (95% CI -25.1 to +6.6)
Now the estimate is precise enough to exclude zero: −11.4 percentage points (95% CI −19.6 to −3.3), against an OLS estimate of +0.1. Is Renavex preventing one kidney failure for every nine early starters?
Check it in R:
# Day 36: the landmark IV in R with ivreg, SEs clustered by prescriber (sandwich::vcovCL).
suppressPackageStartupMessages({ library(DBI); library(duckdb); library(ivreg); library(sandwich); library(lmtest) })
con <- dbConnect(duckdb(shared_home = FALSE))
b <- dbGetQuery(con, "SELECT * FROM read_parquet('m3/landmark_iv.parquet')")
dbDisconnect(con, shutdown = TRUE)
x <- "egfr10 + albuminuria + sglt2_2025 + age10 + male + qc + nephrology_care + heart_failure + copd + prior_stays"
m <- ivreg(as.formula(paste("kf ~ early +", x, "|", x, "+ pref")), data = b)
ct <- coeftest(m, vcov = vcovCL(m, cluster = ~usual_prescriber))
cat(sprintf("2SLS kidney failure: %+.1f points (SE %.1f)\n", 100 * ct["early", 1], 100 * ct["early", 2]))
print(round(summary(m, diagnostics = TRUE)$diagnostics[1:2, c("statistic", "p-value")], 4)) # not clustered
2SLS kidney failure: -11.4 points (SE 4.2)
statistic p-value
Weak instruments 184.9567 0.0000
Wu-Hausman 4.8526 0.0276
36.5 The exclusion restriction (30 min)
The exclusion restriction says the prescriber affects kidney failure only through early Renavex. Test its consequences:
"""Day 36.5: does the instrument affect the outcome only through early Renavex? Check its other paths."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from corridor.exposure import M3 # noqa: E402
from corridor.quasi import IV_COVARIATES # noqa: E402
b = duckdb.sql(f"SELECT * FROM read_parquet('{M3}/landmark_iv.parquet')").df()
g = {"groups": b.usual_prescriber.factorize()[0]}
print("effect of a 10-point higher prescriber preference (percentage points), adjusted for covariates:")
for y, lab, d in (("early", "early Renavex start (the first stage)", b),
("later_start", "Renavex start after July 2026, among non-early", b[b.early == 0]),
("sglt2_after", "new SGLT2 inhibitor after July 2026", b)):
gg = {"groups": d.usual_prescriber.factorize()[0]}
m = smf.ols(f"{y} ~ pref + {IV_COVARIATES}", d).fit(cov_type="cluster", cov_kwds=gg)
lo, hi = m.conf_int().loc["pref"]
print(f" {lab:<50}{10 * m.params.pref:+.1f} ({10 * lo:+.1f} to {10 * hi:+.1f})")
effect of a 10-point higher prescriber preference (percentage points), adjusted for covariates:
early Renavex start (the first stage) +5.4 (+4.4 to +6.4)
Renavex start after July 2026, among non-early +17.3 (+14.8 to +19.9)
new SGLT2 inhibitor after July 2026 +3.2 (+2.3 to +4.1)
A 10-point higher preference raises early starts by 5 points, as intended. But among people who did not start early, it raises Renavex starts after July 2026 by 17 points, and it raises new SGLT2 inhibitor starts by 3 points. A high-preference prescriber does not just start Renavex early; they start it later too, and they prescribe the other kidney-protective drug more. All of that lowers kidney failure, and the IV estimate attributes all of it to the early starts. The exclusion restriction fails.
This is the general weakness of preference instruments: a doctor's preference is a practice style, not a single decision. Distance to a specialist, another common instrument, fails in a similar way: people who live far from a nephrologist also differ in everything else about their access to care.
Why it matters at work: physician preference instruments are common in pharmacoepidemiology submissions, and reviewers now ask the questions of 36.5: does the instrument affect other treatments, later treatment, or the patients each doctor sees? An IV estimate that is much larger than every other estimate is a signal to check, not a discovery.
Where you'll meet this: Brookhart and Schneeweiss's preference-based IV studies; IV analyses in CDA-AMC and FDA RWE submissions; Mendelian randomization (genes as instruments), which faces the same exclusion question
36.6 Truth check (30 min)
"""Day 36 truth check: what the generator says about the effects these IV analyses tried to estimate."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
from corridor.exposure import M3 # noqa: E402
from corridor.truth import TRUTH # noqa: E402
from corridor.tte import load # noqa: E402
t = load()
tr = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/rwe_sequential_truth.csv')").df()
d = t.assign(trial=t.trial.astype(int)).merge(tr, on=["person_id", "trial"])
ite = 100 * (d.kf24_start - d.kf24_no_start)
print(f"sequential trials, 24-month kidney failure: true effect of starting {ite.mean():+.2f} points (everyone), "
f"{ite[d.start == 1].mean():+.2f} (starters)")
b = duckdb.sql(f"SELECT * FROM read_parquet('{M3}/landmark_iv.parquet')").df()
s = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/rwe_strategies.csv')").df()
s = s[s.person_id.isin(b.person_id)].assign(kf=lambda x: x.kf_month.notna() & (x.kf_month < 36))
r = s.pivot(index="person_id", columns="strategy", values="kf")
eff = 100 * (r.renavex_itt.astype(int) - r.never.astype(int))
low = b.set_index("person_id").egfr.reindex(r.index) < 30
print(f"landmark population, 36-month kidney failure, start Renavex at month 0 (then usual care) vs never: "
f"{eff.mean():+.2f} points; eGFR < 30: {eff[low].mean():+.2f}")
z, dd = b.pref_high, b.early
fs = dd[z == 1].mean() - dd[z == 0].mean()
cm = lambda col: ((b[col] * dd)[z == 1].mean() - (b[col] * dd)[z == 0].mean()) / fs # noqa: E731
print(f"\nwho are the compliers (binary instrument)? mean eGFR {cm('egfr'):.1f}, share with eGFR < 30 "
f"{((b.egfr < 30).astype(int) * dd)[z == 1].mean() / fs - ((b.egfr < 30).astype(int) * dd)[z == 0].mean() / fs:.0%}; "
f"all early starters: eGFR {b.egfr[dd == 1].mean():.1f}, {(b.egfr[dd == 1] < 30).mean():.0%} below 30")
e = eff.reindex(b.person_id).to_numpy()
ce = ((e * dd)[z == 1].mean() - (e * dd)[z == 0].mean()) / fs
print(f"true effect averaged over the compliers (the same complier-mean formula applied to each person's true effect): "
f"{ce:+.1f} points")
print("(individual compliers are unknown, so this is the closest truth to the binary-instrument IV estimand)")
sequential trials, 24-month kidney failure: true effect of starting -0.47 points (everyone), -1.16 (starters)
landmark population, 36-month kidney failure, start Renavex at month 0 (then usual care) vs never: -1.75 points; eGFR < 30: -9.56
who are the compliers (binary instrument)? mean eGFR 32.4, share with eGFR < 30 47%; all early starters: eGFR 31.3, 53% below 30
true effect averaged over the compliers (the same complier-mean formula applied to each person's true effect): -4.5 points
(individual compliers are unknown, so this is the closest truth to the binary-instrument IV estimand)
For the sequential trials, the true effect is about −0.5 points for everyone and −1.2 for starters. The IV interval (−44 to +9) covers both and is useless.
For the landmark design, nobody knows who the compliers are. Their average characteristics can still be computed, and so can their average true effect (the same complier-mean formula, applied to each person's true effect). The compliers are sick: mean eGFR 32, 47% below 30. Their true effect is about −4.5 points. The continuous-instrument IV (−11.4) is more than twice that, and its interval only just reaches it. The binary instrument's −20 misses it entirely (see the exercise). The gap is the exclusion violation of 36.5: later Renavex and SGLT2 starts riding on the instrument.
Day 25's AIPW, with all its assumptions about measured confounding, came within 0.03 of its truth (risk ratio 0.80 vs 0.77). Here IV, which assumes away unmeasured confounding, is further off. That is not an argument against IV. It is a reminder that every design trades one untestable assumption for another, and the trade must be argued, not assumed.
36.7 Leaving yourself in (20 min)
Bug of the day. The preference computed from all the prescriber's patients, including the patient being analysed:
"""Day 36 bug of the day: the prescriber's preference computed from all their patients, including this one."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
from corridor.exposure import M3 # noqa: E402
from corridor.quasi import IV_COVARIATES, tsls # noqa: E402
b = duckdb.sql(f"SELECT * FROM read_parquet('{M3}/landmark_iv.parquet')").df()
for z, lab in (("pref", "leave-one-out"), ("pref_with_self", "including the patient")):
r = tsls(b, "kf", "early", [z], IV_COVARIATES, "usual_prescriber")
print(f"{lab:<24} first-stage F {r['first_stage_F']:>6.0f} 2SLS {100 * r['estimate']:+.1f} points (SE {100 * r['se']:.1f})")
print(f"prescribers' median panel: {b.groupby('usual_prescriber').size().median():.0f} patients")
leave-one-out first-stage F 111 2SLS -11.4 points (SE 4.2)
including the patient first-stage F 5110 2SLS -6.5 points (SE 2.3)
prescribers' median panel: 33 patients
With a median panel of 33 patients, each patient's own start is about 3% of their prescriber's rate. That mechanical correlation inflates the first stage from F = 111 to 5,110 and pulls the estimate towards OLS (−6.5). A spectacular F is a warning sign, not a reassurance. Leave-one-out (or a split-sample) preference is the standard fix.
Try it (15 min). Use a binary instrument, above vs below median preference, and compute the Wald estimator by hand.
Solution
"""Day 36 try it: a binary instrument (above-median preference) and the Wald estimator by hand."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
from corridor.exposure import M3 # noqa: E402
from corridor.quasi import IV_COVARIATES, tsls # noqa: E402
b = duckdb.sql(f"SELECT * FROM read_parquet('{M3}/landmark_iv.parquet')").df()
g = b.groupby("pref_high")[["early", "kf"]].mean()
rf, fs = g.kf[1] - g.kf[0], g.early[1] - g.early[0]
print(g.round(4).rename(index={0: "below median", 1: "above median"}).to_string())
print(f"\nWald: {100 * rf:+.2f} points / {100 * fs:.2f} points = {100 * rf / fs:+.1f} points per early start")
r = tsls(b, "kf", "early", ["pref_high"], IV_COVARIATES, "usual_prescriber")
print(f"2SLS with covariates: {100 * r['estimate']:+.1f} (SE {100 * r['se']:.1f}), first-stage F {r['first_stage_F']:.0f}")
early kf
pref_high
below median 0.0538 0.0439
above median 0.1027 0.0320
Wald: -1.18 points / 4.89 points = -24.2 points per early start
2SLS with covariates: -20.3 (SE 8.0), first-stage F 25
Patients of high-preference prescribers start early twice as often (10.3% vs 5.4%) and have fewer kidney failures (3.2% vs 4.4%). The Wald ratio, −1.18 / 4.89, is −24 points per early start; with covariates, −20 (F = 25). The binary instrument throws away information and sharpens the exclusion problem: the "high" prescribers differ in more than early starts.
36.8 Mini-project: the IV appendix (40 min)
Summarize the IV analyses for an appendix to the Module 3 RWE report in docs/iv_summary.csv:
"""Day 36 mini-project: an IV appendix table for the RWE report (docs/iv_summary.csv)."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
import pandas as pd # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.exposure import M3 # noqa: E402
from corridor.quasi import IV_COVARIATES, prescriber_preference, tsls # noqa: E402
from corridor.tte import COVARIATES, load # noqa: E402
t = prescriber_preference(load())
b = duckdb.sql(f"SELECT * FROM read_parquet('{M3}/landmark_iv.parquet')").df()
rows = []
for design, d, y, x, z in (("sequential trials, start this month", t, "kf24", "start", "pref"),
("landmark, start Jan-Jun 2026", b, "kf", "early", "pref"),
("landmark, binary instrument", b, "kf", "early", "pref_high")):
r = tsls(d, y, x, [z], (COVARIATES + " + C(trial)") if d is t else IV_COVARIATES, "usual_prescriber")
rows.append({"design": design, "instrument": z, "first_stage_F": round(r["first_stage_F"]),
"effect_pts": round(100 * r["estimate"], 1), "ci_low": round(100 * (r["estimate"] - 1.96 * r["se"]), 1),
"ci_high": round(100 * (r["estimate"] + 1.96 * r["se"]), 1)})
s = pd.DataFrame(rows)
s.to_csv(os.path.join(ROOT, "docs", "iv_summary.csv"), index=False)
print(s.to_string(index=False))
design instrument first_stage_F effect_pts ci_low ci_high
sequential trials, start this month pref 309 -17.8 -44.5 8.8
landmark, start Jan-Jun 2026 pref 111 -11.4 -19.6 -3.3
landmark, binary instrument pref_high 25 -20.3 -35.9 -4.7
Write the paragraph that goes with it: the instrument is strong and balanced on measured covariates, but it also predicts later Renavex and SGLT2 use, so the exclusion restriction is implausible. The IV estimates are reported as a sensitivity analysis and do not replace the primary analysis.
36.9 Save your work
python -m pytest -q
git add .
git commit -m "Day 36: instrumental variables with prescriber preference"
Day 36 checklist
- I can state the three IV conditions and the monotonicity assumption, and say who the compliers are
- I check first-stage strength and know that a strong F does not guarantee precision
- I compute preference instruments leave-one-out
- I test the exclusion restriction's consequences: later treatment, co-treatments
- I compare IV with the other designs and argue which assumptions are most credible
Bloc français (30 min)
Thème : les variables instrumentales.
La préférence du prescripteur sert souvent de variable instrumentale. Elle modifie la probabilité de commencer le Renavex et semble indépendante de l'état des patients. Mais un médecin qui prescrit tôt le Renavex le prescrit aussi plus tard, et il prescrit davantage d'inhibiteurs du SGLT2. La restriction d'exclusion n'est donc pas respectée, et l'estimation est exagérée.
| Français | English |
|---|---|
| la variable instrumentale | the instrumental variable |
| la préférence du prescripteur | prescriber preference |
| la pertinence | relevance |
| l'indépendance | independence |
| la restriction d'exclusion | the exclusion restriction |
| la monotonicité | monotonicity |
| les observants (compliers) | the compliers |
| l'effet local moyen du traitement | the local average treatment effect |
| l'instrument faible | the weak instrument |
| les doubles moindres carrés | two-stage least squares |
| la première étape | the first stage |
| l'estimateur de Wald | the Wald estimator |
Exercices
- Translate: "A strong first stage does not guarantee a precise estimate."
- Translate: « L'estimation par variables instrumentales concerne seulement les patients dont le traitement dépend du prescripteur. »
- In three French sentences, explain why the prescriber's preference violates the exclusion restriction here.
Réponses
- Une première étape solide ne garantit pas une estimation précise.
- "The instrumental variable estimate concerns only the patients whose treatment depends on the prescriber."
- Example: Le prescripteur influence aussi les débuts tardifs du Renavex et les débuts d'inhibiteurs du SGLT2. Ces traitements réduisent l'insuffisance rénale. L'instrument agit donc sur le résultat par d'autres voies que le traitement étudié.