CCausal inference · causal.iv
Instrumental variables (2SLS / LIML / GMM)
What is the effect of a treatment that is not randomly assigned, using a variable that shifts the treatment but affects the outcome only through it?
Two-stage least squares, LIML or two-step efficient GMM with robust or clustered standard errors, and the diagnostics that decide whether the instruments can be trusted: first-stage F statistics (and the effective F), the Anderson–Rubin test and confidence set (valid even with weak instruments), the test of overidentifying restrictions (Sargan, or Hansen's J under GMM), the Wu–Hausman test of endogeneity and the classic Hausman contrast of IV against OLS, beside the naive OLS estimate.
A real result
Example “Robust overid”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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.
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.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Robust overidc1_iv · covariates: w · instrument: z1, z2 · outcome: earnings (k) · treatment: x
- Liml clusterc1_iv · cluster: region · covariates: w · instrument: z1, z2, zb · outcome: earnings (k) · treatment: x
- Weak classicalc1_iv · instrument: zw · outcome: earnings (k) · treatment: x
- Gmm robust hansenc1_iv · covariates: w · instrument: z1, z2, zb · outcome: earnings (k) · treatment: x
- Gmm clusterc1_iv · cluster: region · covariates: w · instrument: z1, z2 · outcome: earnings (k) · treatment: x
- Binary treatmentc1_iv · covariates: w, region · instrument: zb · outcome: yd · treatment: d
- Degenerate constantc1_iv · covariates: w · instrument: z1, z2 · outcome: earnings (k) · treatment: x
- Degenerate n3c1_iv · covariates: w · instrument: z1, z2 · outcome: earnings (k) · treatment: x
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Causal inference (experiments, DiD, IV, RDD) · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric · 1 column
- The outcome the treatment may affect.
- Endogenous treatmentnumeric / boolean · 1–3 columns
- The treatment (or exposures) whose effect is wanted; the first one is the headline.
- Instrumentsnumeric / boolean · 1–10 columns
- Variables that shift the treatment and affect the outcome only through it. Need at least as many as treatments.
- Covariatesnumeric / boolean / categorical · 0–30 columns
- Exogenous controls (used in both stages).
- Clustercategorical / numeric · 0–1 column
- Clusters for standard errors.
Choices you make
statistics
- Estimatordefault 2sls
2SLS is standard; LIML is less biased with weak or many instruments; GMM is efficient and gives Hansen's J test.
- Two-stage least squares(default) — The standard two-stage estimator; the usual choice with strong instruments.
- LIML (less biased with many or weak instruments) — Limited-information maximum likelihood; less biased when instruments are many or weak.
- Two-step efficient GMM — Weights the instruments by the inverse of their estimated moment covariance: more efficient than 2SLS under heteroskedasticity, and its overidentification test is Hansen's J.
- Standard errorsdefault robust
With a cluster column, standard errors are clustered.
- Heteroskedasticity-robust (HC1)(default) — Stays valid when the error variance changes; the usual choice.
- Classical — Assumes constant error variance; pick it to match textbook 2SLS results.
- Anderson–Rubin confidence setdefault on
A confidence set for the first treatment that stays valid with weak instruments.
hypothesis
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Instrument strength
The instruments shift the treatment (first-stage F well above 10).
Exclusion restriction
The instruments affect the outcome only through the treatment. Untestable with one instrument per treatment.
IndependenceNot checked from data: state why it holds
The instruments are as good as randomly assigned given the covariates.
MonotonicityNot checked from data: state why it holds
No one is pushed away from treatment by the instrument (needed to read the estimate as a LATE).
Overidentifying restrictions
With more instruments than treatments, a test of whether they agree; it can't prove any one of them valid.
Endogeneity of the treatment
Whether the treatment is endogenous at all; if not, OLS is more precise.
OLS against IV (Hausman)
Compares the OLS and IV estimates; a large gap means they answer differently.
What it reports
- Tests: Instrumental-variables effect
- estimate
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- t
- An estimate divided by its standard error, compared with a t distribution.
- p_value
- How surprising your data would be if the null hypothesis were true, as a probability.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- n
- How many independent units the analysis used; it sets precision and power.
- df_resid
- How much independent information is left to estimate variability after fitting the model.
- estimand
- The exact quantity an analysis targets, such as a difference in means or a ratio of medians.
- effect_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- claim_level_max
- How strong a causal statement the design supports, from association up to a causal effect.
- first_stage_f
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- ols_estimate
- Fits a line, or a plane, by choosing the coefficients that make the sum of squared residuals as small as possible.
- k_instruments
- A variable that shifts treatment but affects the outcome only through treatment.
- k_treatments
- A variable that shifts treatment but affects the outcome only through treatment.
Per group, level or term: effective_f, wu_hausman_f, wu_hausman_p, overid_stat, overid_df, overid_p, hausman_chi2, hausman_df, hausman_p, ar_p, ar_ci_low, ar_ci_high, ar_shape, first_stage_f[…], first_stage_p[…], check[<id>], coef[<term>], coef_se[…], estimator, se_type, kappa, partial_r2[<instrument>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, linearmodels, codesplash; R uses ivreg, sandwich, nanoparquet, codesplashr.
Default traps between the two languages
- 2SLS: linearmodels IV2SLS (debiased) ↔ ivreg + sandwich (HC1 / vcovCL HC1). LIML: linearmodels IVLIML ↔ the codesplashr k-class twin (R has no standard LIML).
- GMM: two-step efficient GMM by the codesplash twin in both engines (identical to linearmodels' IVGMM with debiased covariance; Hansen's J from the first-step weight matrix). The Hausman contrast uses classical covariances on the OLS residual variance (Stata's sigmamore) and a generalized inverse.
- Diagnostics (first-stage Wald F, effective F, Anderson–Rubin, overidentification and Wu–Hausman tests) are computed by twins in both engines; the Anderson–Rubin set is found on a grid refined by bisection (agreement ≈ 1e-8).
The exact script CodeSplash ran for example “Robust overid” · 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 exact script CodeSplash ran for example “Robust overid” · 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
))
Sources
- Angrist, J. D., Imbens, G. W., & Rubin, D. B. (1996). Identification of causal effects using instrumental variables. JASA, 91, 444–455.
- Montiel Olea, J. L., & Pflueger, C. (2013). A robust test for weak instruments. Journal of Business & Economic Statistics, 31, 358–369.
- Hansen, L. P. (1982). Large sample properties of generalized method of moments estimators. Econometrica, 50, 1029–1054.
- Hausman, J. A. (1978). Specification tests in econometrics. Econometrica, 46, 1251–1271.
- Andrews, I., Stock, J. H., & Sun, L. (2019). Weak instruments in instrumental variables regression: theory and practice. Annual Review of Economics, 11, 727–753.
From the CodeSplash method registry · causal.iv v1.1.2.