Instrumental variables
Use a variable that moves the treatment but reaches the outcome only through it, and check instrument strength, endogeneity and overidentification.
What runs in CodeSplash
- STAT182Hausman specification test Runs in CodeSplash
- STAT183Durbin–Wu–Hausman endogeneity tests Runs in CodeSplash
- STAT184Sargan overidentification test Runs in CodeSplash
- STAT185Hansen J test Runs in CodeSplash
- STAT186Anderson–Rubin test Runs in CodeSplash
- Instrumental variables (2SLS / LIML / GMM) Verified in Python and R
You will be able to
- State the three conditions an instrument must meet
- Spot a weak instrument, and use Anderson–Rubin intervals when you have one
- Read Wu–Hausman, Sargan and Hansen's J for what they can and can't show
Read first
When you can't adjust your way out
ReadAn unmeasured confounder moves both treatment and outcome, so adjustment can't help. Suppose, though, that you have a variable that nudges the treatment and has no other route to the outcome. Then the changes it causes in treatment are free of that confounder.
Such a variable is an instrumentInstrumental variableA variable that shifts treatment but affects the outcome only through treatment.. It has to meet three conditions:
- Relevance: it moves the treatment.
- Independence: it's as good as randomly assigned, given the covariates.
- Exclusion: it reaches the outcome only through the treatment. This is the exclusion restrictionExclusion restrictionAn instrument affects the outcome only through the treatment. Data can't confirm this; you argue it..
Only the first can be tested directly.
Two stages
ReadTwo-stage least squares uses only the part of treatment the instrument explains:
The first stageFirst stageThe regression of the treatment on the instrument; it shows how strongly the instrument moves the treatment. shows how hard the instrument pushes. The second stage uses the fitted values.
The estimate is a local effectLocal average treatment effectThe average effect among units whose treatment is changed by an instrument or a cutoff.: it applies to units whose treatment the instrument changes, the compliers. Under monotonicity, no one is pushed the other way.
Which way will it move?
PredictPredict first
Simulated earnings data have a hidden factor that raises both the treatment and earnings. How will the IV estimate compare with OLS?
Reveal
OLS gives 2.58, and 2SLS gives 2.02, with an interval from 1.83 to 2.22. Positive confounding pushed OLS up. The Wu–HausmanDurbin–Wu–Hausman testCompares OLS with instrumental variables estimates. A large gap suggests the treatment is endogenous, so OLS is biased. test of endogeneity gives p < .001, so the data speak against treating this treatment as exogenous.
Read a strong result
In the appb = 2.02, SE = 0.10, t(597) = 20.18, p < .001, 95% CI [1.83, 2.22]
- Effect of x
- 2.023
- 95% CI
- [1.826, 2.220]
- p
- < .001
- First-stage F
- 101.05
- Anderson–Rubin 95% set
- [1.749, 2.250]
Assumptions
- Instrument strength — The effective F is 100.4 (≥ 23 clears the Montiel Olea–Pflueger 10% worst-case bias bar).
- Overidentifying restrictions — The robust score test does not reject (p = .937); it cannot rule out that all instruments are invalid in the same way.
- Endogeneity of the treatment — Wu–Hausman p < .001: OLS and IV differ, consistent with confounding of the treatment.
- OLS against IV (Hausman) — Hausman contrast χ²(1) = 54.01, p < .001: OLS and IV differ — consistent with an endogenous treatment (if the instruments are valid).
- Exclusion restriction — The instruments must affect the outcome only through the treatment — attest why (it cannot be tested with one instrument).
Second stage (robust HC1 standard errors)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| Intercept | 1.120 | 0.0788 | 14.208 | 1.124e-39 |
| w | 0.4428 | 0.0720 | 6.148 | 1.435e-9 |
| x | 2.023 | 0.1002 | 20.180 | 1.946e-69 |
First stage
| Treatment | F (excluded instruments) | p | Partial R² |
|---|---|---|---|
| x | 101.05 | 1.621e-38 | 0.2457 |
- Exogenous controls: w; t with 597 df.
The exact R script · R R version 4.5.1 (2025-06-13)
# Instrumental variables (2SLS / LIML / GMM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.iv 1.1.2 · spec fb90dd684aedbe56
# Dataset: c1_iv (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_iv.parquet", col_select = c("earnings (k)", "x", "z1", "z2", "w")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("earnings (k)", "x", "z1", "z2", "w")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("earnings (k)", "x", "z1", "z2", "w")) # infinite values stop the run (registry/errors.yaml)
# %% Design
Y <- "earnings (k)"
TREATMENTS <- c("x")
INSTRUMENTS <- c("z1", "z2")
COVARIATES <- c("w")
CLUSTER <- NULL
CATEGORICAL <- c(NULL)
BOOLEAN <- c(NULL)
estimator <- "2sls"
se_kind <- if (!is.null(CLUSTER)) "cluster" else "robust" # classical | robust | cluster
conf <- 0.95
if (length(INSTRUMENTS) < length(TREATMENTS)) stop("IV needs at least as many instruments as endogenous treatments.")
numeric_of <- function(col) {
v <- df[[col]]
if (is.factor(v)) { # booleans (and 2-level text) -> 0/1 for "true" / the last level
lv <- levels(v)
return(as.numeric(as.character(v) == if ("true" %in% lv) "true" else lv[length(lv)]))
}
as.numeric(v)
}
design <- function(cols) {
out <- list()
for (c in cols) {
if (c %in% CATEGORICAL) {
for (lv in levels(df[[c]])[-1]) out[[sprintf("%s[%s]", c, lv)]] <- as.numeric(as.character(df[[c]]) == lv)
} else {
out[[c]] <- numeric_of(c)
}
}
out
}
y <- as.numeric(df[[Y]])
cov_cols <- design(COVARIATES)
X <- cbind(const = rep(1, nrow(df)), if (length(cov_cols)) do.call(cbind, cov_cols) else NULL)
D <- do.call(cbind, setNames(lapply(TREATMENTS, numeric_of), TREATMENTS))
Z <- do.call(cbind, setNames(lapply(INSTRUMENTS, numeric_of), INSTRUMENTS))
clusters <- if (!is.null(CLUSTER)) as.character(df[[CLUSTER]]) else NULL
n <- nrow(df)
# The first stage regresses each treatment on the covariates and instruments: it needs more rows than columns.
cs_check_rows(n, ncol(X) + ncol(Z) + 1, "Instrumental-variable regression")
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = Y)
names_x <- c("Intercept", names(cov_cols), TREATMENTS)
# %% Estimate: 2SLS with ivreg + sandwich, LIML with the k-class twin (R has no standard LIML)
if (estimator == "2sls") {
dd <- data.frame(y = y, X[, -1, drop = FALSE], D, Z, check.names = FALSE)
names(dd) <- c("y", if (ncol(X) > 1) paste0("c", seq_len(ncol(X) - 1)), paste0("d", seq_len(ncol(D))), paste0("z", seq_len(ncol(Z))))
exog <- if (ncol(X) > 1) paste0("c", seq_len(ncol(X) - 1)) else character(0)
fml <- as.formula(paste("y ~", paste(c(exog, paste0("d", seq_len(ncol(D)))), collapse = " + "), "|",
paste(c(exog, paste0("z", seq_len(ncol(Z)))), collapse = " + ")))
fit <- ivreg::ivreg(fml, data = dd)
b <- unname(coef(fit))
V <- switch(se_kind,
classical = vcov(fit),
robust = sandwich::vcovHC(fit, type = "HC1"),
cluster = sandwich::vcovCL(fit, cluster = clusters, type = "HC1"))
V <- unname(V)
resid <- unname(residuals(fit))
kappa <- 1
} else if (estimator == "gmm") {
# Two-step efficient GMM: the codesplashr twin (= linearmodels IVGMM with debiased covariance).
gmm <- cs_causal_iv_gmm2s(y, X, D, Z, se_kind, clusters)
b <- gmm$b
V <- gmm$V
resid <- gmm$e
kappa <- 1
} else {
kappa <- cs_causal_iv_liml_kappa(y, X, D, Z)
kc <- cs_causal_iv_kclass(y, X, D, Z, kappa, se_kind, clusters)
b <- kc$b
V <- unname(kc$V)
resid <- kc$e
}
k <- length(b)
df_resid <- n - k
qt_ <- qt(0.5 + conf / 2, df_resid)
j0 <- ncol(X) + 1
est <- b[j0]
se <- sqrt(V[j0, j0])
tstat <- est / se
p <- 2 * pt(-abs(tstat), df_resid)
ci_low <- est - qt_ * se
ci_high <- est + qt_ * se
# %% Diagnostics (twins, identical in Python and R)
fs <- cs_causal_iv_first_stage(D, X, Z, se_kind, clusters)
first_stage_f <- min(vapply(fs, function(f) f$f, numeric(1)))
effective_f <- if (length(TREATMENTS) == 1) fs[[1]]$effective_f else NULL
ar <- if (TRUE && length(TREATMENTS) == 1) cs_causal_iv_anderson_rubin(y, D[, 1], X, Z, se_kind, clusters, conf, est, 20 * se + 5 * abs(est)) else NULL
overid <- if (length(INSTRUMENTS) <= length(TREATMENTS)) {
NULL
} else if (estimator == "gmm") {
list(stat = gmm$j, df = gmm$j_df, p = gmm$j_p) # Hansen's J (Sargan with classical errors)
} else {
cs_causal_iv_overid(resid, X, Z, length(TREATMENTS), se_kind, clusters)
}
hz <- cs_causal_iv_hausman(y, X, D, Z)
wh <- cs_causal_iv_wu_hausman(y, X, D, Z, se_kind, clusters)
ols_estimate <- cs_causal_iv_ols(y, cbind(X, D))$b[ncol(X) + 1]
# %% Checks
checks <- list()
add_check <- function(...) checks[[length(checks) + 1]] <<- list(...)
strength <- if (!is.null(effective_f)) effective_f else first_stage_f
strength_name <- if (!is.null(effective_f)) "effective F" else "smallest first-stage F"
if (strength < 10) {
add_check(id = "weak_iv", label = "Instrument strength", status = "fail", downgrade_to = "L1",
detail = sprintf("The %s is %.1f (< 10): the instruments are weak, the 2SLS interval is unreliable — report the Anderson–Rubin set.", strength_name, strength))
} else {
add_check(id = "weak_iv", label = "Instrument strength", status = "pass",
detail = paste0(sprintf("The %s is %.1f", strength_name, strength),
if (strength >= 23.1) " (≥ 23 clears the Montiel Olea–Pflueger 10% worst-case bias bar)." else " (≥ 10)."))
}
if (!is.null(overid)) {
oname <- if (se_kind == "classical") "Sargan" else if (estimator == "gmm") "Hansen J" else "robust score"
if (overid[["p"]] < 0.05) {
add_check(id = "overid", label = "Overidentifying restrictions", status = "concern",
detail = sprintf("The %s test rejects (%s): the instruments disagree, so at least one may violate the exclusion restriction (or effects are heterogeneous).", oname, cs_fmt_p(overid[["p"]])))
} else {
add_check(id = "overid", label = "Overidentifying restrictions", status = "pass",
detail = sprintf("The %s test does not reject (%s); it cannot rule out that all instruments are invalid in the same way.", oname, cs_fmt_p(overid[["p"]])))
}
} else {
add_check(id = "overid", label = "Overidentifying restrictions", status = "info",
detail = "Exactly identified (one instrument per treatment): instrument validity cannot be tested.")
}
add_check(id = "endogeneity", label = "Endogeneity of the treatment", status = "info",
detail = if (wh[["p"]] < 0.05) sprintf("Wu–Hausman %s: OLS and IV differ, consistent with confounding of the treatment.", cs_fmt_p(wh[["p"]]))
else sprintf("Wu–Hausman %s: no evidence that OLS is biased; OLS is more precise if the treatment is exogenous.", cs_fmt_p(wh[["p"]])))
if (!is.null(hz$chi2)) {
add_check(id = "hausman", label = "OLS against IV (Hausman)", status = "info",
detail = paste0(sprintf("Hausman contrast χ²(%d) = %.2f, %s: ", as.integer(hz$df), hz$chi2, cs_fmt_p(hz$p)),
if (hz$p < 0.05) "OLS and IV differ — consistent with an endogenous treatment (if the instruments are valid)."
else "no significant difference between OLS and IV; OLS would be more precise if the treatment is exogenous."))
}
add_check(id = "exclusion", label = "Exclusion restriction", status = "info",
detail = "The instruments must affect the outcome only through the treatment — attest why (it cannot be tested with one instrument).")
# %% Result
se_all <- sqrt(diag(V))
coef_rows <- data.frame(term = names_x, estimate = b, se = se_all, t = b / se_all, p = 2 * pt(-abs(b / se_all), df_resid))
fs_rows <- data.frame(treatment = TREATMENTS, f = vapply(fs, function(f) f$f, numeric(1)), p = vapply(fs, function(f) f$p, numeric(1)),
partial_r2 = vapply(fs, function(f) f$partial_r2, numeric(1)))
binary <- TREATMENTS[1] %in% BOOLEAN
pct <- sprintf("%.0f%%", conf * 100)
g3 <- function(x) formatC(x, digits = 3, format = "g")
summary <- paste0(
sprintf("Instrumenting %s with %s, ", TREATMENTS[1], paste(INSTRUMENTS, collapse = ", ")),
if (binary) sprintf("%s changes %s by %s", TREATMENTS[1], Y, g3(est)) else sprintf("a one-unit increase in %s changes %s by %s", TREATMENTS[1], Y, g3(est)),
sprintf(" (%s CI [%s, %s], %s); ordinary least squares gives %s. ", pct, g3(ci_low), g3(ci_high), cs_fmt_p(p), g3(ols_estimate)),
sprintf("The %s is %.1f", strength_name, strength),
if (strength < 10) "; the instruments are weak, so the Anderson–Rubin set is the safer interval." else "."
)
values <- list(
estimate = est, se = se, t = tstat, p_value = p, ci_low = ci_low, ci_high = ci_high, n = n, df_resid = df_resid,
estimator = estimator, kappa = kappa, se_type = se_kind,
first_stage_f = first_stage_f, effective_f = effective_f, ols_estimate = ols_estimate,
k_instruments = length(INSTRUMENTS), k_treatments = length(TREATMENTS),
wu_hausman_f = wh[["f"]], wu_hausman_p = wh[["p"]],
overid_stat = if (!is.null(overid)) overid[["stat"]] else NULL, overid_df = if (!is.null(overid)) overid[["df"]] else NULL,
overid_p = if (!is.null(overid)) overid[["p"]] else NULL,
hausman_chi2 = hz$chi2, hausman_df = hz$df, hausman_p = hz$p,
ar_p = ar$p0, ar_ci_low = ar$low, ar_ci_high = ar$high, ar_shape = ar$shape,
estimand = "LATE",
effect_label = if (binary) sprintf("Effect of %s on %s for units whose treatment the instruments shift (compliers)", TREATMENTS[1], Y)
else sprintf("Effect of a one-unit increase in %s on %s for units whose treatment the instruments shift", TREATMENTS[1], Y),
claim_level_max = "L3"
)
for (j in seq_along(names_x)) {
values[[sprintf("coef[%s]", names_x[j])]] <- b[j]
values[[sprintf("coef_se[%s]", names_x[j])]] <- se_all[j]
}
for (j in seq_along(fs)) {
values[[sprintf("first_stage_f[%s]", TREATMENTS[j])]] <- fs[[j]]$f
values[[sprintf("first_stage_p[%s]", TREATMENTS[j])]] <- fs[[j]]$p
values[[sprintf("partial_r2[%s]", TREATMENTS[j])]] <- fs[[j]]$partial_r2
}
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
statistics <- list(
list(key = "estimate", label = sprintf("Effect of %s", TREATMENTS[1]), value = est),
list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
list(key = "p_value", label = "p", value = p, format = "p"),
list(key = "first_stage_f", label = "First-stage F", value = first_stage_f)
)
if (!is.null(ar)) statistics[[length(statistics) + 1]] <- list(key = "ar_ci", label = sprintf("Anderson–Rubin %s set", pct), value = list(ar$low, ar$high))
cs_publish(list(
method = "causal.iv",
methodVersion = "1.1.2",
title = paste0("Instrumental variables (", switch(estimator, "2sls" = "2SLS", liml = "LIML", gmm = "efficient GMM"), ")"),
engine = cs_engine_info("ivreg", "sandwich", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("b = %s, SE = %s, t(%d) = %s, %s, %s CI [%s, %s]", cs_fmt_num(est), cs_fmt_num(se), df_resid, cs_fmt_num(tstat), cs_fmt_p(p), pct,
cs_fmt_num(ci_low), cs_fmt_num(ci_high)),
statistics = statistics,
tables = list(
list(key = "coefficients", title = sprintf("Second stage (%s standard errors)", switch(se_kind, classical = "classical", robust = "robust HC1", cluster = paste("clustered by", CLUSTER))),
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "p")),
rows = coef_rows),
list(key = "first_stage", title = "First stage",
columns = list(list(key = "treatment", label = "Treatment", type = "string"), list(key = "f", label = "F (excluded instruments)", type = "number"),
list(key = "p", label = "p", type = "p"), list(key = "partial_r2", label = "Partial R²", type = "number")),
rows = fs_rows)
),
assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = if (c$status == "concern") "warn" else c$status, detail = c$detail)),
checks = checks,
warnings = warnings,
notes = list(paste0(sprintf("Exogenous controls: %s; t with %d df.", if (length(COVARIATES)) paste(COVARIATES, collapse = ", ") else "none", df_resid),
if (estimator == "liml") sprintf(" LIML κ = %.4f.", kappa) else "",
if (estimator == "gmm") " Two-step efficient GMM weighted by the inverse moment covariance from 2SLS residuals." else "")),
values = values
))
b = 2.02, SE = 0.10, t(597) = 20.18, p < .001, 95% CI [1.83, 2.22]
- Effect of x
- 2.023
- 95% CI
- [1.826, 2.220]
- p
- < .001
- First-stage F
- 101.05
- Anderson–Rubin 95% set
- [1.749, 2.250]
Assumptions
- Instrument strength — The effective F is 100.4 (≥ 23 clears the Montiel Olea–Pflueger 10% worst-case bias bar).
- Overidentifying restrictions — The robust score test does not reject (p = .937); it cannot rule out that all instruments are invalid in the same way.
- Endogeneity of the treatment — Wu–Hausman p < .001: OLS and IV differ, consistent with confounding of the treatment.
- OLS against IV (Hausman) — Hausman contrast χ²(1) = 54.01, p < .001: OLS and IV differ — consistent with an endogenous treatment (if the instruments are valid).
- Exclusion restriction — The instruments must affect the outcome only through the treatment — attest why (it cannot be tested with one instrument).
Second stage (robust HC1 standard errors)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| Intercept | 1.120 | 0.0788 | 14.208 | 1.124e-39 |
| w | 0.4428 | 0.0720 | 6.148 | 1.435e-9 |
| x | 2.023 | 0.1002 | 20.180 | 1.946e-69 |
First stage
| Treatment | F (excluded instruments) | p | Partial R² |
|---|---|---|---|
| x | 101.05 | 1.621e-38 | 0.2457 |
- Exogenous controls: w; t with 597 df.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Instrumental variables (2SLS / LIML / GMM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.iv 1.1.2 · spec fb90dd684aedbe56
# Dataset: c1_iv (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from linearmodels.iv import IV2SLS, IVLIML
from scipy import stats
import codesplash as cs
from codesplash.causal import iv as csiv
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_iv.parquet", columns=["earnings (k)", "x", "z1", "z2", "w"])
n_input = len(df)
df = df.dropna(subset=["earnings (k)", "x", "z1", "z2", "w"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["earnings (k)", "x", "z1", "z2", "w"]) # infinite values stop the run (registry/errors.yaml)
# %% Design
Y = "earnings (k)"
TREATMENTS = ["x"]
INSTRUMENTS = ["z1", "z2"]
COVARIATES = ["w"]
CLUSTER = None
CATEGORICAL = []
BOOLEAN = []
estimator = "2sls"
se_kind = "cluster" if CLUSTER else "robust" # classical | robust | cluster
conf = 0.95
if len(INSTRUMENTS) < len(TREATMENTS):
raise ValueError("IV needs at least as many instruments as endogenous treatments.")
def numeric(col: str) -> np.ndarray:
s = df[col]
if isinstance(s.dtype, pd.CategoricalDtype): # booleans (and 2-level text) → 0/1 for "true" / the last level
lv = [str(x) for x in s.cat.categories]
return (s.astype(str) == ("true" if "true" in lv else lv[-1])).to_numpy(dtype=float)
return s.to_numpy(dtype=float)
def design(cols: list[str]) -> pd.DataFrame:
"""Numeric columns as they are, booleans as 0/1, categoricals as dummies (first level dropped)."""
out = {}
for c in cols:
s = df[c]
if c in CATEGORICAL:
for lv in list(s.cat.categories)[1:]:
out[f"{c}[{lv}]"] = (s.astype(str) == str(lv)).to_numpy(dtype=float)
else:
out[c] = numeric(c)
return pd.DataFrame(out, index=df.index)
y = df[Y].to_numpy(dtype=float)
X = pd.concat([pd.DataFrame({"const": np.ones(len(df))}, index=df.index), design(COVARIATES)], axis=1)
D = pd.DataFrame({c: numeric(c) for c in TREATMENTS}, index=df.index)
Z = pd.DataFrame({c: numeric(c) for c in INSTRUMENTS}, index=df.index)
clusters = df[CLUSTER].astype(str).to_numpy() if CLUSTER else None
n = len(df)
# The first stage regresses each treatment on the covariates and instruments: it needs more rows than columns.
cs.check_rows(n, X.shape[1] + Z.shape[1] + 1, "Instrumental-variable regression")
if np.unique(y).size < 2:
cs.cs_error("CS_E_CONSTANT", column=Y)
# %% Estimate (linearmodels; debiased = small-sample t and n/(n − k))
gmm = None
if estimator == "gmm":
# Two-step efficient GMM: the codesplash twin (= linearmodels IVGMM with debiased covariance).
gmm = csiv.gmm2s(y, X.to_numpy(), D.to_numpy(), Z.to_numpy(), se_kind, clusters)
names = list(X.columns) + list(D.columns)
b, V = gmm["b"], gmm["V"]
else:
Model = IV2SLS if estimator == "2sls" else IVLIML
cov_type = {"classical": "unadjusted", "robust": "robust", "cluster": "clustered"}[se_kind]
fit_kw = {"clusters": pd.Series(pd.factorize(clusters)[0], index=df.index)} if CLUSTER else {}
res = Model(y, X, D, Z).fit(cov_type=cov_type, debiased=True, **fit_kw)
names = list(res.params.index)
b = res.params.to_numpy()
V = np.asarray(res.cov)
k = len(names)
df_resid = n - k
qt = stats.t.ppf(0.5 + conf / 2, df_resid)
j0 = names.index(TREATMENTS[0])
est, se = float(b[j0]), float(np.sqrt(V[j0, j0]))
tstat = est / se
p = float(2 * stats.t.sf(abs(tstat), df_resid))
ci_low, ci_high = est - qt * se, est + qt * se
kappa = float(res.kappa) if estimator == "liml" else 1.0
# %% Diagnostics (twins, identical in Python and R)
Xm, Dm, Zm = X.to_numpy(), D.to_numpy(), Z.to_numpy()
fs = csiv.first_stage(Dm, Xm, Zm, se_kind, clusters)
first_stage_f = min(f["f"] for f in fs)
effective_f = fs[0]["effective_f"] if len(TREATMENTS) == 1 else None
ar = csiv.anderson_rubin(y, Dm[:, 0], Xm, Zm, se_kind, clusters, conf, est, 20 * se + 5 * abs(est)) if (True and len(TREATMENTS) == 1) else None
resid = gmm["e"] if gmm is not None else np.asarray(res.resids)
if len(INSTRUMENTS) <= len(TREATMENTS):
overid = None
elif gmm is not None:
overid = (gmm["j"], gmm["j_df"], gmm["j_p"]) # Hansen's J (Sargan with classical errors)
else:
overid = csiv.overid(resid, Xm, Zm, len(TREATMENTS), se_kind, clusters)
hz = csiv.hausman(y, Xm, Dm, Zm)
wh = csiv.wu_hausman(y, Xm, Dm, Zm, se_kind, clusters)
ols_b, _, _ = csiv.ols(y, np.column_stack([Xm, Dm]))
ols_estimate = float(ols_b[Xm.shape[1]])
# %% Checks
checks = []
strength = effective_f if effective_f is not None else first_stage_f
strength_name = "effective F" if effective_f is not None else "smallest first-stage F"
if strength < 10:
checks.append({"id": "weak_iv", "label": "Instrument strength", "status": "fail", "downgrade_to": "L1",
"detail": f"The {strength_name} is {strength:.1f} (< 10): the instruments are weak, the 2SLS interval is unreliable — report the Anderson–Rubin set."})
else:
checks.append({"id": "weak_iv", "label": "Instrument strength", "status": "pass",
"detail": f"The {strength_name} is {strength:.1f}" + (" (≥ 23 clears the Montiel Olea–Pflueger 10% worst-case bias bar)." if strength >= 23.1 else " (≥ 10).")})
if overid is not None:
st, odf, op = overid
name = "Sargan" if se_kind == "classical" else ("Hansen J" if gmm is not None else "robust score")
if op < 0.05:
checks.append({"id": "overid", "label": "Overidentifying restrictions", "status": "concern",
"detail": f"The {name} test rejects ({cs.fmt_p(op)}): the instruments disagree, so at least one may violate the exclusion restriction (or effects are heterogeneous)."})
else:
checks.append({"id": "overid", "label": "Overidentifying restrictions", "status": "pass",
"detail": f"The {name} test does not reject ({cs.fmt_p(op)}); it cannot rule out that all instruments are invalid in the same way."})
else:
checks.append({"id": "overid", "label": "Overidentifying restrictions", "status": "info",
"detail": "Exactly identified (one instrument per treatment): instrument validity cannot be tested."})
checks.append({"id": "endogeneity", "label": "Endogeneity of the treatment", "status": "info",
"detail": (f"Wu–Hausman {cs.fmt_p(wh[1])}: OLS and IV differ, consistent with confounding of the treatment." if wh[1] < 0.05
else f"Wu–Hausman {cs.fmt_p(wh[1])}: no evidence that OLS is biased; OLS is more precise if the treatment is exogenous.")})
if hz["chi2"] is not None:
checks.append({"id": "hausman", "label": "OLS against IV (Hausman)", "status": "info",
"detail": f"Hausman contrast χ²({hz['df']}) = {hz['chi2']:.2f}, {cs.fmt_p(hz['p'])}: "
+ ("OLS and IV differ — consistent with an endogenous treatment (if the instruments are valid)." if hz["p"] < 0.05
else "no significant difference between OLS and IV; OLS would be more precise if the treatment is exogenous.")})
checks.append({"id": "exclusion", "label": "Exclusion restriction", "status": "info",
"detail": "The instruments must affect the outcome only through the treatment — attest why (it cannot be tested with one instrument)."})
# %% Result
def label(nm: str) -> str:
return "Intercept" if nm == "const" else nm
coef_rows = [{"term": label(nm), "estimate": float(b[j]), "se": float(np.sqrt(V[j, j])),
"t": float(b[j] / np.sqrt(V[j, j])), "p": float(2 * stats.t.sf(abs(b[j] / np.sqrt(V[j, j])), df_resid))} for j, nm in enumerate(names)]
fs_rows = [{"treatment": TREATMENTS[j], "f": f["f"], "p": f["p"], "partial_r2": f["partial_r2"]} for j, f in enumerate(fs)]
binary = TREATMENTS[0] in BOOLEAN
summary = (
f"Instrumenting {TREATMENTS[0]} with {', '.join(INSTRUMENTS)}, "
+ (f"{TREATMENTS[0]} changes {Y} by {est:.3g}" if binary else f"a one-unit increase in {TREATMENTS[0]} changes {Y} by {est:.3g}")
+ f" ({conf:.0%} CI [{ci_low:.3g}, {ci_high:.3g}], {cs.fmt_p(p)}); ordinary least squares gives {ols_estimate:.3g}. "
+ f"The {strength_name} is {strength:.1f}"
+ ("; the instruments are weak, so the Anderson–Rubin set is the safer interval." if strength < 10 else ".")
)
values = {
"estimate": est, "se": se, "t": tstat, "p_value": p, "ci_low": ci_low, "ci_high": ci_high, "n": n, "df_resid": df_resid,
"estimator": estimator, "kappa": kappa, "se_type": se_kind,
"first_stage_f": first_stage_f, "effective_f": effective_f, "ols_estimate": ols_estimate,
"k_instruments": len(INSTRUMENTS), "k_treatments": len(TREATMENTS),
"wu_hausman_f": wh[0], "wu_hausman_p": wh[1],
"overid_stat": overid[0] if overid else None, "overid_df": overid[1] if overid else None, "overid_p": overid[2] if overid else None,
"hausman_chi2": hz["chi2"], "hausman_df": hz["df"], "hausman_p": hz["p"],
"ar_p": ar[0] if ar else None, "ar_ci_low": ar[1] if ar else None, "ar_ci_high": ar[2] if ar else None, "ar_shape": ar[3] if ar else None,
"estimand": "LATE",
"effect_label": (f"Effect of {TREATMENTS[0]} on {Y} for units whose treatment the instruments shift (compliers)" if binary
else f"Effect of a one-unit increase in {TREATMENTS[0]} on {Y} for units whose treatment the instruments shift"),
"claim_level_max": "L3",
}
for j, nm in enumerate(names):
values[f"coef[{label(nm)}]"] = float(b[j])
values[f"coef_se[{label(nm)}]"] = float(np.sqrt(V[j, j]))
for j, f in enumerate(fs):
values[f"first_stage_f[{TREATMENTS[j]}]"] = f["f"]
values[f"first_stage_p[{TREATMENTS[j]}]"] = f["p"]
values[f"partial_r2[{TREATMENTS[j]}]"] = f["partial_r2"]
for c in checks:
values[f"check[{c['id']}]"] = c["status"]
statistics = [
{"key": "estimate", "label": f"Effect of {TREATMENTS[0]}", "value": est},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
{"key": "p_value", "label": "p", "value": p, "format": "p"},
{"key": "first_stage_f", "label": "First-stage F", "value": first_stage_f},
]
if ar:
statistics.append({"key": "ar_ci", "label": f"Anderson–Rubin {conf:.0%} set", "value": [ar[1], ar[2]]})
cs.publish({
"method": "causal.iv",
"methodVersion": "1.1.2",
"title": "Instrumental variables (" + {"2sls": "2SLS", "liml": "LIML", "gmm": "efficient GMM"}[estimator] + ")",
"engine": cs.engine_info("pandas", "numpy", "linearmodels"),
"n": n,
"summary": summary,
"apa": f"b = {cs.fmt_num(est)}, SE = {cs.fmt_num(se)}, t({df_resid}) = {cs.fmt_num(tstat)}, {cs.fmt_p(p)}, {conf:.0%} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}]",
"statistics": statistics,
"tables": [
{"key": "coefficients", "title": "Second stage (" + {"classical": "classical", "robust": "robust HC1", "cluster": f"clustered by {CLUSTER}"}[se_kind] + " standard errors)",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
"rows": coef_rows},
{"key": "first_stage", "title": "First stage",
"columns": [{"key": "treatment", "label": "Treatment", "type": "string"}, {"key": "f", "label": "F (excluded instruments)", "type": "number"},
{"key": "p", "label": "p", "type": "p"}, {"key": "partial_r2", "label": "Partial R²", "type": "number"}],
"rows": fs_rows},
],
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"warnings": warnings,
"notes": [f"Exogenous controls: {', '.join(COVARIATES) or 'none'}; t with {df_resid} df." + (f" LIML κ = {kappa:.4f}." if estimator == "liml" else "") + (" Two-step efficient GMM weighted by the inverse moment covariance from 2SLS residuals." if estimator == "gmm" else "")],
"values": values,
})
The effective first-stage F is 100, far above the usual rule of thumb of 10. These instruments move the treatment hard.
Weaken the instrument
ExploreDExplorable · How strong is your instrument?
What goes wrong with instrumental variables when the instrument barely moves the treatment?
How often will the nominal 95% interval from two-stage least squares cover the true effect?
Commit your prediction above to see the result
Make your prediction to see the result.
Lower the instrument's pull and watch the many simulated studies. Estimates drift toward the confounded OLS answer, and their spread becomes enormous.
A weak instrument, for real
PredictPredict first
Another instrument gives a first-stage F of 0.761. 2SLS reports a 90% interval from 0.0306 to 4.33. Which do you rely on?
Reveal
The Anderson–RubinAnderson–Rubin testA test and confidence set for an IV coefficient that stay valid however weak the instrument is. set is the honest one. It stays valid with weak instruments, and here its shape is unbounded, with p = .501. The data can't rule out any effect size. The tidy 2SLS interval was false precision. Reporting OLS isn't a rescue, because it keeps the confounding.
Testing what can be tested
ReadWith more instruments than treatments, you can check whether they agree. That's a test of overidentifying restrictionsOveridentification testWith more instruments than treatments, tests whether the instruments give compatible answers.: Sargan with classical errors, a robust score test with robust errors, and Hansen's J under GMM.
The robust score test gives p = .937. Hansen's J with three instruments gives p = .475. Neither shows a conflict.
That isn't proof of validity. If all the instruments are wrong in the same way, they can agree perfectly. With one instrument per treatment, there's nothing to test, and exclusion has to be argued from outside the data.
Check your understanding
CheckpointCheck yourself
You propose distance to a clinic as an instrument for treatment. Which claim can the data never confirm?
Show the answer
Answer: b
Relevance can be tested, but the exclusion restriction is an argument about the world. Make it explicitly, in the DAG and in your report.
Check yourself
Hansen's J gives p = 0.48. What can you say?
Show the answer
Answer: b
The test only compares instruments with each other. Agreement is compatible with validity but doesn't establish it.
Check yourself
The Durbin–Wu–Hausman test rejects. What does that tell you?
Show the answer
Answer: a
The test compares two estimates, and it takes the instruments' validity for granted. Bad instruments can also produce a large gap.
Check yourself
The first-stage F is 2, and the Anderson–Rubin set is unbounded. What should you report?
Show the answer
Answer: b
An unbounded set is a real finding: this instrument doesn't carry enough information. It isn't evidence of no effect.
Check yourself
A lottery encourages people to join a program, and you use it as an instrument. Whose effect does IV estimate?
Show the answer
Answer: c
IV identifies the effect for compliers. It can differ from the population average, so say whose effect you estimated.
Read a card first-stage first
In the appHere the treatment is yes or no, and the instrument is too.
b = 3.06, SE = 0.73, t(568) = 4.17, p < .001, 95% CI [1.62, 4.50]
- Effect of d
- 3.057
- 95% CI
- [1.615, 4.498]
- p
- < .001
- First-stage F
- 38.647
- Anderson–Rubin 95% set
- [1.352, 4.411]
Assumptions
- Instrument strength — The effective F is 38.6 (≥ 23 clears the Montiel Olea–Pflueger 10% worst-case bias bar).
- Overidentifying restrictions — Exactly identified (one instrument per treatment): instrument validity cannot be tested.
- Endogeneity of the treatment — Wu–Hausman p = .036: OLS and IV differ, consistent with confounding of the treatment.
- OLS against IV (Hausman) — Hausman contrast χ²(1) = 4.46, p = .035: OLS and IV differ — consistent with an endogenous treatment (if the instruments are valid).
- Exclusion restriction — The instruments must affect the outcome only through the treatment — attest why (it cannot be tested with one instrument).
Second stage (robust HC1 standard errors)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| Intercept | −0.1462 | 0.4730 | −0.3092 | 0.7573 |
| w | 0.3630 | 0.0949 | 3.826 | 0.0001 |
| region[r02] | 0.5058 | 0.6188 | 0.8174 | 0.4140 |
| region[r03] | 1.272 | 0.6501 | 1.956 | 0.0510 |
| region[r04] | 1.012 | 0.7145 | 1.416 | 0.1574 |
| region[r05] | 0.8606 | 0.6543 | 1.315 | 0.1890 |
| region[r06] | 0.8650 | 0.6509 | 1.329 | 0.1844 |
| region[r07] | 1.026 | 0.6947 | 1.477 | 0.1402 |
| region[r08] | 1.226 | 0.7682 | 1.596 | 0.1111 |
| region[r09] | 0.8852 | 0.6819 | 1.298 | 0.1948 |
| region[r10] | 2.116 | 0.7043 | 3.004 | 0.0028 |
| region[r11] | 0.7549 | 0.6458 | 1.169 | 0.2429 |
| region[r12] | 0.6138 | 0.6755 | 0.9088 | 0.3639 |
| region[r13] | 1.415 | 0.6770 | 2.091 | 0.0370 |
| region[r14] | 0.6120 | 0.6600 | 0.9273 | 0.3542 |
| region[r15] | 1.371 | 0.6241 | 2.197 | 0.0284 |
| region[r16] | 0.8107 | 0.6614 | 1.226 | 0.2208 |
| region[r17] | 0.6963 | 0.6884 | 1.011 | 0.3122 |
| region[r18] | 1.025 | 0.5697 | 1.799 | 0.0725 |
| region[r19] | 1.181 | 0.7072 | 1.671 | 0.0954 |
| region[r20] | 1.680 | 0.7021 | 2.392 | 0.0171 |
| region[r21] | 1.210 | 0.7221 | 1.676 | 0.0942 |
| region[r22] | 0.7226 | 0.6631 | 1.090 | 0.2763 |
| region[r23] | 1.538 | 0.6892 | 2.232 | 0.0260 |
| region[r24] | 1.002 | 0.6285 | 1.594 | 0.1114 |
| region[r25] | 1.827 | 0.8050 | 2.270 | 0.0236 |
| region[r26] | 1.178 | 0.6445 | 1.828 | 0.0681 |
| region[r27] | 1.347 | 0.7242 | 1.860 | 0.0635 |
| region[r28] | 1.930 | 0.7327 | 2.634 | 0.0087 |
| region[r29] | 0.5301 | 0.6523 | 0.8127 | 0.4168 |
| region[r30] | 1.804 | 0.7081 | 2.548 | 0.0111 |
| d | 3.057 | 0.7339 | 4.165 | 3.597e-5 |
First stage
| Treatment | F (excluded instruments) | p | Partial R² |
|---|---|---|---|
| d | 38.647 | 9.843e-10 | 0.0643 |
- Exogenous controls: w, region; t with 568 df.
The exact R script · R R version 4.5.1 (2025-06-13)
# Instrumental variables (2SLS / LIML / GMM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.iv 1.1.2 · spec 2321b1018272e950
# Dataset: c1_iv (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_iv.parquet", col_select = c("yd", "d", "zb", "w", "region")))
n_input <- nrow(df)
df[["d"]] <- factor(df[["d"]], levels = c("false", "true")) # stored level order
df[["zb"]] <- factor(df[["zb"]], levels = c("false", "true")) # stored level order
df[["region"]] <- factor(df[["region"]], levels = c("r01", "r02", "r03", "r04", "r05", "r06", "r07", "r08", "r09", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30")) # stored level order
df <- df[stats::complete.cases(df[c("yd", "d", "zb", "w", "region")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("yd", "d", "zb", "w", "region")) # infinite values stop the run (registry/errors.yaml)
# %% Design
Y <- "yd"
TREATMENTS <- c("d")
INSTRUMENTS <- c("zb")
COVARIATES <- c("w", "region")
CLUSTER <- NULL
CATEGORICAL <- c("region", NULL)
BOOLEAN <- c("d", "zb", NULL)
estimator <- "2sls"
se_kind <- if (!is.null(CLUSTER)) "cluster" else "robust" # classical | robust | cluster
conf <- 0.95
if (length(INSTRUMENTS) < length(TREATMENTS)) stop("IV needs at least as many instruments as endogenous treatments.")
numeric_of <- function(col) {
v <- df[[col]]
if (is.factor(v)) { # booleans (and 2-level text) -> 0/1 for "true" / the last level
lv <- levels(v)
return(as.numeric(as.character(v) == if ("true" %in% lv) "true" else lv[length(lv)]))
}
as.numeric(v)
}
design <- function(cols) {
out <- list()
for (c in cols) {
if (c %in% CATEGORICAL) {
for (lv in levels(df[[c]])[-1]) out[[sprintf("%s[%s]", c, lv)]] <- as.numeric(as.character(df[[c]]) == lv)
} else {
out[[c]] <- numeric_of(c)
}
}
out
}
y <- as.numeric(df[[Y]])
cov_cols <- design(COVARIATES)
X <- cbind(const = rep(1, nrow(df)), if (length(cov_cols)) do.call(cbind, cov_cols) else NULL)
D <- do.call(cbind, setNames(lapply(TREATMENTS, numeric_of), TREATMENTS))
Z <- do.call(cbind, setNames(lapply(INSTRUMENTS, numeric_of), INSTRUMENTS))
clusters <- if (!is.null(CLUSTER)) as.character(df[[CLUSTER]]) else NULL
n <- nrow(df)
# The first stage regresses each treatment on the covariates and instruments: it needs more rows than columns.
cs_check_rows(n, ncol(X) + ncol(Z) + 1, "Instrumental-variable regression")
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = Y)
names_x <- c("Intercept", names(cov_cols), TREATMENTS)
# %% Estimate: 2SLS with ivreg + sandwich, LIML with the k-class twin (R has no standard LIML)
if (estimator == "2sls") {
dd <- data.frame(y = y, X[, -1, drop = FALSE], D, Z, check.names = FALSE)
names(dd) <- c("y", if (ncol(X) > 1) paste0("c", seq_len(ncol(X) - 1)), paste0("d", seq_len(ncol(D))), paste0("z", seq_len(ncol(Z))))
exog <- if (ncol(X) > 1) paste0("c", seq_len(ncol(X) - 1)) else character(0)
fml <- as.formula(paste("y ~", paste(c(exog, paste0("d", seq_len(ncol(D)))), collapse = " + "), "|",
paste(c(exog, paste0("z", seq_len(ncol(Z)))), collapse = " + ")))
fit <- ivreg::ivreg(fml, data = dd)
b <- unname(coef(fit))
V <- switch(se_kind,
classical = vcov(fit),
robust = sandwich::vcovHC(fit, type = "HC1"),
cluster = sandwich::vcovCL(fit, cluster = clusters, type = "HC1"))
V <- unname(V)
resid <- unname(residuals(fit))
kappa <- 1
} else if (estimator == "gmm") {
# Two-step efficient GMM: the codesplashr twin (= linearmodels IVGMM with debiased covariance).
gmm <- cs_causal_iv_gmm2s(y, X, D, Z, se_kind, clusters)
b <- gmm$b
V <- gmm$V
resid <- gmm$e
kappa <- 1
} else {
kappa <- cs_causal_iv_liml_kappa(y, X, D, Z)
kc <- cs_causal_iv_kclass(y, X, D, Z, kappa, se_kind, clusters)
b <- kc$b
V <- unname(kc$V)
resid <- kc$e
}
k <- length(b)
df_resid <- n - k
qt_ <- qt(0.5 + conf / 2, df_resid)
j0 <- ncol(X) + 1
est <- b[j0]
se <- sqrt(V[j0, j0])
tstat <- est / se
p <- 2 * pt(-abs(tstat), df_resid)
ci_low <- est - qt_ * se
ci_high <- est + qt_ * se
# %% Diagnostics (twins, identical in Python and R)
fs <- cs_causal_iv_first_stage(D, X, Z, se_kind, clusters)
first_stage_f <- min(vapply(fs, function(f) f$f, numeric(1)))
effective_f <- if (length(TREATMENTS) == 1) fs[[1]]$effective_f else NULL
ar <- if (TRUE && length(TREATMENTS) == 1) cs_causal_iv_anderson_rubin(y, D[, 1], X, Z, se_kind, clusters, conf, est, 20 * se + 5 * abs(est)) else NULL
overid <- if (length(INSTRUMENTS) <= length(TREATMENTS)) {
NULL
} else if (estimator == "gmm") {
list(stat = gmm$j, df = gmm$j_df, p = gmm$j_p) # Hansen's J (Sargan with classical errors)
} else {
cs_causal_iv_overid(resid, X, Z, length(TREATMENTS), se_kind, clusters)
}
hz <- cs_causal_iv_hausman(y, X, D, Z)
wh <- cs_causal_iv_wu_hausman(y, X, D, Z, se_kind, clusters)
ols_estimate <- cs_causal_iv_ols(y, cbind(X, D))$b[ncol(X) + 1]
# %% Checks
checks <- list()
add_check <- function(...) checks[[length(checks) + 1]] <<- list(...)
strength <- if (!is.null(effective_f)) effective_f else first_stage_f
strength_name <- if (!is.null(effective_f)) "effective F" else "smallest first-stage F"
if (strength < 10) {
add_check(id = "weak_iv", label = "Instrument strength", status = "fail", downgrade_to = "L1",
detail = sprintf("The %s is %.1f (< 10): the instruments are weak, the 2SLS interval is unreliable — report the Anderson–Rubin set.", strength_name, strength))
} else {
add_check(id = "weak_iv", label = "Instrument strength", status = "pass",
detail = paste0(sprintf("The %s is %.1f", strength_name, strength),
if (strength >= 23.1) " (≥ 23 clears the Montiel Olea–Pflueger 10% worst-case bias bar)." else " (≥ 10)."))
}
if (!is.null(overid)) {
oname <- if (se_kind == "classical") "Sargan" else if (estimator == "gmm") "Hansen J" else "robust score"
if (overid[["p"]] < 0.05) {
add_check(id = "overid", label = "Overidentifying restrictions", status = "concern",
detail = sprintf("The %s test rejects (%s): the instruments disagree, so at least one may violate the exclusion restriction (or effects are heterogeneous).", oname, cs_fmt_p(overid[["p"]])))
} else {
add_check(id = "overid", label = "Overidentifying restrictions", status = "pass",
detail = sprintf("The %s test does not reject (%s); it cannot rule out that all instruments are invalid in the same way.", oname, cs_fmt_p(overid[["p"]])))
}
} else {
add_check(id = "overid", label = "Overidentifying restrictions", status = "info",
detail = "Exactly identified (one instrument per treatment): instrument validity cannot be tested.")
}
add_check(id = "endogeneity", label = "Endogeneity of the treatment", status = "info",
detail = if (wh[["p"]] < 0.05) sprintf("Wu–Hausman %s: OLS and IV differ, consistent with confounding of the treatment.", cs_fmt_p(wh[["p"]]))
else sprintf("Wu–Hausman %s: no evidence that OLS is biased; OLS is more precise if the treatment is exogenous.", cs_fmt_p(wh[["p"]])))
if (!is.null(hz$chi2)) {
add_check(id = "hausman", label = "OLS against IV (Hausman)", status = "info",
detail = paste0(sprintf("Hausman contrast χ²(%d) = %.2f, %s: ", as.integer(hz$df), hz$chi2, cs_fmt_p(hz$p)),
if (hz$p < 0.05) "OLS and IV differ — consistent with an endogenous treatment (if the instruments are valid)."
else "no significant difference between OLS and IV; OLS would be more precise if the treatment is exogenous."))
}
add_check(id = "exclusion", label = "Exclusion restriction", status = "info",
detail = "The instruments must affect the outcome only through the treatment — attest why (it cannot be tested with one instrument).")
# %% Result
se_all <- sqrt(diag(V))
coef_rows <- data.frame(term = names_x, estimate = b, se = se_all, t = b / se_all, p = 2 * pt(-abs(b / se_all), df_resid))
fs_rows <- data.frame(treatment = TREATMENTS, f = vapply(fs, function(f) f$f, numeric(1)), p = vapply(fs, function(f) f$p, numeric(1)),
partial_r2 = vapply(fs, function(f) f$partial_r2, numeric(1)))
binary <- TREATMENTS[1] %in% BOOLEAN
pct <- sprintf("%.0f%%", conf * 100)
g3 <- function(x) formatC(x, digits = 3, format = "g")
summary <- paste0(
sprintf("Instrumenting %s with %s, ", TREATMENTS[1], paste(INSTRUMENTS, collapse = ", ")),
if (binary) sprintf("%s changes %s by %s", TREATMENTS[1], Y, g3(est)) else sprintf("a one-unit increase in %s changes %s by %s", TREATMENTS[1], Y, g3(est)),
sprintf(" (%s CI [%s, %s], %s); ordinary least squares gives %s. ", pct, g3(ci_low), g3(ci_high), cs_fmt_p(p), g3(ols_estimate)),
sprintf("The %s is %.1f", strength_name, strength),
if (strength < 10) "; the instruments are weak, so the Anderson–Rubin set is the safer interval." else "."
)
values <- list(
estimate = est, se = se, t = tstat, p_value = p, ci_low = ci_low, ci_high = ci_high, n = n, df_resid = df_resid,
estimator = estimator, kappa = kappa, se_type = se_kind,
first_stage_f = first_stage_f, effective_f = effective_f, ols_estimate = ols_estimate,
k_instruments = length(INSTRUMENTS), k_treatments = length(TREATMENTS),
wu_hausman_f = wh[["f"]], wu_hausman_p = wh[["p"]],
overid_stat = if (!is.null(overid)) overid[["stat"]] else NULL, overid_df = if (!is.null(overid)) overid[["df"]] else NULL,
overid_p = if (!is.null(overid)) overid[["p"]] else NULL,
hausman_chi2 = hz$chi2, hausman_df = hz$df, hausman_p = hz$p,
ar_p = ar$p0, ar_ci_low = ar$low, ar_ci_high = ar$high, ar_shape = ar$shape,
estimand = "LATE",
effect_label = if (binary) sprintf("Effect of %s on %s for units whose treatment the instruments shift (compliers)", TREATMENTS[1], Y)
else sprintf("Effect of a one-unit increase in %s on %s for units whose treatment the instruments shift", TREATMENTS[1], Y),
claim_level_max = "L3"
)
for (j in seq_along(names_x)) {
values[[sprintf("coef[%s]", names_x[j])]] <- b[j]
values[[sprintf("coef_se[%s]", names_x[j])]] <- se_all[j]
}
for (j in seq_along(fs)) {
values[[sprintf("first_stage_f[%s]", TREATMENTS[j])]] <- fs[[j]]$f
values[[sprintf("first_stage_p[%s]", TREATMENTS[j])]] <- fs[[j]]$p
values[[sprintf("partial_r2[%s]", TREATMENTS[j])]] <- fs[[j]]$partial_r2
}
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
statistics <- list(
list(key = "estimate", label = sprintf("Effect of %s", TREATMENTS[1]), value = est),
list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
list(key = "p_value", label = "p", value = p, format = "p"),
list(key = "first_stage_f", label = "First-stage F", value = first_stage_f)
)
if (!is.null(ar)) statistics[[length(statistics) + 1]] <- list(key = "ar_ci", label = sprintf("Anderson–Rubin %s set", pct), value = list(ar$low, ar$high))
cs_publish(list(
method = "causal.iv",
methodVersion = "1.1.2",
title = paste0("Instrumental variables (", switch(estimator, "2sls" = "2SLS", liml = "LIML", gmm = "efficient GMM"), ")"),
engine = cs_engine_info("ivreg", "sandwich", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("b = %s, SE = %s, t(%d) = %s, %s, %s CI [%s, %s]", cs_fmt_num(est), cs_fmt_num(se), df_resid, cs_fmt_num(tstat), cs_fmt_p(p), pct,
cs_fmt_num(ci_low), cs_fmt_num(ci_high)),
statistics = statistics,
tables = list(
list(key = "coefficients", title = sprintf("Second stage (%s standard errors)", switch(se_kind, classical = "classical", robust = "robust HC1", cluster = paste("clustered by", CLUSTER))),
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "p")),
rows = coef_rows),
list(key = "first_stage", title = "First stage",
columns = list(list(key = "treatment", label = "Treatment", type = "string"), list(key = "f", label = "F (excluded instruments)", type = "number"),
list(key = "p", label = "p", type = "p"), list(key = "partial_r2", label = "Partial R²", type = "number")),
rows = fs_rows)
),
assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = if (c$status == "concern") "warn" else c$status, detail = c$detail)),
checks = checks,
warnings = warnings,
notes = list(paste0(sprintf("Exogenous controls: %s; t with %d df.", if (length(COVARIATES)) paste(COVARIATES, collapse = ", ") else "none", df_resid),
if (estimator == "liml") sprintf(" LIML κ = %.4f.", kappa) else "",
if (estimator == "gmm") " Two-step efficient GMM weighted by the inverse moment covariance from 2SLS residuals." else "")),
values = values
))
b = 3.06, SE = 0.73, t(568) = 4.17, p < .001, 95% CI [1.62, 4.50]
- Effect of d
- 3.057
- 95% CI
- [1.615, 4.498]
- p
- < .001
- First-stage F
- 38.647
- Anderson–Rubin 95% set
- [1.352, 4.411]
Assumptions
- Instrument strength — The effective F is 38.6 (≥ 23 clears the Montiel Olea–Pflueger 10% worst-case bias bar).
- Overidentifying restrictions — Exactly identified (one instrument per treatment): instrument validity cannot be tested.
- Endogeneity of the treatment — Wu–Hausman p = .036: OLS and IV differ, consistent with confounding of the treatment.
- OLS against IV (Hausman) — Hausman contrast χ²(1) = 4.46, p = .035: OLS and IV differ — consistent with an endogenous treatment (if the instruments are valid).
- Exclusion restriction — The instruments must affect the outcome only through the treatment — attest why (it cannot be tested with one instrument).
Second stage (robust HC1 standard errors)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| Intercept | −0.1462 | 0.4730 | −0.3092 | 0.7573 |
| w | 0.3630 | 0.0949 | 3.826 | 0.0001 |
| region[r02] | 0.5058 | 0.6188 | 0.8174 | 0.4140 |
| region[r03] | 1.272 | 0.6501 | 1.956 | 0.0510 |
| region[r04] | 1.012 | 0.7145 | 1.416 | 0.1574 |
| region[r05] | 0.8606 | 0.6543 | 1.315 | 0.1890 |
| region[r06] | 0.8650 | 0.6509 | 1.329 | 0.1844 |
| region[r07] | 1.026 | 0.6947 | 1.477 | 0.1402 |
| region[r08] | 1.226 | 0.7682 | 1.596 | 0.1111 |
| region[r09] | 0.8852 | 0.6819 | 1.298 | 0.1948 |
| region[r10] | 2.116 | 0.7043 | 3.004 | 0.0028 |
| region[r11] | 0.7549 | 0.6458 | 1.169 | 0.2429 |
| region[r12] | 0.6138 | 0.6755 | 0.9088 | 0.3639 |
| region[r13] | 1.415 | 0.6770 | 2.091 | 0.0370 |
| region[r14] | 0.6120 | 0.6600 | 0.9273 | 0.3542 |
| region[r15] | 1.371 | 0.6241 | 2.197 | 0.0284 |
| region[r16] | 0.8107 | 0.6614 | 1.226 | 0.2208 |
| region[r17] | 0.6963 | 0.6884 | 1.011 | 0.3122 |
| region[r18] | 1.025 | 0.5697 | 1.799 | 0.0725 |
| region[r19] | 1.181 | 0.7072 | 1.671 | 0.0954 |
| region[r20] | 1.680 | 0.7021 | 2.392 | 0.0171 |
| region[r21] | 1.210 | 0.7221 | 1.676 | 0.0942 |
| region[r22] | 0.7226 | 0.6631 | 1.090 | 0.2763 |
| region[r23] | 1.538 | 0.6892 | 2.232 | 0.0260 |
| region[r24] | 1.002 | 0.6285 | 1.594 | 0.1114 |
| region[r25] | 1.827 | 0.8050 | 2.270 | 0.0236 |
| region[r26] | 1.178 | 0.6445 | 1.828 | 0.0681 |
| region[r27] | 1.347 | 0.7242 | 1.860 | 0.0635 |
| region[r28] | 1.930 | 0.7327 | 2.634 | 0.0087 |
| region[r29] | 0.5301 | 0.6523 | 0.8127 | 0.4168 |
| region[r30] | 1.804 | 0.7081 | 2.548 | 0.0111 |
| d | 3.057 | 0.7339 | 4.165 | 3.597e-5 |
First stage
| Treatment | F (excluded instruments) | p | Partial R² |
|---|---|---|---|
| d | 38.647 | 9.843e-10 | 0.0643 |
- Exogenous controls: w, region; t with 568 df.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Instrumental variables (2SLS / LIML / GMM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.iv 1.1.2 · spec 2321b1018272e950
# Dataset: c1_iv (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from linearmodels.iv import IV2SLS, IVLIML
from scipy import stats
import codesplash as cs
from codesplash.causal import iv as csiv
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_iv.parquet", columns=["yd", "d", "zb", "w", "region"])
n_input = len(df)
df["d"] = pd.Categorical(df["d"], categories=["false", "true"]) # stored level order
df["zb"] = pd.Categorical(df["zb"], categories=["false", "true"]) # stored level order
df["region"] = pd.Categorical(df["region"], categories=["r01", "r02", "r03", "r04", "r05", "r06", "r07", "r08", "r09", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30"]) # stored level order
df = df.dropna(subset=["yd", "d", "zb", "w", "region"]) # listwise deletion over the analysis columns
df["d"] = df["d"].cat.remove_unused_categories()
df["zb"] = df["zb"].cat.remove_unused_categories()
df["region"] = df["region"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["yd", "d", "zb", "w", "region"]) # infinite values stop the run (registry/errors.yaml)
# %% Design
Y = "yd"
TREATMENTS = ["d"]
INSTRUMENTS = ["zb"]
COVARIATES = ["w", "region"]
CLUSTER = None
CATEGORICAL = ["region", ]
BOOLEAN = ["d", "zb", ]
estimator = "2sls"
se_kind = "cluster" if CLUSTER else "robust" # classical | robust | cluster
conf = 0.95
if len(INSTRUMENTS) < len(TREATMENTS):
raise ValueError("IV needs at least as many instruments as endogenous treatments.")
def numeric(col: str) -> np.ndarray:
s = df[col]
if isinstance(s.dtype, pd.CategoricalDtype): # booleans (and 2-level text) → 0/1 for "true" / the last level
lv = [str(x) for x in s.cat.categories]
return (s.astype(str) == ("true" if "true" in lv else lv[-1])).to_numpy(dtype=float)
return s.to_numpy(dtype=float)
def design(cols: list[str]) -> pd.DataFrame:
"""Numeric columns as they are, booleans as 0/1, categoricals as dummies (first level dropped)."""
out = {}
for c in cols:
s = df[c]
if c in CATEGORICAL:
for lv in list(s.cat.categories)[1:]:
out[f"{c}[{lv}]"] = (s.astype(str) == str(lv)).to_numpy(dtype=float)
else:
out[c] = numeric(c)
return pd.DataFrame(out, index=df.index)
y = df[Y].to_numpy(dtype=float)
X = pd.concat([pd.DataFrame({"const": np.ones(len(df))}, index=df.index), design(COVARIATES)], axis=1)
D = pd.DataFrame({c: numeric(c) for c in TREATMENTS}, index=df.index)
Z = pd.DataFrame({c: numeric(c) for c in INSTRUMENTS}, index=df.index)
clusters = df[CLUSTER].astype(str).to_numpy() if CLUSTER else None
n = len(df)
# The first stage regresses each treatment on the covariates and instruments: it needs more rows than columns.
cs.check_rows(n, X.shape[1] + Z.shape[1] + 1, "Instrumental-variable regression")
if np.unique(y).size < 2:
cs.cs_error("CS_E_CONSTANT", column=Y)
# %% Estimate (linearmodels; debiased = small-sample t and n/(n − k))
gmm = None
if estimator == "gmm":
# Two-step efficient GMM: the codesplash twin (= linearmodels IVGMM with debiased covariance).
gmm = csiv.gmm2s(y, X.to_numpy(), D.to_numpy(), Z.to_numpy(), se_kind, clusters)
names = list(X.columns) + list(D.columns)
b, V = gmm["b"], gmm["V"]
else:
Model = IV2SLS if estimator == "2sls" else IVLIML
cov_type = {"classical": "unadjusted", "robust": "robust", "cluster": "clustered"}[se_kind]
fit_kw = {"clusters": pd.Series(pd.factorize(clusters)[0], index=df.index)} if CLUSTER else {}
res = Model(y, X, D, Z).fit(cov_type=cov_type, debiased=True, **fit_kw)
names = list(res.params.index)
b = res.params.to_numpy()
V = np.asarray(res.cov)
k = len(names)
df_resid = n - k
qt = stats.t.ppf(0.5 + conf / 2, df_resid)
j0 = names.index(TREATMENTS[0])
est, se = float(b[j0]), float(np.sqrt(V[j0, j0]))
tstat = est / se
p = float(2 * stats.t.sf(abs(tstat), df_resid))
ci_low, ci_high = est - qt * se, est + qt * se
kappa = float(res.kappa) if estimator == "liml" else 1.0
# %% Diagnostics (twins, identical in Python and R)
Xm, Dm, Zm = X.to_numpy(), D.to_numpy(), Z.to_numpy()
fs = csiv.first_stage(Dm, Xm, Zm, se_kind, clusters)
first_stage_f = min(f["f"] for f in fs)
effective_f = fs[0]["effective_f"] if len(TREATMENTS) == 1 else None
ar = csiv.anderson_rubin(y, Dm[:, 0], Xm, Zm, se_kind, clusters, conf, est, 20 * se + 5 * abs(est)) if (True and len(TREATMENTS) == 1) else None
resid = gmm["e"] if gmm is not None else np.asarray(res.resids)
if len(INSTRUMENTS) <= len(TREATMENTS):
overid = None
elif gmm is not None:
overid = (gmm["j"], gmm["j_df"], gmm["j_p"]) # Hansen's J (Sargan with classical errors)
else:
overid = csiv.overid(resid, Xm, Zm, len(TREATMENTS), se_kind, clusters)
hz = csiv.hausman(y, Xm, Dm, Zm)
wh = csiv.wu_hausman(y, Xm, Dm, Zm, se_kind, clusters)
ols_b, _, _ = csiv.ols(y, np.column_stack([Xm, Dm]))
ols_estimate = float(ols_b[Xm.shape[1]])
# %% Checks
checks = []
strength = effective_f if effective_f is not None else first_stage_f
strength_name = "effective F" if effective_f is not None else "smallest first-stage F"
if strength < 10:
checks.append({"id": "weak_iv", "label": "Instrument strength", "status": "fail", "downgrade_to": "L1",
"detail": f"The {strength_name} is {strength:.1f} (< 10): the instruments are weak, the 2SLS interval is unreliable — report the Anderson–Rubin set."})
else:
checks.append({"id": "weak_iv", "label": "Instrument strength", "status": "pass",
"detail": f"The {strength_name} is {strength:.1f}" + (" (≥ 23 clears the Montiel Olea–Pflueger 10% worst-case bias bar)." if strength >= 23.1 else " (≥ 10).")})
if overid is not None:
st, odf, op = overid
name = "Sargan" if se_kind == "classical" else ("Hansen J" if gmm is not None else "robust score")
if op < 0.05:
checks.append({"id": "overid", "label": "Overidentifying restrictions", "status": "concern",
"detail": f"The {name} test rejects ({cs.fmt_p(op)}): the instruments disagree, so at least one may violate the exclusion restriction (or effects are heterogeneous)."})
else:
checks.append({"id": "overid", "label": "Overidentifying restrictions", "status": "pass",
"detail": f"The {name} test does not reject ({cs.fmt_p(op)}); it cannot rule out that all instruments are invalid in the same way."})
else:
checks.append({"id": "overid", "label": "Overidentifying restrictions", "status": "info",
"detail": "Exactly identified (one instrument per treatment): instrument validity cannot be tested."})
checks.append({"id": "endogeneity", "label": "Endogeneity of the treatment", "status": "info",
"detail": (f"Wu–Hausman {cs.fmt_p(wh[1])}: OLS and IV differ, consistent with confounding of the treatment." if wh[1] < 0.05
else f"Wu–Hausman {cs.fmt_p(wh[1])}: no evidence that OLS is biased; OLS is more precise if the treatment is exogenous.")})
if hz["chi2"] is not None:
checks.append({"id": "hausman", "label": "OLS against IV (Hausman)", "status": "info",
"detail": f"Hausman contrast χ²({hz['df']}) = {hz['chi2']:.2f}, {cs.fmt_p(hz['p'])}: "
+ ("OLS and IV differ — consistent with an endogenous treatment (if the instruments are valid)." if hz["p"] < 0.05
else "no significant difference between OLS and IV; OLS would be more precise if the treatment is exogenous.")})
checks.append({"id": "exclusion", "label": "Exclusion restriction", "status": "info",
"detail": "The instruments must affect the outcome only through the treatment — attest why (it cannot be tested with one instrument)."})
# %% Result
def label(nm: str) -> str:
return "Intercept" if nm == "const" else nm
coef_rows = [{"term": label(nm), "estimate": float(b[j]), "se": float(np.sqrt(V[j, j])),
"t": float(b[j] / np.sqrt(V[j, j])), "p": float(2 * stats.t.sf(abs(b[j] / np.sqrt(V[j, j])), df_resid))} for j, nm in enumerate(names)]
fs_rows = [{"treatment": TREATMENTS[j], "f": f["f"], "p": f["p"], "partial_r2": f["partial_r2"]} for j, f in enumerate(fs)]
binary = TREATMENTS[0] in BOOLEAN
summary = (
f"Instrumenting {TREATMENTS[0]} with {', '.join(INSTRUMENTS)}, "
+ (f"{TREATMENTS[0]} changes {Y} by {est:.3g}" if binary else f"a one-unit increase in {TREATMENTS[0]} changes {Y} by {est:.3g}")
+ f" ({conf:.0%} CI [{ci_low:.3g}, {ci_high:.3g}], {cs.fmt_p(p)}); ordinary least squares gives {ols_estimate:.3g}. "
+ f"The {strength_name} is {strength:.1f}"
+ ("; the instruments are weak, so the Anderson–Rubin set is the safer interval." if strength < 10 else ".")
)
values = {
"estimate": est, "se": se, "t": tstat, "p_value": p, "ci_low": ci_low, "ci_high": ci_high, "n": n, "df_resid": df_resid,
"estimator": estimator, "kappa": kappa, "se_type": se_kind,
"first_stage_f": first_stage_f, "effective_f": effective_f, "ols_estimate": ols_estimate,
"k_instruments": len(INSTRUMENTS), "k_treatments": len(TREATMENTS),
"wu_hausman_f": wh[0], "wu_hausman_p": wh[1],
"overid_stat": overid[0] if overid else None, "overid_df": overid[1] if overid else None, "overid_p": overid[2] if overid else None,
"hausman_chi2": hz["chi2"], "hausman_df": hz["df"], "hausman_p": hz["p"],
"ar_p": ar[0] if ar else None, "ar_ci_low": ar[1] if ar else None, "ar_ci_high": ar[2] if ar else None, "ar_shape": ar[3] if ar else None,
"estimand": "LATE",
"effect_label": (f"Effect of {TREATMENTS[0]} on {Y} for units whose treatment the instruments shift (compliers)" if binary
else f"Effect of a one-unit increase in {TREATMENTS[0]} on {Y} for units whose treatment the instruments shift"),
"claim_level_max": "L3",
}
for j, nm in enumerate(names):
values[f"coef[{label(nm)}]"] = float(b[j])
values[f"coef_se[{label(nm)}]"] = float(np.sqrt(V[j, j]))
for j, f in enumerate(fs):
values[f"first_stage_f[{TREATMENTS[j]}]"] = f["f"]
values[f"first_stage_p[{TREATMENTS[j]}]"] = f["p"]
values[f"partial_r2[{TREATMENTS[j]}]"] = f["partial_r2"]
for c in checks:
values[f"check[{c['id']}]"] = c["status"]
statistics = [
{"key": "estimate", "label": f"Effect of {TREATMENTS[0]}", "value": est},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
{"key": "p_value", "label": "p", "value": p, "format": "p"},
{"key": "first_stage_f", "label": "First-stage F", "value": first_stage_f},
]
if ar:
statistics.append({"key": "ar_ci", "label": f"Anderson–Rubin {conf:.0%} set", "value": [ar[1], ar[2]]})
cs.publish({
"method": "causal.iv",
"methodVersion": "1.1.2",
"title": "Instrumental variables (" + {"2sls": "2SLS", "liml": "LIML", "gmm": "efficient GMM"}[estimator] + ")",
"engine": cs.engine_info("pandas", "numpy", "linearmodels"),
"n": n,
"summary": summary,
"apa": f"b = {cs.fmt_num(est)}, SE = {cs.fmt_num(se)}, t({df_resid}) = {cs.fmt_num(tstat)}, {cs.fmt_p(p)}, {conf:.0%} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}]",
"statistics": statistics,
"tables": [
{"key": "coefficients", "title": "Second stage (" + {"classical": "classical", "robust": "robust HC1", "cluster": f"clustered by {CLUSTER}"}[se_kind] + " standard errors)",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
"rows": coef_rows},
{"key": "first_stage", "title": "First stage",
"columns": [{"key": "treatment", "label": "Treatment", "type": "string"}, {"key": "f", "label": "F (excluded instruments)", "type": "number"},
{"key": "p", "label": "p", "type": "p"}, {"key": "partial_r2", "label": "Partial R²", "type": "number"}],
"rows": fs_rows},
],
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"warnings": warnings,
"notes": [f"Exogenous controls: {', '.join(COVARIATES) or 'none'}; t with {df_resid} df." + (f" LIML κ = {kappa:.4f}." if estimator == "liml" else "") + (" Two-step efficient GMM weighted by the inverse moment covariance from 2SLS residuals." if estimator == "gmm" else "")],
"values": values,
})
Check yourself
What effective first-stage F does this card report? One decimal is enough.
Show the answer
Answer: 38.6465571374788
Look at it before you read the effect, because a weak instrument undermines everything after it. This one clears the rule of thumb of 10.
Try it
In the appIn the Causal studio's Design step, answer yes when asked about a variable that shifts treatment but affects the outcome only through it. The Assumptions step shows what the data can test, and asks you to attest the rest.
import pandas as pd
from linearmodels.iv import IV2SLS
df = pd.read_csv("iv.csv").rename(columns={"earnings (k)": "earnings"})
fit = IV2SLS.from_formula("earnings ~ 1 + w + [x ~ z1 + z2]", df).fit(cov_type="robust")
print(fit.summary)
print(fit.first_stage)
print(fit.wooldridge_overid) # robust test of overidentifying restrictions
print(fit.wu_hausman()) # endogeneitylibrary(AER)
df <- read.csv("iv.csv", check.names = FALSE)
names(df)[names(df) == "earnings (k)"] <- "earnings"
fit <- ivreg(earnings ~ x + w | z1 + z2 + w, data = df)
# Weak instruments, Wu-Hausman and Sargan, with robust standard errors
summary(fit, vcov = sandwich::sandwich, diagnostics = TRUE)Recap
Recap- An instrument must move the treatment, be as good as random, and reach the outcome only through the treatment.
- Check the first stage first. When it's weak, read the Anderson–Rubin set.
- Sargan and Hansen's J compare instruments with each other. They can't establish validity.
- The estimate applies to compliers.
Concepts in this lesson