diff-diff
A Python library for Difference-in-Differences (DiD) causal inference - sklearn-like estimators with statsmodels-style outputs, built for econometricians, marketing analysts, and data scientists running campaign-lift, policy, and staggered-rollout analyses.
Installation
pip install diff-diff
For development:
git clone https://github.com/igerber/diff-diff.git
cd diff-diff
pip install -e ".[dev]"
Quick Start
import pandas as pd
from diff_diff import DifferenceInDifferences # or: DiD
data = pd.DataFrame({
'outcome': [10, 11, 15, 18, 9, 10, 12, 13],
'treated': [1, 1, 1, 1, 0, 0, 0, 0],
'post': [0, 0, 1, 1, 0, 0, 1, 1],
})
did = DifferenceInDifferences()
results = did.fit(data, outcome='outcome', treatment='treated', post='post')
print(results) # DiDResults(ATT=3.0000, SE=1.7321, p=0.1583)
results.print_summary() # full statsmodels-style table
Documentation
For AI Agents
If you are an AI agent or LLM using this library, call diff_diff.get_llm_guide() for a concise API reference with an 8-step practitioner workflow (based on Baker et al. 2025). The workflow ensures rigorous DiD analysis - testing assumptions, running sensitivity analysis, and checking robustness, not just calling fit().
from diff_diff import get_llm_guide
get_llm_guide() # concise API reference
get_llm_guide("practitioner") # 8-step workflow (Baker et al. 2025)
get_llm_guide("full") # comprehensive documentation
get_llm_guide("autonomous") # autonomous-agent variant
The guides are bundled in the wheel - accessible from a pip install with no network access. After estimation, call practitioner_next_steps(results) for context-aware guidance on remaining diagnostic steps.
For Data Scientists
Measuring campaign lift? Evaluating a product launch? Rolling out a policy in waves? diff-diff handles the causal inference so you can focus on the business question.
- Which method fits my problem? - start from your business scenario (campaign in some markets, staggered rollout, survey data) and find the right estimator
- Getting started for practitioners - end-to-end walkthrough from marketing campaign to causal estimate to stakeholder-ready result
- Brand awareness survey tutorial - full example with complex survey design, brand funnel analysis, and staggered rollouts
- Have BRFSS/ACS/CPS individual records? Use
aggregate_survey() to roll respondent-level microdata into a geographic-period panel with inverse-variance precision weights for second-stage DiD
BusinessReport and DiagnosticReport are experimental preview classes that produce plain-English output and a structured to_dict() schema from any fitted estimator result except the two rejected by type (EventStudyResults surfaces and DurationDiDResults) - wording and schema will evolve. See docs/methodology/REPORTING.md for usage and stability notes.
Practitioner Workflow (Baker et al. 2025)
For rigorous DiD analysis, follow these 8 steps. Skipping diagnostic steps produces unreliable results.
- Define target parameter - ATT, group-time ATT(g,t), or event-study ATT_es(e). State whether weighted or unweighted.
- State identification assumptions - which parallel trends variant (unconditional, conditional, PT-GT-Nev, PT-GT-NYT), no-anticipation, overlap.
- Test parallel trends - simple 2x2:
check_parallel_trends(), equivalence_test_trends(); staggered: inspect CS event-study pre-period coefficients (generic PT tests are invalid for staggered designs). Insignificant pre-trends do NOT prove PT holds.
- Choose estimator - staggered adoption -> CS/SA/BJS (NOT plain TWFE); few treated units -> SDiD; factor confounding -> TROP; simple 2x2 -> DiD. Run
BaconDecomposition to diagnose TWFE bias.
- Estimate -
estimator.fit(data, ...). Always print the cluster count first and choose inference method based on the result (cluster-robust if >= 50 clusters, wild bootstrap if fewer - for DifferenceInDifferences pass cluster=; TwoWayFixedEffects auto-clusters at unit level).
- Sensitivity analysis -
compute_honest_did(results) for bounds under PT violations (the TwoWayFixedEffects event_study=True surface, CS, or dCDH natively; a StackedDiD results.aggregate('event_study') container also admits - Stacked needs kappa_pre >= 2), run_all_placebo_tests() for 2x2 falsification, specification comparisons for staggered designs.
- Heterogeneity - CS:
results.aggregate('group')/'event_study' (post-fit, no refit); SA: results.event_study_effects / to_dataframe(level='cohort'); Stacked: results.aggregate('event_study')/'simple' post-fit views (surface always computed since 3.9); EDiD: results.aggregate(...) post-fit from retained EIFs (3.9); ImputationDiD/TwoStageDiD: results.aggregate(...) post-fit from panel-backed kits (3.9); ContinuousDiD: results.aggregate('dose'/'simple'/'event_study') post-fit (3.9; dose/simple are views, event_study recomputes); subgroup re-estimation.
- Robustness - compare 2-3 estimators (CS vs SA vs BJS), report with and without covariates (shows whether conditioning drives identification), present pre-trends and sensitivity bounds.
Full guide: diff_diff.get_llm_guide("practitioner").
Estimators
- DifferenceInDifferences - basic 2x2 DiD with robust/cluster-robust SEs, wild bootstrap, formula interface, and fixed effects
- TwoWayFixedEffects - panel data DiD with unit and time fixed effects via within-transformation or dummies; event-study mode (
event_study=True) for period-specific treatment effects
- CallawaySantAnna - Callaway & Sant'Anna (2021) group-time ATT estimator for staggered adoption
- ChaisemartinDHaultfoeuille - de Chaisemartin & D'Haultfœuille (2020/2022) for reversible (non-absorbing) treatments with multi-horizon event study, normalized effects, cost-benefit delta, sup-t bands, and dynamic placebos. The most general option for treatments that switch on AND off (see also
LPDiD/TROP non_absorbing). Alias DCDH.
- SunAbraham - Sun & Abraham (2021) interaction-weighted estimator for heterogeneity-robust event studies
- ImputationDiD - Borusyak, Jaravel & Spiess (2024) imputation estimator, most efficient under homogeneous effects
- TwoStageDiD - Gardner (2022) two-stage estimator with GMM sandwich variance
- SpilloverDiD - Butts (2021) ring-indicator spillover-aware DiD identifying direct effect on treated + per-ring spillover on near-control units; handles non-staggered and staggered timing; supports survey-design variance under
survey_design= for HC1 / CR1 (Wave E.1 Binder TSL) and Conley (Wave E.2 panel-aware stratified-Conley sandwich on per-period PSU totals; extended in Wave E.2 follow-up to conley_lag_cutoff > 0 via panel-block composition with within-PSU serial Bartlett HAC — lag>0 requires an effective PSU via explicit survey_design.psu or injected cluster=<col>); SurveyDesign.subpopulation() preserves full-design n_psu / df_survey via zero-padded scores (Wave E.3, R svyrecvar(subset()) form)
- SyntheticDiD - Synthetic DiD combining standard DiD and synthetic control for few treated units
- SyntheticControl - Abadie, Diamond & Hainmueller (2010) classic synthetic control for a single treated unit (donor-weight counterfactual, nested/cv/inverse-variance/custom V; in-space placebo permutation inference via
in_space_placebo(), plus ADH-2015 leave_one_out() + in_time_placebo() robustness, Firpo-Possebom (2018) test-inversion confidence sets, and Chernozhukov-Wüthrich-Zhu (2021) conformal inference)
- TripleDifference - triple difference (DDD) estimator for designs requiring two criteria for treatment eligibility; serves both the 2x2x2 and the staggered-adoption design (Ortiz-Villavicencio & Sant'Anna (2025) staggered DDD with group-time ATT) from one signature (
fit(..., first_treat=) selects the staggered engine)
- ContinuousDiD - Callaway, Goodman-Bacon & Sant'Anna (2024) continuous treatment DiD with dose-response curves
- HeterogeneousAdoptionDiD - de Chaisemartin, Ciccia, D'Haultfœuille & Knau (2026) for designs where no unit remains untreated; local-linear estimator at the dose support boundary returning Weighted Average Slope (WAS) on Design 1' (
d̲ = 0 / QUG) or WAS_{d̲} on Design 1 (d̲ > 0, continuous-near-d̲ or mass-point), with a multi-period event-study extension (last-treatment cohort, pointwise CIs). Panel-only in this release - repeated cross-sections rejected by the validator. Alias HAD.
- RegressionDiscontinuity - Calonico, Cattaneo & Titiunik (2014) sharp, fuzzy, AND covariate-adjusted regression discontinuity with robust bias-corrected inference and rdrobust-parity bandwidth selection (all 10 selectors, mass-point handling; fuzzy via
takeup= with a first-stage block and weak-identification warning; covariates via covariates= - CCFT 2019, same estimand, covariate-aware bandwidths). Canonical att is the bias-corrected estimate with a coherent robust CI (rdrobust's printed headline is att_conventional). Alias RDD.
- StackedDiD - Wing, Freedman & Hollingsworth (2024) stacked DiD with Q-weights and sub-experiments; optional covariate balancing (Ustyuzhanin 2026)
- EfficientDiD - Chen, Sant'Anna & Xie (2025) efficient DiD with optimal weighting for tighter SEs
- TROP - Triply Robust Panel estimator (Athey et al. 2025) with nuclear norm factor adjustment
- WooldridgeDiD - Wooldridge (2023, 2025) ETWFE: saturated OLS, logit/Poisson QMLE (ASF-based ATT). Alias
ETWFE.