Skip to content

Add experimental native ChainedDiD for incomplete panels - #887

Open
shawcharles wants to merge 3 commits into
igerber:mainfrom
shawcharles:contrib/chained-did-native
Open

shawcharles wants to merge 3 commits into
igerber:mainfrom
shawcharles:contrib/chained-did-native

Conversation

@shawcharles

@shawcharles shawcharles commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Add experimental native ChainedDiD for overlapping incomplete panels. It combines observed within-unit changes to recover group-time effects, using normalised per-pair IPW, never-treated controls, PT-post and identity GMM. Results keep original-unit population accounting, analytical unit or cluster covariance, canonical aggregation and explicit support diagnostics. The contract is restricted to binary absorbing treatment, zero anticipation and static complete covariates.

This revision implements the fixed target and is merged with main at 7723c6de. My note lists the points that need a ruling, and a follow-up reports the covariate simulation.

Methodology references (required if estimator / math changes)

  • Method name(s): chained difference-in-differences, identity-weighting variant.
  • Paper / source link(s): Bellégo, Benatia and Dortet-Bernadet (2025), The chained difference-in-differences, Journal of Econometrics. The specification is the formal review in docs/methodology/papers/bellego-2025-review.md (docs(methodology): Bellégo, Benatia & Dortet-Bernadet (2025) chained difference-in-differences paper review #909).
  • Any intentional deviations from the source (and why):
    • Identity GMM, where the paper proposes optimal weighting. Settled in the fixed target.
    • The propensity logit is fitted separately on each observed pair. The paper fits once per cohort, and cdid uses a response-calibrated pair score. Settled in the fixed target and recorded in REGISTRY.
    • Pairs with fewer than 20 observed units in either arm, or control ESS below 20, are excluded. A failed pair logit excludes that pair with a reason and the fit continues. The paper gives no rule for thin pairs.
    • The reference period, free pre-period parameters, the identity-weighting sandwich and clustering are library choices where the paper is silent. The pseudocode disposes of the review's fourteen printed inconsistencies.
    • Not implemented: optimal GMM, OR/DR, attrition correction, not-yet-treated controls, survey designs, simultaneous bands and bootstrap.

Validation

  • Tests added/updated: tests/test_chained_did*.py and tests/test_methodology_chained_did.py. On the current head, the focused set passes (578 tests on pandas 2.3.3), and the ChainedDiD tests pass on pandas 3.0.3 with NumPy 2.4.5 and SciPy 1.17.1 (139 tests). ruff 0.17.1, black 26.10.1 and mypy 2.4.0 pass. The documentation builds with warnings as errors and the tutorial cells execute.
  • Backtest / simulation / notebook evidence (if applicable):
    • cdid 1.4.0.0 (R 4.5.2, did 2.5.1, DRDID 1.4.0): eight of nine fixtures match, with covariance discrepancy below 7e-15. The incomplete continuous-covariate fixture differs because the propensity criterion differs by design. The comparison image was upgraded in place; the tracked Dockerfile has not been built from clean.
    • Sparse grid, ten cases at 2,000 replications: no fit fails. Coverage is 0.9395 and 0.9345 in two cases, so the literal 0.94 flag is false. I read this as coverage of about 0.94 at the 20-unit boundary, not a literal all-case pass.
    • Identity GMM ignores pair precision. In the retained 20/190 case the empirical SD is 0.0940, against about 0.0434 where thin pairs are excluded.
    • Covariate qualification grid, rerun on this head and not part of the branch (13 designs at 2,000 replications, seed 20261102): no fit fails, and 34 of 39 targets are unchanged from the pre-policy run. In the n=1,000 cohort-dependent design the exclusion rule leaves a required cell unsupported in 85 of 2,000 fits, so the overall ATT is unavailable there. When available, its coverage is 0.939, as before. Four n=1,000 targets sit between 0.930 and 0.937, also as before.
  • Checked on the first submission only, not rerun on this head: the complete non-slow suite, the Python 3.9 and 3.15 checks, and a local wheel with the native backend.
  • Not run: hosted CI. The workflows are waiting for approval.

This contribution makes no general finite-sample calibration claim and no blanket R-parity claim.

Security / privacy

  • Confirm no secrets/PII in this PR: confirmed. Benchmark fixtures are simulated.

Changelog

  • changelog.d/ fragment added (or N/A - no user-visible change): changelog.d/20261102-chained-did.md.

🤖 Generated with Claude Code

…anels

Context:
- Extend diff-diff to overlapping incomplete panels using within-unit changes,
  with a paper-derived algorithm and cdid as an external validation reference.

Changes:
- Add ChainedDiD and ChainedDiDResults with normalised pair IPW, never-treated
  controls, PT-post and fixed identity GMM; support static complete covariates.
- Preserve original-unit accounting and provide analytical unit/cluster
  covariance, canonical aggregation, constituent weights and support diagnostics.
- Add API/LLM documentation, executable tutorial, public exports, plotting
  integration, algebraic/reference tests and source-bound simulation evidence.
- Retain failed coverage qualification and the known continuous-covariate R
  criterion difference. Sparse-pair pointwise intervals remain experimental.
- Record the subsequent user-supplied numerical review; keep maintainer
  inference-policy and propensity-criterion decisions explicit before merge.
- Exclude OR/DR, attrition correction, survey designs, optimal GMM, bootstrap and
  simultaneous bands. Preserve upstream 4.0.0 release metadata and dependencies.

Verification:
- Clean upstream contribution: default non-slow pytest suite, 15,619 passed and
  291 skipped on CPython 3.14 with the local OpenBLAS backend available.
- Focused estimator/reference/integration checks: 609 passed.
- Minimum-version/reference checks: 111 passed each on Python 3.9 and 3.15.
- Built and installed a local CPython 3.14 Linux/OpenBLAS wheel; isolated Python
  and Rust consumers agree exactly across four configurations, including
  aggregation, pickle and plotting checks.
- Tutorial 34 executed; Sphinx with -W, Black and Ruff passed.
- Independent submission review found no actionable packaging findings.
- Subsequent user-supplied numerical review confirmed the bounded fixes but
  retained sparse-pair undercoverage and requested explicit merge decisions.
- Submission wording and review-record correction only: previous execution
  logs retained; estimator code, tests and frozen evidence unchanged.
- Not run: hosted/non-Linux CI, portable manylinux build, or fresh broad
  Monte Carlo qualification. Existing qualification failures remain documented.
@igerber

igerber commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thanks, Charles. This is careful work and I want it in. Below is a fixed target; a line-by-line review comes once you mark it ready and will not reopen these points.

Reference target. I wrote a formal review of the paper, in #909 (docs/methodology/papers/bellego-2025-review.md). Please treat it as the specification. The points that bear on this PR:

  • The paper's proposed estimator uses optimal weighting; identity weighting is a named variant.
  • For the general stacked system it prints the variance only under optimal weighting.
  • It fits the propensity score once per cohort on all units.
  • It gives no rule for thinly observed pairs and reports no coverage evidence.
  • It lists 14 printed inconsistencies, including the sign of the influence function.

What I verified: your tests pass merged with main; on balanced panels the results equal CallawaySantAnna IPW exactly; on 1,000 incomplete panels they match cdid identity weighting to 1e-14. I also reproduced the sparse-pair failure (coverage 0.73).

Your two questions

  1. Inference: keep identity GMM, but exclude pairs below 20 units per arm (or control ESS below 20) instead of warning. On your ten-case grid plus six more, at 2,000 replications, that passes every case (lowest coverage 0.9405); the current rule fails five. A failed logit on a pair should exclude that pair with a reason, not abort the fit: with five covariates in a thin design, 18% of fits aborted.
  2. Propensity: keep your per-pair fit. In my simulations it was unbiased, with coverage similar to the paper's per-cohort fit and equal or better precision. Record it as a deviation from the paper and from R.

Precision cost that remains. Exclusion fixes coverage, not efficiency. With n=4,000, keeping pairs that have 20 to 50 treated units gives a spread of 0.069 to 0.092 for ATT(3,3), against about 0.045 when those pairs are dropped. Please document this. Precision-aware weighting, such as your count-weighted prototype, is a welcome follow-up but not a merge condition.

Also accepted: the restricted experimental scope, and a coverage bar of about 0.94 in place of your exact-nominal gate, since the balanced-panel case is identical to CallawaySantAnna.

Please document as choices the paper leaves open: the reference period and free pre-period parameters, the identity-weighting variance, and clustering.

API alignment (changes requested)

  1. group_time_effects values: from GroupTimeEffect objects to plain dicts. Today a cell is read as res.group_time_effects[(g, t)].effect; please make it res.group_time_effects[(g, t)]["effect"], with the keys CallawaySantAnna returns: effect, se, t_stat, p_value, conf_int, n_treated, n_control, skip_reason. You followed our guide here, which documents the object type; the estimators return dicts, and I will correct the guide.
  2. Per-cell table from to_dataframe(): rename att to effect, and replace available and status with a single skip_reason column (None when the cell is estimable, otherwise your reason string). n_treated and n_control can stay.
  3. Rename aggregation_weights(level) to get_aggregation_weights_df(level), matching get_unit_weights_df() and get_weights_df() elsewhere. The current name already exists on WooldridgeDiDResults as a field with a different meaning. In its returned table, replace available with skip_reason as in item 2.
  4. Turn the EPV check back on (the logit is currently called with epv_threshold=0): expose epv_threshold on the estimator and report per-cell results in epv_diagnostics, as CallawaySantAnna does.
  5. Add the standard metadata fields to the results: groups, time_periods, n_obs, cluster_name, n_clusters.

I will handle the tutorial renumbering, condensing the methodology documents into the REGISTRY entry, and the plotter change on your branch. Please re-run the cdid comparison at 1.4.0.0.

shawcharles and others added 2 commits December 1, 2026 22:52
Context:
- The maintainer fixed the target for PR igerber#887 in issue comment 7175894148,
  specified against the formal paper review merged in igerber#909.
- The estimator kept thin pairs with a warning and aborted the whole fit when
  one pair's propensity logit failed. Its result API also differed from the
  other staggered estimators.
- Two independent reviews ran before this commit. Their corrections are
  included.

Changes:
- Pair eligibility: exclude pairs with fewer than 20 observed units in either
  arm or control effective sample size below 20. The previous rule required
  two units and warned below 20.
- Failure handling: a failed pair propensity fit excludes that pair with a
  recorded reason and detail, and the fit continues on the remaining paths.
  Only propensity-model failures are local. Outcome overflow still raises,
  with or without covariates. Warning categories other than UserWarning from
  the logit helper pass to the caller.
- EPV: expose epv_threshold (default 10), enable the shared check and report
  per-cell epv_diagnostics from contributing pairs. A fit issues one summary
  warning for retained low-EPV pairs.
- Result API, unreleased and without a compatibility alias: plain-dict cells
  with effect, se, t_stat, p_value, conf_int, n_treated, n_control and
  skip_reason; to_dataframe() uses effect and skip_reason;
  get_aggregation_weights_df(level) replaces aggregation_weights(level); add
  groups, time_periods, n_obs, cluster_name and n_clusters.
- Table skip_reason columns have object dtype, so estimable cells hold None on
  pandas 2 and 3. n_obs counts observed outcomes. to_dict() returns a detached
  structure.
- Documentation: identity GMM as the paper's named variant; the per-pair
  propensity fit as a deviation from the paper and from R under REGISTRY
  labels; the reference period, free pre-period parameters, identity sandwich
  and clustering as library choices; dispositions of the review's fourteen
  printed inconsistencies.
- Evidence: cdid comparison re-run at 1.4.0.0 (R 4.5.2, did 2.5.1, DRDID
  1.4.0) and a new sparse-policy report. Historical 1.1.0.0 records are
  unchanged.

Limits:
- Sparse grid, 2,000 replications per case: coverage is 0.9395 and 0.9345 in
  two of ten cases, so the literal 0.94 acceptance flag is false. This is
  consistent with the maintainer's bar of about 0.94, not a literal pass.
- The incomplete continuous-covariate R fixture still differs, because the
  per-pair propensity criterion differs from cdid's by design.
- Identity GMM ignores pair precision, so retained thin pairs cost precision.
- The estimator predates docs/input-contract.md. It treats NaN outcomes as
  unobserved (IC-03 refuses them) and requires 0 as the never-treated marker
  (IC-15 also allows +inf). Both are left for the maintainer to rule on.
- The reference image was upgraded in place; the tracked Dockerfile has not
  been built from clean.

Verification:
- Focused chained, methodology, doc-dependency and changelog tests: 477 passed
  on pandas 2.3.3.
- Chained tests on pandas 3.0.3, NumPy 2.4.5 and SciPy 1.17.1: 139 passed.
- ruff 0.17.1, black 26.10.1 and mypy 2.4.0 pass.
- cdid 1.4.0.0 comparison: eight of nine fixtures pass, with the expected
  mismatch. Both reports were regenerated from this source.
- Tutorial code cells executed.
- Not run: hosted CI, the complete suite, the Python version matrix, the
  native backend, a clean rebuild of the reference image, and a simulation of
  the covariate path under the new policy.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Integrates igerber/diff-diff main at 7723c6d so that PR igerber#887 is current
before review. The merge has no conflicts. Merged instead of rebased to keep
the published PR head ecdd1e0 in the history.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
shawcharles pushed a commit to shawcharles/diff-diff that referenced this pull request Dec 1, 2026
Context:
- The maintainer fixed the target for PR igerber#887 in issue comment 7175894148,
  specified against the formal paper review merged in igerber#909.
- The estimator kept thin pairs with a warning and aborted the whole fit when
  one pair's propensity logit failed. Its result API also differed from the
  other staggered estimators.
- Two independent reviews ran before this commit. Their corrections are
  included.

Changes:
- Pair eligibility: exclude pairs with fewer than 20 observed units in either
  arm or control effective sample size below 20. The previous rule required
  two units and warned below 20.
- Failure handling: a failed pair propensity fit excludes that pair with a
  recorded reason and detail, and the fit continues on the remaining paths.
  Only propensity-model failures are local. Outcome overflow still raises,
  with or without covariates. Warning categories other than UserWarning from
  the logit helper pass to the caller.
- EPV: expose epv_threshold (default 10), enable the shared check and report
  per-cell epv_diagnostics from contributing pairs. A fit issues one summary
  warning for retained low-EPV pairs.
- Result API, unreleased and without a compatibility alias: plain-dict cells
  with effect, se, t_stat, p_value, conf_int, n_treated, n_control and
  skip_reason; to_dataframe() uses effect and skip_reason;
  get_aggregation_weights_df(level) replaces aggregation_weights(level); add
  groups, time_periods, n_obs, cluster_name and n_clusters.
- Table skip_reason columns have object dtype, so estimable cells hold None on
  pandas 2 and 3. n_obs counts observed outcomes. to_dict() returns a detached
  structure.
- Documentation: identity GMM as the paper's named variant; the per-pair
  propensity fit as a deviation from the paper and from R under REGISTRY
  labels; the reference period, free pre-period parameters, identity sandwich
  and clustering as library choices; dispositions of the review's fourteen
  printed inconsistencies.
- Evidence: cdid comparison re-run at 1.4.0.0 (R 4.5.2, did 2.5.1, DRDID
  1.4.0) and a new sparse-policy report. Historical 1.1.0.0 records are
  unchanged.

Limits:
- Sparse grid, 2,000 replications per case: coverage is 0.9395 and 0.9345 in
  two of ten cases, so the literal 0.94 acceptance flag is false. This is
  consistent with the maintainer's bar of about 0.94, not a literal pass.
- The incomplete continuous-covariate R fixture still differs, because the
  per-pair propensity criterion differs from cdid's by design.
- Identity GMM ignores pair precision, so retained thin pairs cost precision.
- The estimator predates docs/input-contract.md. It treats NaN outcomes as
  unobserved (IC-03 refuses them) and requires 0 as the never-treated marker
  (IC-15 also allows +inf). Both are left for the maintainer to rule on.
- The reference image was upgraded in place; the tracked Dockerfile has not
  been built from clean.

Verification:
- Focused chained, methodology, doc-dependency and changelog tests: 477 passed
  on pandas 2.3.3.
- Chained tests on pandas 3.0.3, NumPy 2.4.5 and SciPy 1.17.1: 139 passed.
- ruff 0.17.1, black 26.10.1 and mypy 2.4.0 pass.
- cdid 1.4.0.0 comparison: eight of nine fixtures pass, with the expected
  mismatch. Both reports were regenerated from this source.
- Tutorial code cells executed.
- Not run: hosted CI, the complete suite, the Python version matrix, the
  native backend, a clean rebuild of the reference image, and a simulation of
  the covariate path under the new policy.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
shawcharles pushed a commit to shawcharles/diff-diff that referenced this pull request Dec 1, 2026
Integrates igerber/diff-diff main at 7723c6d so that PR igerber#887 is current
before review. The merge has no conflicts. Merged instead of rebased to keep
the published PR head ecdd1e0 in the history.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@shawcharles

Copy link
Copy Markdown
Contributor Author

Thanks for the fixed target. This revision implements it, and the branch is merged with main at 7723c6de. The PR description above predates the revision; this comment describes the current head. Nothing here reopens the settled points.

Implemented

  • Identity GMM and the per-pair propensity fit are kept. The per-pair fit is recorded in REGISTRY as a deviation from the paper and from R.
  • Pairs with fewer than 20 observed units in either arm, or control ESS below 20, are excluded. A failed pair logit excludes that pair with a reason and the fit continues.
  • All five API changes: plain-dict cells with the eight keys; effect and skip_reason in the per-cell table; get_aggregation_weights_df(level); epv_threshold with per-cell epv_diagnostics; and groups, time_periods, n_obs, cluster_name, n_clusters.
  • The reference period, free pre-period parameters, identity-weighting variance and clustering are documented as choices the paper leaves open. The pseudocode disposes of all fourteen printed inconsistencies.
  • Tutorial renumbering, the REGISTRY consolidation and the plotter change are left for you, as agreed.

Coverage evidence

On the ten-case sparse grid (2,000 replications per case, seed 20261106) no fit fails, but two cases fall below a literal 0.94 bar: 0.9395 (n=400, 50 treated and 19 controls at the extra date) and 0.9345 (n=4,000, 20 treated and 190 controls). The report's literal acceptance flag is therefore false. I did not change the threshold or the seed.

On the same draws, intervals built from the known variance cover 0.942 and 0.946, so the shortfall from the HC0 variance is about 0.25 and 1.15 percentage points. An independent-seed replay of those two cases gave 0.945 and 0.942. I read this as coverage of about 0.94 at the 20-unit boundary: consistent with your stated bar, but not a literal all-case pass. Your sixteen-design result is cited as your evidence; I could not rerun the six additional designs.

The precision cost remains as you described. In the retained 20/190 case the empirical SD is 0.0940, against about 0.0434 where the thin pairs are excluded.

cdid 1.4.0.0

Eight of nine fixtures match, with maximum covariance discrepancy below 7e-15. The incomplete continuous-covariate fixture still differs, because the per-pair propensity criterion differs from cdid's by design. The comparison image was upgraded in place from the 1.1.0.0 image; the tracked Dockerfile has not been built from clean.

Two choices to confirm

  • Table skip_reason columns use object dtype, so an estimable cell holds a literal None on pandas 3. CallawaySantAnna's table gives NaN there.
  • n_obs counts observed outcomes, so absent-row and explicit-NaN layouts agree. Other estimators report len(data); the two agree unless outcomes are stored as NaN.

Each is a one-line change if you prefer the other behaviour.

Input contract (#925)

This estimator predates docs/input-contract.md, and I have not audited it against every clause. I confirmed two differences that need your ruling:

  • IC-03: a NaN outcome is treated as an unobserved unit-date, which is the estimator's subject. Infinite outcomes are refused.
  • IC-15: never-treated units must be marked 0. +inf is refused.

Boolean outcomes are accepted and converted exactly, as IC-01 requires. The remaining clauses are unchecked.

Not verified

The workflows on this PR are waiting for approval to run, so the Lint Gate has not executed. Locally, on the merged tree, ruff 0.17.1, black 26.10.1 and mypy 2.4.0 pass, and the ChainedDiD tests pass on pandas 2.3.3 and 3.0.3. I have not run the complete suite, the Python version matrix or the native backend. No simulation here covers the covariate path under the new exclusion policy; that rests on the simulations you reported.

@shawcharles
shawcharles marked this pull request as ready for review December 1, 2026 23:07
@shawcharles

Copy link
Copy Markdown
Contributor Author

One addition to my note above. I said no simulation here covered the covariate path under the new exclusion rule. I have since rerun the existing 13-design qualification grid on the current head (2,000 replications per design, seed 20261102, one binary covariate). The report is not in the branch; I can add it if you want it.

  • No fit fails in any design.
  • 34 of 39 targets are identical to the pre-policy run, because no pair is excluded in those designs.
  • In the n=1,000 cohort-dependent design, the control-ESS rule excludes at least one pair in 84 fits and the count rule in one. Each target there rests on one chain of adjacent pairs, so a single exclusion makes it unavailable. The overall ATT is unavailable in 85 of 2,000 fits (4.25%) and ATT(3,4) in 27. In one such fit the excluded pair had 53 treated and 29 control units, with control ESS 18.9.
  • Coverage when the estimate is available is unchanged in that design: 0.939 for the overall ATT and 0.946 for ATT(3,4). The study counts an unavailable estimate as a miss, so its unconditional figures read 0.899 and 0.9335.
  • Four n=1,000 targets remain between 0.930 and 0.937, identical to the earlier run: two in the rotating design and two in the intermittent design with 50 clusters.

I read the cohort-dependent result as the availability cost of the rule you set, not a calibration failure. I am flagging it because the ESS rule binds there with about 30 raw controls and a single binary covariate.

@shawcharles
shawcharles force-pushed the contrib/chained-did-native branch from 613d5bd to f8d80c0 Compare December 3, 2026 17:27
@shawcharles

Copy link
Copy Markdown
Contributor Author

I force-pushed to correct the author email on my two commits (2e7e9606 is now eb8ab51a, and 613d5bd5 is now f8d80c00). Nothing else changed: the files, commit messages and history are identical.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants