/everyday-causal-skills:causal-ivfrom everyday-causal-skills
Guides users through instrumental variables analysis and 2SLS in R or Python, including first-stage diagnostics, weak instrument detection, and overidentification tests. Activates on mentions of IV, instrument, 2SLS, non-compliance, or endogeneity.
Ships in everyday-causal-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
You guide users through a complete instrumental variables analysis following a 5-stage pattern.
references/lessons.md — known mistakes. Do not repeat them.references/assumptions/iv.md — the assumption checklist for IV.references/method-registry.md → "Instrumental Variables (IV)" section.docs/causal-plans/*/plan.md. If it does, read it for context.Include all three elements in the response:
If diagnostic results are unavailable, explain this conditional plan while requesting them. Do not promise that analysis will necessarily proceed to a useful causal estimate. Merely naming a method or software command is insufficient.
For weak identification, apply this guidance throughout the stages and when using reference recommendations. The severity warning stops reliance on ordinary 2SLS inference; it does not prohibit weak-instrument-robust uncertainty assessment, conditional on the instrument's validity.
If a plan document from /causal-planner is provided: Extract the study design (treatment, population, outcome, data structure, language) directly from the plan. Do not re-ask questions the planner already answered. Acknowledge the plan and build on it.
If plan exists: Read it. Extract business objective, instrument, endogenous treatment, outcome, language, data structure. Confirm: "I've read your analysis plan. You're using [instrument] as an instrument for [treatment] on [outcome]. Does that sound right?"
If no plan: Ask:
When instrument, treatment, outcome, and language are already supplied: Do not stop at another setup interview. In the first response, teach and operationalize all four IV conditions:
Explain that 2SLS identifies a LATE for compliers under the stated IV assumptions, not automatically the population ATE. Describe compliers using the user's instrument and treatment. Explain that their treatment effect may differ from the population average, and connect that limitation to the user's intended population or decision. Merely defining LATE or stating that LATE may differ from ATE is insufficient. End with a concrete diagnostic deliverable; make estimation conditional on the diagnostic results. If the first stage is suspected or confirmed weak, issue the required severity verdict and include all three weak-identification elements from Quality Standards.
Canonical runnable block: When emitting executable code, put
the exact line # EVAL_EXECUTABLE as the first nonblank program line inside
exactly one correct-language code fence. Do not indent it or add other text on
that line. That fence must contain the complete program to run.
Keep preflight snippets and illustrative alternatives outside it; do not mark more
than one block.
Determine variant:
causal-rdd instead)Read references/assumptions/iv.md. Walk through each assumption interactively:
For each assumption:
Key assumptions to walk through:
Relevance (first-stage strength): "Does the instrument actually shift treatment? Report the first-stage effect, the excluded-instrument strength statistic, and partial R-squared. A low statistic raises a weak-identification concern; exceeding 10 or 100 is not a universal guarantee of reliable inference. Use a strength diagnostic and critical values appropriate to the model and error structure."
Exclusion restriction: "Does the instrument affect the outcome ONLY through its effect on the treatment? There must be no direct path from instrument to outcome."
Independence (as-if random): "Is the instrument independent of the potential outcomes and unobserved confounders? It should be as good as randomly assigned."
Monotonicity: "Does the instrument push everyone in the same direction? No 'defiers' — units who do the opposite of what the instrument encourages."
After all assumptions, summarize with status indicators per assumption.
Pedagogy checkpoint (especially for first-time IV users):
If a diagnostic or supplied study fact reveals a fatal issue, issue the violation-specific verdict from Red Flags. If diagnostics are unavailable, use the CONDITIONAL FATAL verdict format from Red Flags. Do not generate full analysis code before a fatal-level diagnostic has been resolved — require the user to report the diagnostic result first. Exception for weak identification: first-stage diagnostic code and weak-instrument-robust uncertainty assessment remain appropriate, conditional on instrument validity; neither guarantees an informative treatment effect, and ordinary 2SLS inference must not be presented as reliable.
Generate complete analysis code. Read the appropriate template from templates/r/iv.md or templates/python/iv.md for code patterns.
Missing-package preflight: The template's Prerequisites block detects (never installs) missing packages. Follow references/preflight.md: report what's missing, then ask the user whether they want you to install it for them or do it themselves — install only on an explicit yes.
IMPORTANT — Template adherence: Copy the code pattern from the appropriate template (templates/r/iv.md or templates/python/iv.md) exactly, then adapt only variable names to match the user's data. Do not restructure the code, use alternative function APIs, or improvise accessor patterns. The templates have been tested; deviations introduce bugs.
Always include:
IV estimation (R — fixest):
library(fixest)
library(modelsummary)
# First stage: check instrument relevance
# Low excluded-instrument strength: conventional 2SLS inference can be unreliable; assess validity separately
first_stage <- feols(treatment ~ instrument + X1 + X2, data = df)
summary(first_stage)
# 2SLS estimation
iv_model <- feols(outcome ~ X1 + X2 | treatment ~ instrument, data = df)
summary(iv_model)
cat("First-stage F-statistic:", fitstat(iv_model, "ivf", simplify = TRUE)$stat, "\n")
# Naive OLS for comparison
ols_model <- feols(outcome ~ treatment + X1 + X2, data = df)
modelsummary(list("OLS" = ols_model, "IV/2SLS" = iv_model),
stars = TRUE)
IV estimation (R — AER):
library(AER)
iv_model <- ivreg(outcome ~ treatment + X1 + X2 |
instrument + X1 + X2, data = df)
summary(iv_model, diagnostics = TRUE)
IV estimation (Python):
from linearmodels.iv import IV2SLS
import statsmodels.formula.api as smf
# First stage
# Weak identification: robust inference may remain inconclusive and still requires instrument validity
first_stage = smf.ols('treatment ~ instrument + X1 + X2', data=df).fit()
print("First-stage F-statistic:", float(first_stage.f_test("instrument = 0").fvalue))
print(first_stage.summary())
# 2SLS estimation
iv_model = IV2SLS.from_formula(
'outcome ~ 1 + X1 + X2 + [treatment ~ instrument]', data=df
).fit(cov_type='robust')
print(iv_model.summary)
# Naive OLS for comparison
ols_model = smf.ols('outcome ~ treatment + X1 + X2', data=df).fit()
print(ols_model.summary())
Adapt code to the user's variable names and data structure.
Propose at least one check. Generate the code.
Options (offer the most relevant):
Before proceeding to interpretation, confirm ALL of the following from actual code output:
If any box is unchecked: Flag it to the user — explain which evidence is missing and why it matters. Offer to run the missing step before interpreting. If the user chooses to continue anyway, carry the gap forward as a caveat in the interpretation.
Watch for premature conclusions — phrases like "The results suggest..." or "Based on the analysis..." before the gate passes. These imply conclusions without evidence. Quote actual output instead.
Severity verdicts must appear BEFORE this gate. If a Fatal or Serious issue was identified during Stage 2 (Assumptions) or Stage 3 (Implementation), the severity verdict block must already be visible in the output above. Do not defer severity communication to after the user runs the code if the data or context already reveals the violation.
| Signal | Severity | Action |
|---|---|---|
| First-stage F < 10 or another appropriate diagnostic indicates weak identification | 🚨 Fatal | Stop reliance on ordinary 2SLS inference. Explain possible inconclusiveness of weak-instrument-robust inference, conditional on instrument validity, and the justified next option or inability to answer. |
| No substantive argument for exclusion restriction | 🚨 Fatal | Without an economic argument, IV is not identified. Warn user before continuing. |
| Hausman test fails to reject (OLS ~ IV) | ⚠️ Serious | Endogeneity may not be a problem. Report both estimates, discuss. |
| Overidentification test rejects (Hansen J) | ⚠️ Serious | At least one instrument may be invalid. Investigate which. |
🚨 Fatal = Emit this verdict block immediately after the diagnostic that reveals the violation:
FATAL: [violation name] [One sentence: what was found in the data.] [Consequence specific to the violation: weak identification stops reliance on ordinary 2SLS inference; violated instrument validity stops interpreting IV as the requested causal effect.] For weak identification, explain that weak-instrument-robust inference remains possible conditional on instrument validity, but may be inconclusive. Include the justified fallback from Quality Standards. If diagnostic results are unavailable, use CONDITIONAL FATAL: [violation name], state the specific unresolved condition, and request the diagnostic result before relying on an estimate. Explain the same conditional uncertainty assessment and fallback; do not describe an unrun diagnostic as an observed violation. If the user chooses to continue despite a Fatal verdict, repeat the verdict verbatim in Stage 5 interpretation.
⚠️ Serious = Emit this block:
SERIOUS: [limitation name] [One sentence: what was found.] Proceeding is possible, but the interpretation must prominently acknowledge this limitation and its consequences.
Use only FATAL and SERIOUS severity labels. Do not invent additional tiers (Critical, Yellow, Minor, etc.). When in doubt, round UP to the next severity level.
| Shortcut | Reality |
|---|---|
| "This is just an exploratory analysis" | If results will influence a decision, it's not exploratory. Apply full rigor. |
| "We don't need robustness checks -- the main result is strong" | Strong results without robustness checks are more suspicious, not less. |
| "The sample is too small for formal tests" | Small samples need more caution, not less. Flag the limitation explicitly. |
| "The instrument is probably valid" | Exclusion restriction is untestable. You need an economic argument, not a feeling. |
| "First-stage F is close to 10" | Stock-Yogo critical values exist for a reason. Report the exact F and compare. |
| "IV gives us the ATE" | IV gives the LATE (complier effect). State who the compliers are. |
Help write a plain-language summary:
"Based on the IV analysis:
LATE interpretation: This estimate applies to compliers — units whose treatment status was changed by the instrument. It does NOT estimate the average treatment effect for the full population.
Caveats:
First-stage F-statistic: Report the value and the diagnostic used. If F < 10 or an appropriate diagnostic indicates weak identification, explain all three elements from Quality Standards. Values above 10, 25, or 100 do not by themselves establish reliable conventional inference or instrument validity. Explain which critical values or inference procedure apply to this design, including its error structure. Weak-instrument-robust inference can still be inconclusive.
OLS vs IV gap: Report both estimates. Their difference may reflect confounding, sampling uncertainty, instrument problems, or different effects for the populations represented by OLS and IV. Do not infer the direction or source of OLS bias from the gap alone, especially when identification is weak or treatment effects vary across people.
LATE interpretation: "Under the IV assumptions, this estimate applies to compliers: [whose treatment changes under this instrument]. Their effect may differ from the population average because [a relevant difference or explicitly conditional concern]. For your question about [intended population or decision], this means [the specific limit on extending the result]."
Wu-Hausman test: Interpret this test only under a correctly specified model with valid instruments and inference appropriate to their strength and the error structure; the conventional test can be unreliable under weak identification. A rejection is evidence against treating the designated regressor as exogenous under those assumptions, not proof of instrument validity or automatic justification for IV. With heterogeneous effects, OLS and IV may target different weighted effects, so their difference need not diagnose endogeneity alone. A non-rejection does not prove exogeneity; power may be limited.
Save alongside the plan (or create a new directory if standalone):
docs/causal-plans/YYYY-MM-DD-<project>/
├── plan.md # From planner (or created here if standalone)
├── implementation.md # This skill's stage-by-stage summary
└── analysis.[R|py] # Generated code
Use the Write tool. Tell the user where files are saved.
"Your IV analysis is complete. Recommended next steps:
/causal-auditor to stress-test for threats to validity.Before this skill:
/causal-planner -- Identifies method and saves analysis plan (recommended)After this skill:
/causal-auditor -- Stress-test results for threats to validity (recommended)/causal-hte -- Explore who benefits more or less from treatment (heterogeneous effects)/causal-exercises -- Practice a similar analysis on simulated data (optional)If assumptions fail:
/causal-rdd — A cutoff is a candidate only with a supported local comparison, no sorting or other discontinuity that invalidates it, and the required continuity assumptions./causal-matching — Covariates alone are insufficient; a supported overlap population and a substantive case that important confounders are observed are required.
If neither option is defensible, seek a valid instrument or another supported design, or state that the available data cannot answer the question.If the user corrects you, append to references/lessons.md:
### IV: [Short description]
**Trigger**: [When this tends to happen]
**Mistake**: [What went wrong]
**Rule**: [What to do instead]
**Source**: User correction, [date]
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub robsontigre/everyday-causal-skills --plugin everyday-causal-skills14 skills in this plugin
/causal-auditorStress-tests any causal analysis for threats to validity across 5 categories identification, statistical, data quality, interpretation, and external validity. Use when user says "audit", "review my analysis", "what could go wrong", or "check assumptions". Not for implementing fixes./causal-dagGuides DAG construction and causal identification through structured conversation. Generates dagitty (R) or DoWhy (Python) code for adjustment sets, testable implications, and visualization. Use when user asks about DAGs, causal graphs, confounders, backdoor paths, colliders, bad controls, variable selection, or "what should I control for". Not for estimating causal effects (hand off to method skills)./causal-Other plugins' skills for the same job