-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathsun_abraham.py
More file actions
2564 lines (2308 loc) · 109 KB
/
Copy pathsun_abraham.py
File metadata and controls
2564 lines (2308 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Sun-Abraham Interaction-Weighted Estimator for staggered DiD.
Implements the estimator from Sun & Abraham (2021), "Estimating dynamic
treatment effects in event studies with heterogeneous treatment effects",
Journal of Econometrics.
This provides an alternative to Callaway-Sant'Anna using a saturated
regression with cohort × relative-time interactions.
"""
import warnings
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Literal,
NamedTuple,
Optional,
Tuple,
Union,
overload,
)
import numpy as np
import pandas as pd
from diff_diff._base import BaseEstimator
from diff_diff.bootstrap_utils import compute_effect_bootstrap_stats
if TYPE_CHECKING:
from diff_diff.survey import ResolvedSurveyDesign, SurveyDesign
from diff_diff.linalg import LinearRegression
from diff_diff.results import _format_survey_block, _get_significance_stars
from diff_diff.results_base import BaseResults, _coverage_pct, _require_fit_alpha
from diff_diff.utils import (
absorbed_fe_cr1_k_increment,
absorbed_fe_rank,
pre_demean_norms,
resolve_tail_df,
safe_inference,
snap_absorbed_regressors,
validate_anticipation,
validate_df_convention,
validate_n_bootstrap,
)
from diff_diff.utils import (
within_transform as _within_transform_util,
)
class _SaturatedFitStats(NamedTuple):
"""Fit-level df ingredients read off the saturated LinearRegression.
Carried out of ``_fit_saturated_regression`` so the aggregate inference
layer can resolve the ``df_convention`` fallback df from the SAME fit the
cells used (the D4 fix: one df source per fit). ``df_residual`` is the
regression's ``df_`` (n_eff − k_effective − absorbed rank);
``n_clusters`` its effective positive-weight cluster count (None on
unclustered fits).
"""
df_residual: Optional[float]
n_clusters: Optional[int]
@dataclass
class SunAbrahamResults(BaseResults):
"""
Results from Sun-Abraham (2021) interaction-weighted estimation.
Attributes
----------
event_study_effects : dict
Dictionary mapping relative time to effect dictionaries with keys:
'effect', 'se', 't_stat', 'p_value', 'conf_int', 'n_groups'.
event_study_df : dict, optional
Per-relative-time inference degrees-of-freedom PROVENANCE: the df
each stored event-study row's ``safe_inference`` actually received.
Under ``vcov_type="hc2_bm"`` this is that event time's own
Bell-McCaffrey contrast DOF; under a survey design it is the design
df (post-drop when replicates were dropped by the refit); it is NaN
where inference was normal-theory or where a non-finite BM DOF made
the row's inference undefined. ``None`` under bootstrap, whose
percentile p-values/CIs never used a df - a narrower clearing rule
than ``event_study_vcov``, which also clears under replicate refits
(whose rows DID use a genuine df).
overall_att : float
Overall average treatment effect (weighted average of post-treatment effects).
overall_se : float
Standard error of overall ATT.
overall_t_stat : float
T-statistic for overall ATT.
overall_p_value : float
P-value for overall ATT.
overall_conf_int : tuple
Confidence interval for overall ATT.
cohort_weights : dict
Dictionary mapping relative time to cohort weight dictionaries.
groups : list
List of treatment cohorts (first treatment periods).
time_periods : list
List of all time periods.
n_obs : int
Total number of observations.
n_treated_units : int
Number of ever-treated units.
n_control_units : int
Number of never-treated units.
alpha : float
Significance level used for confidence intervals.
control_group : str
Type of control group used.
vcov_type : str
Variance-covariance family from the fit-time configuration
(``classical``, ``hc1``, ``hc2``, ``hc2_bm``, or ``conley``). On the
``"conley"`` (spatial-HAC) path, ``conley_lag_cutoff`` and
``cluster_name`` are populated. Note: when a
``survey_design=`` is supplied, the survey-design Taylor Series
Linearization (or replicate-weight refit) variance overrides
this analytical family — the field still records the
configured value but ``survey_metadata`` indicates the survey
path was active. Likewise, on bootstrap fits (``n_bootstrap >
0``) the SE comes from the pairs bootstrap (or Rao-Wu rescaled
bootstrap under stratified / PSU survey designs), not the
analytical family.
"""
event_study_effects: Dict[int, Dict[str, Any]]
overall_att: float
overall_se: float
overall_t_stat: float
overall_p_value: float
overall_conf_int: Tuple[float, float]
cohort_weights: Dict[int, Dict[Any, float]]
groups: List[Any]
time_periods: List[Any]
n_obs: int
n_treated_units: int
n_control_units: int
alpha: float = 0.05
control_group: str = "never_treated"
vcov_type: str = "hc1"
# Anticipation periods (``k``) used at fit time. Persisted so
# downstream diagnostics (``BusinessReport`` / ``DiagnosticReport``
# / ``compute_pretrends_power``) can classify pre-period vs
# anticipation-window coefficients without re-plumbing the kwarg
# through every caller.
anticipation: int = 0
bootstrap_results: Optional["SABootstrapResults"] = field(default=None, repr=False)
cohort_effects: Optional[Dict[Tuple[Any, int], Dict[str, Any]]] = field(
default=None, repr=False
)
# Survey design metadata (SurveyMetadata instance from diff_diff.survey)
survey_metadata: Optional[Any] = field(default=None)
# Full event-study VCV matrix (PR-B 2026-05-17 for PreTrendsPower
# canonical Σ_22 fidelity). Built via W @ vcov_cohort @ W.T where W
# is the |event_times| × n_interactions cohort-aggregation matrix.
# Set to None for bootstrap fits (analytical VCV is invalidated by
# bootstrap SE overrides) and for replicate-weight survey fits
# (analytical vcov_cohort is overridden by replicate refit variance).
# Consumed by ``compute_pretrends_power`` to route SA through the full
# pre-period sub-Σ_22 block. Index keys mirror the relative-time labels
# in ``event_study_vcov_index``.
event_study_vcov: Optional["np.ndarray"] = field(default=None, repr=False)
event_study_vcov_index: Optional[list] = field(default=None, repr=False)
# Conley spatial-HAC metadata (populated only when vcov_type == "conley").
# ``conley_lag_cutoff`` carries the within-unit Bartlett max lag; ``cluster_name``
# records an explicit cluster= column (enables the spatial+cluster product-kernel
# summary label). Both None on non-conley fits.
conley_lag_cutoff: Optional[int] = None
cluster_name: Optional[str] = None
# The normalization reference relative time (e = -1 - anticipation, the
# omitted category of the saturated regression) and whether it was
# GENUINELY OBSERVED in the panel. The reference is excluded from
# event_study_effects either because it is the omitted baseline (observed)
# OR because no cohort has an observation there (unobserved, on a gapped
# grid) - the two are indistinguishable from the estimated keys alone, so
# the unified event-study surface synthesizes the anchor row only when
# reference_observed is True. Defaults are conservative (no synthesis) for
# externally / legacy-constructed results.
reference_period: Optional[int] = None
reference_observed: bool = False
# event_study_df (spec section 5, row M-092): per-event-time df
# PROVENANCE - maps each estimated relative time to the df its stored
# p-value/CI's safe_inference actually received (the per-event
# Bell-McCaffrey contrast df under hc2_bm; the survey design df -
# post-drop under replicate refits - on survey fits; the
# df_convention-resolved fallback on plain analytic fits - FINITE
# residual df under the 3.9 default, G-1 under "cluster", NaN under
# "normal" and on rows whose BM DOF was non-finite, where
# safe_inference's non-finite-df guard yields all-NaN inference). None
# under bootstrap: the stored percentile p/CIs never used a df (note
# this clears the WHOLE channel even when a partial bootstrap override
# leaves some rows analytic - a conservative under-claim, consistent
# with the other producers). Deliberately narrower clearing than
# event_study_vcov above: replicate refits KEEP the df (it genuinely
# governed the recomputed rows) while the vcov clears.
# This block is appended-only so every pre-existing field keeps its
# positional index in the generated __init__ (the constructor signature
# is public API); new fields go BELOW.
event_study_df: Optional[Dict[int, float]] = field(default=None, repr=False)
df_convention: Optional[str] = None
"""The estimator's ``df_convention`` configuration echoed onto the
results ("residual" | "cluster" | "normal"; added 3.9)."""
inference_df: Optional[float] = None
"""The df the stored overall-ATT p-value/CI's ``safe_inference``
actually received: the BM contrast df under hc2_bm, the survey design
df on survey fits, else the ``df_convention``-resolved analytical
fallback (None under "normal" = normal theory). None on bootstrap fits,
whose overall p/CI are percentile-based and never used a df."""
# --- Inference-field aliases (balance/external-adapter compatibility) ---
@property
def att(self) -> float:
return self.overall_att
@property
def se(self) -> float:
return self.overall_se
@property
def conf_int(self) -> Tuple[float, float]:
return self.overall_conf_int
@property
def p_value(self) -> float:
return self.overall_p_value
@property
def t_stat(self) -> float:
return self.overall_t_stat
def __repr__(self) -> str:
"""Concise string representation."""
sig = _get_significance_stars(self.overall_p_value)
n_rel_periods = len(self.event_study_effects)
return (
f"SunAbrahamResults(ATT={self.overall_att:.4f}{sig}, "
f"SE={self.overall_se:.4f}, "
f"n_groups={len(self.groups)}, "
f"n_rel_periods={n_rel_periods})"
)
@property
def coef_var(self) -> float:
"""Coefficient of variation: SE / abs(overall ATT). NaN when ATT is 0 or SE non-finite."""
if not (np.isfinite(self.overall_se) and self.overall_se >= 0):
return np.nan
if not np.isfinite(self.overall_att) or self.overall_att == 0:
return np.nan
return self.overall_se / abs(self.overall_att)
def summary(self, alpha: Optional[float] = None) -> str:
"""
Generate formatted summary of estimation results.
Parameters
----------
alpha : float, optional
Accepted for signature uniformity. The stored intervals were
computed at fit time; a value different from the stored
``alpha`` raises ValueError rather than silently recomputing
or relabeling (bootstrap percentile intervals cannot be
reconstructed from the reported SE). Re-fit at the desired
alpha instead.
Returns
-------
str
Formatted summary.
"""
alpha = _require_fit_alpha(alpha, self.alpha)
conf_level = _coverage_pct(alpha)
lines = [
"=" * 85,
"Sun-Abraham Interaction-Weighted Estimator Results".center(85),
"=" * 85,
"",
f"{'Total observations:':<30} {self.n_obs:>10}",
f"{'Treated units:':<30} {self.n_treated_units:>10}",
f"{'Control units:':<30} {self.n_control_units:>10}",
f"{'Treatment cohorts:':<30} {len(self.groups):>10}",
f"{'Time periods:':<30} {len(self.time_periods):>10}",
f"{'Control group:':<30} {self.control_group:>10}",
"",
]
# Add survey design info
if self.survey_metadata is not None:
sm = self.survey_metadata
lines.extend(_format_survey_block(sm, 85))
# Conley spatial-HAC variance label (rendered only on the conley path;
# a full vcov-family label for all families is a separate follow-up).
if self.vcov_type == "conley":
from diff_diff.results import _format_vcov_label
_vlabel = _format_vcov_label(
self.vcov_type,
cluster_name=self.cluster_name,
n_clusters=None,
n_obs=self.n_obs,
conley_lag_cutoff=self.conley_lag_cutoff,
)
if _vlabel:
lines.extend([f"Std. errors: {_vlabel}", ""])
# Overall ATT
lines.extend(
[
"-" * 85,
"Overall Average Treatment Effect on the Treated".center(85),
"-" * 85,
f"{'Parameter':<15} {'Estimate':>12} {'Std. Err.':>12} "
f"{'t-stat':>10} {'P>|t|':>10} {'Sig.':>6}",
"-" * 85,
f"{'ATT':<15} {self.overall_att:>12.4f} {self.overall_se:>12.4f} "
f"{self.overall_t_stat:>10.3f} {self.overall_p_value:>10.4f} "
f"{_get_significance_stars(self.overall_p_value):>6}",
"-" * 85,
"",
f"{conf_level}% Confidence Interval: "
f"[{self.overall_conf_int[0]:.4f}, {self.overall_conf_int[1]:.4f}]",
]
)
cv = self.coef_var
if np.isfinite(cv):
lines.append(f"{'CV (SE/abs(ATT)):':<25} {cv:>10.4f}")
lines.append("")
# Event study effects
lines.extend(
[
"-" * 85,
"Event Study (Dynamic) Effects".center(85),
"-" * 85,
f"{'Rel. Period':<15} {'Estimate':>12} {'Std. Err.':>12} "
f"{'t-stat':>10} {'P>|t|':>10} {'Sig.':>6}",
"-" * 85,
]
)
for rel_t in sorted(self.event_study_effects.keys()):
eff = self.event_study_effects[rel_t]
sig = _get_significance_stars(eff["p_value"])
lines.append(
f"{rel_t:<15} {eff['effect']:>12.4f} {eff['se']:>12.4f} "
f"{eff['t_stat']:>10.3f} {eff['p_value']:>10.4f} {sig:>6}"
)
lines.extend(["-" * 85, ""])
lines.extend(
[
"Signif. codes: '***' 0.001, '**' 0.01, '*' 0.05, '.' 0.1",
"=" * 85,
]
)
return "\n".join(lines)
def print_summary(self, alpha: Optional[float] = None) -> None:
"""Print summary to stdout."""
print(self.summary(alpha))
def to_dict(self) -> Dict[str, Any]:
"""
Convert headline results to a dictionary.
Returns
-------
Dict[str, Any]
Canonical inference row plus scalar metadata. Detailed
event-study / cohort tables are available via
``to_dataframe(level=...)``.
"""
result = {
"att": self.att,
"se": self.se,
"t_stat": self.t_stat,
"p_value": self.p_value,
"conf_int_lower": self.overall_conf_int[0],
"conf_int_upper": self.overall_conf_int[1],
"n_obs": self.n_obs,
"n_treated_units": self.n_treated_units,
"n_control_units": self.n_control_units,
"control_group": self.control_group,
"anticipation": self.anticipation,
"alpha": self.alpha,
"vcov_type": self.vcov_type,
}
if self.cluster_name is not None:
result["cluster_name"] = self.cluster_name
if self.conley_lag_cutoff is not None:
result["conley_lag_cutoff"] = self.conley_lag_cutoff
if self.df_convention is not None:
result["df_convention"] = self.df_convention
if self.inference_df is not None:
result["inference_df"] = self.inference_df
return result
def to_dataframe(self, level: str = "event_study") -> pd.DataFrame:
"""
Convert results to DataFrame.
Parameters
----------
level : str, default="event_study"
Level of aggregation: "event_study" or "cohort".
Returns
-------
pd.DataFrame
Results as DataFrame.
"""
if level == "event_study":
rows = []
for rel_t, data in sorted(self.event_study_effects.items()):
rows.append(
{
"relative_period": rel_t,
"effect": data["effect"],
"se": data["se"],
"t_stat": data["t_stat"],
"p_value": data["p_value"],
"conf_int_lower": data["conf_int"][0],
"conf_int_upper": data["conf_int"][1],
}
)
return pd.DataFrame(rows)
elif level == "cohort":
if self.cohort_effects is None:
raise ValueError(
"Cohort-level effects not available. "
"They are computed internally but not stored by default."
)
rows = []
for (cohort, rel_t), data in sorted(self.cohort_effects.items()):
rows.append(
{
"cohort": cohort,
"relative_period": rel_t,
"effect": data["effect"],
"se": data["se"],
"weight": data.get("weight", np.nan),
}
)
return pd.DataFrame(rows)
else:
raise ValueError(f"Unknown level: {level}. Use 'event_study' or 'cohort'.")
@property
def is_significant(self) -> bool:
"""Check if overall ATT is significant."""
return bool(self.overall_p_value < self.alpha)
@property
def significance_stars(self) -> str:
"""Significance stars for overall ATT."""
return _get_significance_stars(self.overall_p_value)
@dataclass
class SABootstrapResults:
"""
Results from Sun-Abraham bootstrap inference.
Attributes
----------
n_bootstrap : int
Number of bootstrap iterations.
weight_type : str
Type of bootstrap used (always "pairs" for pairs bootstrap).
alpha : float
Significance level used for confidence intervals.
overall_att_se : float
Bootstrap standard error for overall ATT.
overall_att_ci : Tuple[float, float]
Bootstrap confidence interval for overall ATT.
overall_att_p_value : float
Bootstrap p-value for overall ATT.
event_study_ses : Dict[int, float]
Bootstrap SEs for event study effects.
event_study_cis : Dict[int, Tuple[float, float]]
Bootstrap CIs for event study effects.
event_study_p_values : Dict[int, float]
Bootstrap p-values for event study effects.
bootstrap_distribution : Optional[np.ndarray]
Full bootstrap distribution of overall ATT.
"""
n_bootstrap: int
weight_type: str
alpha: float
overall_att_se: float
overall_att_ci: Tuple[float, float]
overall_att_p_value: float
event_study_ses: Dict[int, float]
event_study_cis: Dict[int, Tuple[float, float]]
event_study_p_values: Dict[int, float]
bootstrap_distribution: Optional[np.ndarray] = field(default=None, repr=False)
class SunAbraham(BaseEstimator):
"""
Sun-Abraham (2021) interaction-weighted estimator for staggered DiD.
This estimator provides event-study coefficients using a saturated
TWFE regression with cohort × relative-time interactions, following
the methodology in Sun & Abraham (2021).
The estimation procedure follows three steps:
1. Run a saturated TWFE regression with cohort × relative-time dummies
2. Compute cohort shares (weights) at each relative time
3. Aggregate cohort-specific effects using interaction weights
This avoids the negative weighting problem of standard TWFE and provides
consistent event-study estimates under treatment effect heterogeneity.
Parameters
----------
control_group : str, default="never_treated"
Which units to use as controls:
- "never_treated": Use only never-treated units (recommended)
- "not_yet_treated": Use never-treated and not-yet-treated units
anticipation : int, default=0
Number of periods before treatment where effects may occur.
Must be a non-negative integer; ``bool`` is rejected.
alpha : float, default=0.05
Significance level for confidence intervals.
cluster : str, optional
Column name for cluster-robust standard errors.
If None, clusters at the unit level by default — UNLESS
``vcov_type`` is explicitly set to ``"hc2"`` or ``"classical"``,
in which case the unit auto-cluster is dropped (both are
one-way families and the linalg validator rejects them with
``cluster_ids``). Use ``vcov_type="hc1"`` (default) or
``vcov_type="hc2_bm"`` for cluster-robust inference; the latter
routes to CR2 Bell-McCaffrey at the cluster level.
n_bootstrap : int, default=0
Number of bootstrap iterations for inference.
If 0, uses analytical cluster-robust standard errors.
seed : int, optional
Random seed for reproducibility.
rank_deficient_action : str, default="warn"
Action when design matrix is rank-deficient (linearly dependent columns):
- "warn": Issue warning and drop linearly dependent columns (default)
- "error": Raise ValueError
- "silent": Drop columns silently without warning
vcov_type : {"classical", "hc1", "hc2", "hc2_bm", "conley"}, default "hc1"
Variance-covariance family for analytical inference. Defaults to
``"hc1"`` (preserves prior behavior bit-equally; SA historically
hard-coded HC1). ``"conley"`` (Conley 1999 spatial-HAC) threads the
``conley_*`` params through the within-transform saturated regression
(``conley_lag_cutoff=0`` = within-period spatial only; ``conley_lag_cutoff>0``
adds the within-unit Bartlett serial term — note ``conley_time`` / ``conley_unit``
are always supplied, so this is the panel-aware path, not pooled cross-sectional);
the unit auto-cluster is dropped (an explicit
``cluster=`` enables the spatial+cluster product kernel) and
``survey_design=`` / ``weights`` / ``n_bootstrap>0`` are rejected.
- ``"classical"``: homoskedastic OLS standard errors. One-way
only (linalg validator rejects ``classical + cluster_ids``);
the unit auto-cluster is dropped when ``classical`` is
explicitly opted into.
- ``"hc1"``: Eicker-Huber-White HC1 finite-sample correction
(default; cluster-robust when ``cluster=`` is set or the unit
auto-cluster fires).
- ``"hc2"``: Eicker-Huber-White HC2 leverage correction. One-way
only; the linalg validator rejects combining ``hc2`` with
clusters. The unit auto-cluster is dropped when ``hc2`` is
explicitly opted into.
- ``"hc2_bm"``: HC2 + Bell-McCaffrey CR2 Satterthwaite DOF for
cluster-robust inference. Routes to CR2-BM at the cluster
level; preserves the auto-cluster default.
When ``vcov_type ∈ {"classical","hc2","hc2_bm"}``, the
saturated regression switches from the within-transform path
to a full-dummy ``[intercept + interactions + covariates +
unit_dummies + time_dummies]`` build. For ``hc2`` and
``hc2_bm``, the Frisch-Waugh-Lovell theorem preserves
coefficients but NOT the hat matrix, so HC2 leverage and BM
Satterthwaite DOF must be computed on the full FE projection.
``classical`` also routes through full-dummy so the ``(n-k)``
finite-sample correction in ``s² × (X'X)^{-1}`` matches R's
``lm()`` interpretation. Empirically matches
``lm(...) + sandwich::vcovHC(type="HC2")`` and
``clubSandwich::vcovCR(..., type="CR2")`` at atol=1e-10.
``"hc1"`` keeps the within-transform path (cluster-robust HC1
does not depend on the hat matrix); empirically close to
``fixest::sunab(cluster=~unit)``. See REGISTRY.md for the
documented HC1 finite-sample-correction deviation.
Survey designs (``survey_design=``) are rejected for
``vcov_type ∈ {"classical","hc2","hc2_bm"}`` because the
survey-design Taylor Series Linearization (or replicate-weight
refit) variance overrides the analytical sandwich family, and
the auto-cluster guard for one-way families would silently
downgrade unit-level PSUs to per-observation PSUs. Use
``vcov_type="hc1"`` (default) for survey designs.
``conley`` (Conley-1999 spatial-HAC) is threaded through the
within-transform saturated regression (pass ``conley_coords`` /
``conley_cutoff_km`` / ``conley_lag_cutoff``); ``survey_design=`` /
``weights`` / ``n_bootstrap>0`` are rejected. See the ``vcov_type``
parameter docs above.
df_convention : {"residual", "cluster", "normal"}, default "residual"
Degrees-of-freedom convention for analytical t/p/CI, applied to BOTH
the per-cohort-cell inference and the aggregated event-study /
overall-ATT inference (one df source per fit). ``"residual"``
(default) uses the saturated regression's residual df — the 3.9 fix:
aggregates previously dropped to normal theory on plain clustered
fits; ``"cluster"`` uses the Stata/fixest cluster df ``G − 1``
(inert under ``vcov_type="conley"``); ``"normal"`` deliberately uses
normal-theory z at the fallback level everywhere (cells included).
Survey/replicate df and hc2_bm Bell-McCaffrey contrast DOF always
take precedence; bootstrap p/CI (``n_bootstrap>0``) are percentile-
based and unaffected. The default flips to ``"cluster"`` at v4.
Attributes
----------
results_ : SunAbrahamResults
Estimation results after calling fit().
is_fitted_ : bool
Whether the model has been fitted.
Examples
--------
Basic usage:
>>> import pandas as pd
>>> from diff_diff import SunAbraham
>>>
>>> # Panel data with staggered treatment
>>> data = pd.DataFrame({
... 'unit': [...],
... 'time': [...],
... 'outcome': [...],
... 'first_treat': [...] # 0 for never-treated
... })
>>>
>>> sa = SunAbraham()
>>> results = sa.fit(data, outcome='outcome', unit='unit',
... time='time', first_treat='first_treat')
>>> results.print_summary()
With covariates:
>>> sa = SunAbraham()
>>> results = sa.fit(data, outcome='outcome', unit='unit',
... time='time', first_treat='first_treat',
... covariates=['age', 'income'])
Notes
-----
The Sun-Abraham estimator uses a saturated regression approach:
Y_it = α_i + λ_t + Σ_g Σ_e [δ_{g,e} × 1(G_i=g) × D_{it}^e] + X'γ + ε_it
where:
- α_i = unit fixed effects
- λ_t = time fixed effects
- G_i = unit i's treatment cohort (first treatment period)
- D_{it}^e = indicator for being e periods from treatment
- δ_{g,e} = cohort-specific effect (CATT) at relative time e
The event-study coefficients are then computed as:
β_e = Σ_g w_{g,e} × δ_{g,e}
where w_{g,e} is the share of cohort g in the treated population at
relative time e (interaction weights).
Compared to Callaway-Sant'Anna:
- SA uses saturated regression; CS uses 2x2 DiD comparisons
- SA can be more efficient when model is correctly specified
- Both are consistent under heterogeneous treatment effects
- Running both provides a useful robustness check
References
----------
Sun, L., & Abraham, S. (2021). Estimating dynamic treatment effects in
event studies with heterogeneous treatment effects. Journal of
Econometrics, 225(2), 175-199.
"""
def __init__(
self,
control_group: str = "never_treated",
anticipation: int = 0,
alpha: float = 0.05,
cluster: Optional[str] = None,
n_bootstrap: int = 0,
seed: Optional[int] = None,
rank_deficient_action: str = "warn",
vcov_type: str = "hc1",
conley_coords: Optional[Tuple[str, str]] = None,
conley_cutoff_km: Optional[float] = None,
conley_metric: str = "haversine",
conley_kernel: str = "bartlett",
conley_lag_cutoff: Optional[int] = None,
df_convention: str = "residual",
):
if control_group not in ["never_treated", "not_yet_treated"]:
raise ValueError(
f"control_group must be 'never_treated' or 'not_yet_treated', "
f"got '{control_group}'"
)
validate_df_convention(df_convention)
if rank_deficient_action not in ["warn", "error", "silent"]:
raise ValueError(
f"rank_deficient_action must be 'warn', 'error', or 'silent', "
f"got '{rank_deficient_action}'"
)
if vcov_type not in ("classical", "hc1", "hc2", "hc2_bm", "conley"):
raise ValueError(
f"vcov_type must be one of "
f"{{'classical','hc1','hc2','hc2_bm','conley'}}; got '{vcov_type}'"
)
self.control_group = control_group
self.anticipation = validate_anticipation(anticipation)
self.alpha = alpha
self.cluster = cluster
validate_n_bootstrap(n_bootstrap)
self.n_bootstrap = n_bootstrap
self.seed = seed
self.rank_deficient_action = rank_deficient_action
self.vcov_type = vcov_type
self.conley_coords = conley_coords
self.conley_cutoff_km = conley_cutoff_km
self.conley_metric = conley_metric
self.conley_kernel = conley_kernel
self.conley_lag_cutoff = conley_lag_cutoff
self.df_convention = df_convention
# Track whether the user explicitly opted out of the "hc1" default.
# The auto-cluster-at-unit default in `fit` is suppressed only when
# the user explicitly opts into a one-way family — currently
# ``vcov_type in {"hc2","classical"}``. Both are rejected by the
# linalg validator when combined with ``cluster_ids``. Leaving the
# auto-cluster on the default "hc1" path preserves backward compat;
# ``hc2_bm`` also keeps the auto-cluster (routes to CR2-BM at unit).
self._vcov_type_explicit = vcov_type != "hc1"
self.is_fitted_ = False
self.results_: Optional[SunAbrahamResults] = None
self._reference_period = -1 # Will be set during fit
def fit(
self,
data: pd.DataFrame,
outcome: str,
unit: str,
time: str,
first_treat: str,
covariates: Optional[List[str]] = None,
survey_design: Optional["SurveyDesign"] = None,
) -> SunAbrahamResults:
"""
Fit the Sun-Abraham estimator using saturated regression.
Parameters
----------
data : pd.DataFrame
Panel data with unit and time identifiers.
outcome : str
Name of outcome variable column.
unit : str
Name of unit identifier column.
time : str
Name of time period column.
first_treat : str
Name of column indicating when unit was first treated.
Use 0 (or np.inf) for never-treated units.
covariates : list, optional
List of covariate column names to include in regression.
survey_design : SurveyDesign, optional
Survey design specification for design-based inference.
Supports weighted estimation and Taylor series linearization
variance with strata, PSU, and FPC.
Returns
-------
SunAbrahamResults
Object containing all estimation results.
Raises
------
ValueError
If required columns are missing or data validation fails.
"""
# Fit-time re-check: __init__ and set_params validate eagerly, so
# this only catches DIRECT attribute mutation (est.anticipation = ...)
# — an out-of-domain value silently changes the ESTIMAND. The
# assignment also re-normalizes a mutated numpy scalar to int.
self.anticipation = validate_anticipation(self.anticipation)
# Validate inputs
required_cols = [outcome, unit, time, first_treat]
if covariates:
required_cols.extend(covariates)
missing = [c for c in required_cols if c not in data.columns]
if missing:
raise ValueError(f"Missing columns: {missing}")
# Validate explicit cluster column upfront. Without this guard, a
# missing `cluster=` column would cascade through cluster_var=None
# and silently downgrade clustered inference to one-way (HC1 →
# heteroskedasticity-only; HC2-BM → singleton CR2-BM). Explicit
# user input must error, not silently weaken the SE convention.
if self.cluster is not None:
if self.cluster not in data.columns:
raise ValueError(
f"cluster column {self.cluster!r} not found in data; "
f"available columns: {list(data.columns)}"
)
# NA cluster labels are silently dropped by the meat-side
# `groupby(cluster_ids)` but counted by `np.unique(cluster_ids)`
# in `n_clusters`, producing malformed cluster-robust SEs. Reject
# explicitly so the user fixes the cluster column rather than
# consuming silently-wrong inference.
if data[self.cluster].isna().any():
n_na = int(data[self.cluster].isna().sum())
raise ValueError(
f"cluster column {self.cluster!r} contains {n_na} "
"NA/NaN values. Cluster labels must be non-missing for "
"all observations to produce well-formed cluster-robust "
"standard errors. Drop or impute the NA rows before fit."
)
# Conley spatial-HAC front-door validation + bootstrap incompatibility.
# The shared validator gates coords/cutoff/unit/lag/cluster columns and
# rejects conley + survey_design (deferred). SA has no `inference=` param,
# so pass the literal "analytical"; the n_bootstrap override is gated
# separately below (the validator only knows about wild_bootstrap).
if self.vcov_type == "conley":
from diff_diff.conley import _validate_conley_estimator_inputs
_validate_conley_estimator_inputs(
estimator_name="SunAbraham",
data=data,
unit=unit,
conley_coords=self.conley_coords,
conley_cutoff_km=self.conley_cutoff_km,
conley_lag_cutoff=self.conley_lag_cutoff,
survey_design=survey_design,
inference="analytical",
cluster=self.cluster,
)
if self.n_bootstrap > 0:
raise ValueError(
"SunAbraham(vcov_type='conley') is incompatible with "
"n_bootstrap > 0: the pairs bootstrap overrides the "
"analytical Conley sandwich. Use n_bootstrap=0 for the "
"analytical Conley SE, or vcov_type='hc1' with the bootstrap."
)
# Resolve survey design if provided
from diff_diff.survey import (
_resolve_effective_cluster,
_resolve_survey_for_fit,
_validate_unit_constant_survey,
)
resolved_survey, survey_weights, survey_weight_type, survey_metadata = (
_resolve_survey_for_fit(survey_design, data, "analytical")
)
# Validate survey columns are constant within units (required for
# unit-level collapse in Rao-Wu bootstrap)
if resolved_survey is not None:
_validate_unit_constant_survey(data, unit, survey_design)
_uses_replicate_sa = resolved_survey is not None and resolved_survey.uses_replicate_variance
if _uses_replicate_sa and self.n_bootstrap > 0:
raise ValueError(
"Cannot use n_bootstrap > 0 with replicate-weight survey designs. "
"Replicate weights provide their own variance estimation."
)
# Survey-design + non-HC1 analytical family reject: survey-design
# Taylor Series Linearization (or replicate-weight refit) variance
# overrides the analytical sandwich family, so the requested
# vcov_type ∈ {classical, hc2, hc2_bm} would either silently downgrade
# unit-as-PSU injection to per-observation PSUs (auto-cluster guard
# drops cluster_var=None before the survey path injects unit as PSU)
# or hit the linalg validator's hc2/classical + cluster_ids reject.
# Explicit reject preserves the "survey TSL overrides analytical"
# contract documented in REGISTRY. Use vcov_type='hc1' (default) for
# survey designs.
if resolved_survey is not None and self.vcov_type in ("classical", "hc2", "hc2_bm"):
raise NotImplementedError(
f"SunAbraham(vcov_type={self.vcov_type!r}) with survey_design "
"is not yet supported: the survey-design TSL (or replicate-"
"weight refit) variance overrides the analytical sandwich, "
"so the requested HC2/HC2-BM/classical family would be "
"silently discarded. Additionally, the auto-cluster guard "
"for explicit one-way families (classical/hc2) would drop "
"the unit auto-cluster before survey-PSU injection, "
"downgrading the panel structure from unit-level to "
"per-observation PSUs. Use vcov_type='hc1' (default) for "
"survey designs; the survey TSL machinery computes the "
"design-aware SE on the within-transform path."
)
# Note: the broader survey reject above (line ~625) already covers
# the replicate-weight + hc2/hc2_bm combo (replicate is a subset of
# survey). The replicate-only reject that previously lived here is
# redundant and was removed; see commit history for the rationale.
# Bootstrap + survey supported via Rao-Wu rescaled bootstrap.
# Determine Rao-Wu eligibility from the *original* survey_design
# (before cluster-as-PSU injection which adds PSU to weights-only designs).
_use_rao_wu = False
if survey_design is not None and resolved_survey is not None:
_has_explicit_strata = getattr(survey_design, "strata", None) is not None
_has_explicit_psu = getattr(survey_design, "psu", None) is not None
_has_explicit_fpc = getattr(survey_design, "fpc", None) is not None
if _has_explicit_strata or _has_explicit_psu or _has_explicit_fpc:
_use_rao_wu = True
# Create working copy
df = data.copy()
# Ensure numeric types
df[time] = pd.to_numeric(df[time])
df[first_treat] = pd.to_numeric(df[first_treat])
# Never-treated indicator (must precede treatment_groups to exclude np.inf)
df["_never_treated"] = (df[first_treat] == 0) | (df[first_treat] == np.inf)
# Normalize np.inf → 0 so all downstream `> 0` checks exclude never-treated
df.loc[df[first_treat] == np.inf, first_treat] = 0
# Identify groups and time periods
time_periods = sorted(df[time].unique())
treatment_groups = sorted([g for g in df[first_treat].unique() if g > 0])
# Get unique units
unit_info = (
df.groupby(unit).agg({first_treat: "first", "_never_treated": "first"}).reset_index()
)
n_treated_units = int((unit_info[first_treat] > 0).sum())
n_control_units = int((unit_info["_never_treated"]).sum())
if n_control_units == 0:
raise ValueError("No never-treated units found. Check 'first_treat' column.")
if len(treatment_groups) == 0:
raise ValueError("No treated units found. Check 'first_treat' column.")
# Compute relative time for each observation (vectorized)
df["_rel_time"] = np.where(df[first_treat] > 0, df[time] - df[first_treat], np.nan)
# Identify the range of relative time periods to estimate
rel_times_by_cohort = {}
for g in treatment_groups:
g_times = df[df[first_treat] == g][time].unique()
rel_times_by_cohort[g] = sorted([t - g for t in g_times])
# Find all relative time values
all_rel_times: set = set()
for g, rel_times in rel_times_by_cohort.items():
all_rel_times.update(rel_times)
all_rel_times_sorted = sorted(all_rel_times)
# Use full range of relative times (no artificial truncation, matches R's fixest::sunab())
min_rel = min(all_rel_times_sorted)
max_rel = max(all_rel_times_sorted)
# Reference period: last pre-treatment period (typically -1)
self._reference_period = -1 - self.anticipation
# Whether that anchor was GENUINELY OBSERVED (vs a gap on an
# unbalanced grid). The unified event-study surface synthesizes the
# reference row only when it was observed.
self._reference_observed = self._reference_period in all_rel_times
# Get relative periods to estimate (excluding reference)
rel_periods_to_estimate = [
e
for e in all_rel_times_sorted
if min_rel <= e <= max_rel and e != self._reference_period
]