Endogeneity: Hausman, Durbin–Wu–Hausman, Sargan, Hansen J and Anderson–Rubin
When a predictor is tangled with the error term, more data won't help and residual plots won't warn you. Learn which test answers which question once you have an instrument.
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
- Name three ways a predictor becomes endogenous, and why residuals can't show it
- Test a predictor's endogeneity with the Hausman and Durbin–Wu–Hausman tests
- Test overidentifying restrictions with Sargan and Hansen J, and say what passing doesn't show
- Use the Anderson–Rubin test when instruments may be weak
The problem residuals can't show
ReadLeast squares assumes that predictors are unrelated to the error. When that fails, the predictor is endogenousEndogeneityA predictor is correlated with the error term, through omitted variables, reverse causation or measurement error., and three routes lead there:
- An omitted variable moves both and .
- Reverse causation: also moves .
- Measurement error in .
More data doesn't help: the slope settles on the wrong value. Residual plots don't help either, because least squares forces residuals to be uncorrelated with , whatever the truth is.
Make a prediction
PredictPredict first
You measure with random error, and is measured well. Where does the fitted slope land, compared with the true one?
Reveal
Too close to zero. Noise in spreads the points sideways, so the line flattens. That's attenuation. Omitted variables and reverse causation can push either way, depending on their signs.
What an instrument adds
ReadAn instrumentInstrumental variableA variable that shifts treatment but affects the outcome only through treatment. moves and has no other route to . It gives you a second estimate of the slope, which is what makes the tests below possible.
Two checks come first, and the Causal track's instrumental-variables lesson covers them as a design: the first stageFirst stageThe regression of the treatment on the instrument; it shows how strongly the instrument moves the treatment. must be strong, and the exclusion restrictionExclusion restrictionAn instrument affects the outcome only through the treatment. Data can't confirm this; you argue it. must be argued, because the data can't confirm it.
This lesson asks a regression question: given an instrument, what can you test?
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 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,
})
Is least squares actually wrong?
PredictThe Hausman testHausman testCompares fixed and random effects estimates; a large gap suggests unit differences track the regressors, so random effects are biased. compares the two estimates. If is exogenous, both are consistent, so they should differ only by chance. If not, only IV is.
Predict first
These simulated data have a true effect of 2. Least squares gives 2.58, and IV gives 2.02 with a standard error of 0.100. What do you expect?
Reveal
Reject: (1) = 54.0, p < .001. The gap is far larger than chance would produce, if the instruments are valid.
The same question, as a regression
ReadThe Durbin–Wu–Hausman testDurbin–Wu–Hausman testCompares OLS with instrumental variables estimates. A large gap suggests the treatment is endogenous, so OLS is biased. gets there in two steps:
- Regress on the instruments and covariates, and keep the residuals .
- Add to the outcome regression, and test its coefficient.
is the part of the instruments can't explain. If it still predicts , then is carrying something from the error term.
Here, = 53.5, p < .001. Its regression form accepts robust or clustered errors, so it's usually the easier one to use.
When the test can't see
PredictPredict first
Now take a weak instrument: first-stage = 0.761. Least squares gives 2.62, IV gives 2.18, and Hausman gives p = .715. What's the right reading?
Reveal
The instrument can't tell us. These are the same data, and is still endogenous. With a standard error of 1.31, IV is too noisy to contradict anything. A large p-value here shows a lack of power, not an absence of bias.
Weigh bias against noise
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.
Set Hidden confounding to 0. Least squares is now right, and IV only adds noise. Raise it again, then lower the instrument's pull.
IV pays for removing bias with a wider spread, and the price climbs quickly as the instrument weakens.
Anderson–Rubin: no first stage needed
ReadThe Anderson–Rubin testAnderson–Rubin testA test and confidence set for an IV coefficient that stay valid however weak the instrument is. asks about the effect directly. Pick a candidate , and regress on the instruments. If is right, the instruments should explain nothing.
Try every , and keep those not rejected. That set stays valid however weak the instruments are.
| Case | 2SLS interval | Anderson–Rubin set |
|---|---|---|
| Strong | 1.83 to 2.22 | 1.75 to 2.25 |
| Weak (90% level) | 0.0306 to 4.33 | unbounded |
Do the instruments agree?
ReadWith more instruments than treatments, each instrument implies its own estimate. Overidentifying restrictionsOveridentification testWith more instruments than treatments, tests whether the instruments give compatible answers. ask whether they agree.
Sargan regresses the 2SLS residuals on all the instruments, and refers to with (instruments − treatments) df. It's the classical version. CodeSplash runs a robust score test when errors are robust, which gives p = .937 here.
Hansen's J is the same idea under GMM, where it stays valid under heteroskedasticity: (2) = 1.49, p = .475.
Where could yours come from?
ReflectTake a regression you've run. Name one variable you didn't measure that could move both a key predictor and the outcome. Which way would it push the slope?
Now try to name something that shifts that predictor but has no other route to the outcome. If you can't, that's useful to know. Say so in the report, and treat the slope as an association.
Check your understanding
CheckpointCheck yourself
Which test asks whether least squares and IV differ by more than chance?
Show the answer
Answer: a
Hausman contrasts the two estimates, and Durbin–Wu–Hausman is its regression form. Sargan and Hansen J compare instruments with each other.
Check yourself
You have 3 instruments and 1 endogenous treatment. How many degrees of freedom does Hansen's J have?
Show the answer
Answer: 2
Instruments minus treatments: 3 − 1 = 2. With exactly as many instruments as treatments there's nothing to test.
Check yourself
Sargan gives p = 0.60. What can you conclude?
Show the answer
Answer: c
The test compares instruments with each other. If all of them violate exclusion in the same direction, it won't notice.
Check yourself
The first-stage F is 3. Which interval should you read?
Show the answer
Answer: b
Precise isn't the same as right. Least squares keeps its bias, and the 2SLS interval is unreliable with a weak instrument. An unbounded Anderson–Rubin set is an honest answer.
Check yourself
Put these in the order you'd read them on a card.
Show the answer
The order:
- First-stage strength
- Anderson–Rubin, if the first stage is weak
- Overidentification, if there are extra instruments
- The endogeneity test, then the estimate
Everything rests on the first stage, so start there. Then see whether the instruments agree before you lean on them to judge least squares.
Run it
In the appSet Outcome, Endogenous treatment, Instruments and Covariates. Choose Two-step efficient GMM under Estimator for Hansen's J, and leave the Anderson–Rubin confidence set on.
import pandas as pd
import statsmodels.formula.api as smf
from linearmodels.iv import IV2SLS
df = pd.read_csv("c1_iv.csv").rename(columns={"earnings (k)": "earnings"})
fit = IV2SLS.from_formula("earnings ~ 1 + w + [x ~ z1 + z2]", df).fit(cov_type="unadjusted")
print(fit.sargan) # Sargan
print(fit.durbin()) # Durbin-Wu-Hausman, chi-square form
print(fit.wu_hausman()) # Durbin-Wu-Hausman, F form
# Anderson-Rubin at one candidate effect: do the instruments explain y - 2x?
ar = smf.ols("I(earnings - 2 * x) ~ w + z1 + z2", df).fit()
print(ar.f_test("z1 = 0, z2 = 0"))library(ivreg)
df <- read.csv("c1_iv.csv", check.names = FALSE)
names(df)[names(df) == "earnings (k)"] <- "earnings"
fit <- ivreg(earnings ~ x + w | z1 + z2 + w, data = df)
summary(fit, diagnostics = TRUE) # weak instruments, Wu-Hausman, Sargan
# Anderson-Rubin at one candidate effect: do the instruments explain y - 2x?
small <- lm(I(earnings - 2 * x) ~ w, data = df)
large <- lm(I(earnings - 2 * x) ~ w + z1 + z2, data = df)
anova(small, large)These scripts use classical errors, so their numbers differ somewhat from the robust card above.
Recap
Recap- Endogeneity comes from omitted variables, reverse causation or measurement error, and residuals can't show it.
- Hausman and Durbin–Wu–Hausman compare least squares with IV. Weak instruments leave them with little power.
- Sargan and Hansen J compare instruments with each other, so passing doesn't establish validity.
- Anderson–Rubin stays valid with weak instruments.
Concepts in this lesson