-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathestimators.py
More file actions
1501 lines (1309 loc) · 59.4 KB
/
estimators.py
File metadata and controls
1501 lines (1309 loc) · 59.4 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
"""
Difference-in-Differences estimators with sklearn-like API.
This module contains the core DiD estimators:
- DifferenceInDifferences: Basic 2x2 DiD estimator
- MultiPeriodDiD: Event-study style DiD with period-specific treatment effects
Additional estimators are in separate modules:
- TwoWayFixedEffects: See diff_diff.twfe
- SyntheticDiD: See diff_diff.synthetic_did
For backward compatibility, all estimators are re-exported from this module.
"""
import warnings
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from diff_diff.linalg import (
LinearRegression,
_expand_vcov_with_nan,
compute_r_squared,
compute_robust_vcov,
solve_ols,
)
from diff_diff.results import DiDResults, MultiPeriodDiDResults, PeriodEffect
from diff_diff.utils import (
WildBootstrapResults,
demean_by_group,
safe_inference,
validate_binary,
wild_bootstrap_se,
)
class DifferenceInDifferences:
"""
Difference-in-Differences estimator with sklearn-like interface.
Estimates the Average Treatment effect on the Treated (ATT) using
the canonical 2x2 DiD design or panel data with two-way fixed effects.
Parameters
----------
formula : str, optional
R-style formula for the model (e.g., "outcome ~ treated * post").
If provided, overrides column name parameters.
robust : bool, default=True
Whether to use heteroskedasticity-robust standard errors (HC1).
cluster : str, optional
Column name for cluster-robust standard errors.
alpha : float, default=0.05
Significance level for confidence intervals.
inference : str, default="analytical"
Inference method: "analytical" for standard asymptotic inference,
or "wild_bootstrap" for wild cluster bootstrap (recommended when
number of clusters is small, <50).
n_bootstrap : int, default=999
Number of bootstrap replications when inference="wild_bootstrap".
bootstrap_weights : str, default="rademacher"
Type of bootstrap weights: "rademacher" (standard), "webb"
(recommended for <10 clusters), or "mammen" (skewness correction).
seed : int, optional
Random seed for reproducibility when using bootstrap inference.
If None (default), results will vary between runs.
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
Attributes
----------
results_ : DiDResults
Estimation results after calling fit().
is_fitted_ : bool
Whether the model has been fitted.
Examples
--------
Basic usage with a DataFrame:
>>> import pandas as pd
>>> from diff_diff import DifferenceInDifferences
>>>
>>> # Create sample data
>>> 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]
... })
>>>
>>> # Fit the model
>>> did = DifferenceInDifferences()
>>> results = did.fit(data, outcome='outcome', treatment='treated', time='post')
>>>
>>> # View results
>>> print(results.att) # ATT estimate
>>> results.print_summary() # Full summary table
Using formula interface:
>>> did = DifferenceInDifferences()
>>> results = did.fit(data, formula='outcome ~ treated * post')
Notes
-----
The ATT is computed using the standard DiD formula:
ATT = (E[Y|D=1,T=1] - E[Y|D=1,T=0]) - (E[Y|D=0,T=1] - E[Y|D=0,T=0])
Or equivalently via OLS regression:
Y = α + β₁*D + β₂*T + β₃*(D×T) + ε
Where β₃ is the ATT.
"""
def __init__(
self,
robust: bool = True,
cluster: Optional[str] = None,
alpha: float = 0.05,
inference: str = "analytical",
n_bootstrap: int = 999,
bootstrap_weights: str = "rademacher",
seed: Optional[int] = None,
rank_deficient_action: str = "warn",
):
self.robust = robust
self.cluster = cluster
self.alpha = alpha
self.inference = inference
self.n_bootstrap = n_bootstrap
self.bootstrap_weights = bootstrap_weights
self.seed = seed
self.rank_deficient_action = rank_deficient_action
self.is_fitted_ = False
self.results_ = None
self._coefficients = None
self._vcov = None
self._bootstrap_results = None # Store WildBootstrapResults if used
def fit(
self,
data: pd.DataFrame,
outcome: Optional[str] = None,
treatment: Optional[str] = None,
time: Optional[str] = None,
formula: Optional[str] = None,
covariates: Optional[List[str]] = None,
fixed_effects: Optional[List[str]] = None,
absorb: Optional[List[str]] = None,
survey_design=None,
) -> DiDResults:
"""
Fit the Difference-in-Differences model.
Parameters
----------
data : pd.DataFrame
DataFrame containing the outcome, treatment, and time variables.
outcome : str
Name of the outcome variable column.
treatment : str
Name of the treatment group indicator column (0/1).
time : str
Name of the post-treatment period indicator column (0/1).
formula : str, optional
R-style formula (e.g., "outcome ~ treated * post").
If provided, overrides outcome, treatment, and time parameters.
covariates : list, optional
List of covariate column names to include as linear controls.
fixed_effects : list, optional
List of categorical column names to include as fixed effects.
Creates dummy variables for each category (drops first level).
Use for low-dimensional fixed effects (e.g., industry, region).
absorb : list, optional
List of categorical column names for high-dimensional fixed effects.
Uses within-transformation (demeaning) instead of dummy variables.
More efficient for large numbers of categories (e.g., firm, individual).
survey_design : SurveyDesign, optional
Survey design specification for design-based inference. When provided,
uses Taylor Series Linearization for variance estimation and
applies sampling weights to the regression.
Returns
-------
DiDResults
Object containing estimation results.
Raises
------
ValueError
If required parameters are missing or data validation fails.
Examples
--------
Using fixed effects (dummy variables):
>>> did.fit(data, outcome='sales', treatment='treated', time='post',
... fixed_effects=['state', 'industry'])
Using absorbed fixed effects (within-transformation):
>>> did.fit(data, outcome='sales', treatment='treated', time='post',
... absorb=['firm_id'])
"""
# Parse formula if provided
if formula is not None:
outcome, treatment, time, covariates = self._parse_formula(formula, data)
elif outcome is None or treatment is None or time is None:
raise ValueError(
"Must provide either 'formula' or all of 'outcome', 'treatment', and 'time'"
)
# Validate inputs
self._validate_data(data, outcome, treatment, time, covariates)
# Validate binary variables BEFORE any transformations
validate_binary(data[treatment].values, "treatment")
validate_binary(data[time].values, "time")
# Validate fixed effects and absorb columns
if fixed_effects:
for fe in fixed_effects:
if fe not in data.columns:
raise ValueError(f"Fixed effect column '{fe}' not found in data")
if absorb:
for ab in absorb:
if ab not in data.columns:
raise ValueError(f"Absorb column '{ab}' not found in data")
# Resolve survey design if provided
from diff_diff.survey import _resolve_effective_cluster, _resolve_survey_for_fit
resolved_survey, survey_weights, survey_weight_type, survey_metadata = (
_resolve_survey_for_fit(survey_design, data, self.inference)
)
_uses_replicate = (
resolved_survey is not None and resolved_survey.uses_replicate_variance
)
if _uses_replicate and self.inference == "wild_bootstrap":
raise ValueError(
"Cannot use inference='wild_bootstrap' with replicate-weight "
"survey designs. Replicate weights provide their own variance "
"estimation."
)
# Handle absorbed fixed effects (within-transformation)
working_data = data.copy()
absorbed_vars = []
n_absorbed_effects = 0
# Save raw treatment counts before absorb demeaning
n_treated_raw = int(np.sum(data[treatment].values.astype(float)))
n_control_raw = len(data) - n_treated_raw
# Reject multi-absorb with survey weights (single-pass demeaning is
# not the correct weighted FWL projection for N > 1 dimensions)
if absorb and len(absorb) > 1 and survey_weights is not None:
raise ValueError(
f"Multiple absorbed fixed effects (absorb={absorb}) with survey "
"weights is not supported. Single-pass sequential demeaning is not "
"the correct weighted FWL projection for multiple absorbed dimensions. "
"Use absorb with a single variable, or use fixed_effects= instead."
)
if absorb and fixed_effects:
raise ValueError(
"Cannot use both absorb and fixed_effects. "
"The absorb within-transformation does not residualize "
"fixed_effects dummies, violating the FWL theorem. "
"Use absorb alone (for high-dimensional FE) "
"or fixed_effects alone (for low-dimensional FE)."
)
if absorb:
# FWL theorem: demean ALL regressors alongside outcome.
# Regressors collinear with absorbed FE (e.g., treatment after
# absorbing unit FE) will zero out and be handled by rank-deficiency.
working_data["_treat_time"] = working_data[treatment].values.astype(
float
) * working_data[time].values.astype(float)
vars_to_demean = [outcome, treatment, time, "_treat_time"] + (covariates or [])
for ab_var in absorb:
working_data, n_fe = demean_by_group(
working_data,
vars_to_demean,
ab_var,
inplace=True,
weights=survey_weights,
)
n_absorbed_effects += n_fe
absorbed_vars.append(ab_var)
# Extract variables (may be demeaned if absorb was used)
y = working_data[outcome].values.astype(float)
d = working_data[treatment].values.astype(float)
t = working_data[time].values.astype(float)
# Create interaction term
if absorb:
dt = working_data["_treat_time"].values.astype(float)
else:
dt = d * t
# Build design matrix
X = np.column_stack([np.ones(len(y)), d, t, dt])
var_names = ["const", treatment, time, f"{treatment}:{time}"]
# Add covariates if provided
if covariates:
for cov in covariates:
X = np.column_stack([X, working_data[cov].values.astype(float)])
var_names.append(cov)
# Add fixed effects as dummy variables
if fixed_effects:
for fe in fixed_effects:
# Create dummies, drop first category to avoid multicollinearity
# Use working_data to be consistent with absorbed FE if both are used
dummies = pd.get_dummies(working_data[fe], prefix=fe, drop_first=True)
for col in dummies.columns:
X = np.column_stack([X, dummies[col].values.astype(float)])
var_names.append(col)
# Extract ATT index (coefficient on interaction term)
att_idx = 3 # Index of interaction term
att_var_name = f"{treatment}:{time}"
assert var_names[att_idx] == att_var_name, (
f"ATT index mismatch: expected '{att_var_name}' at index {att_idx}, "
f"but found '{var_names[att_idx]}'"
)
# Always use LinearRegression for initial fit (unified code path)
# For wild bootstrap, we don't need cluster SEs from the initial fit
cluster_ids = data[self.cluster].values if self.cluster is not None else None
# When survey PSU is present, it overrides cluster for variance estimation
effective_cluster_ids = _resolve_effective_cluster(
resolved_survey, cluster_ids, self.cluster
)
# Inject cluster as effective PSU for survey variance estimation
if resolved_survey is not None and effective_cluster_ids is not None:
from diff_diff.survey import _inject_cluster_as_psu, compute_survey_metadata
resolved_survey = _inject_cluster_as_psu(resolved_survey, effective_cluster_ids)
if resolved_survey.psu is not None and survey_metadata is not None:
raw_w = (
data[survey_design.weights].values.astype(np.float64)
if survey_design.weights
else np.ones(len(data), dtype=np.float64)
)
survey_metadata = compute_survey_metadata(resolved_survey, raw_w)
# When absorb + replicate: pass survey_design=None to prevent
# LinearRegression from computing replicate vcov on already-demeaned
# data (demeaning depends on weights, so replicate refits must re-demean).
_lr_survey = resolved_survey
if _uses_replicate and absorbed_vars:
_lr_survey = None
reg = LinearRegression(
include_intercept=False, # Intercept already in X
robust=self.robust,
cluster_ids=effective_cluster_ids if self.inference != "wild_bootstrap" else None,
alpha=self.alpha,
rank_deficient_action=self.rank_deficient_action,
weights=survey_weights,
weight_type=survey_weight_type,
survey_design=_lr_survey,
).fit(X, y, df_adjustment=n_absorbed_effects)
coefficients = reg.coefficients_
residuals = reg.residuals_
fitted = reg.fitted_values_
assert coefficients is not None
att = coefficients[att_idx]
# Get inference - replicate absorb override, bootstrap, or analytical
if _uses_replicate and absorbed_vars:
# Estimator-level replicate variance: re-demean + re-solve per replicate
from diff_diff.survey import compute_replicate_refit_variance
from diff_diff.utils import safe_inference
_absorb_list = list(absorbed_vars) # capture for closure
# Handle rank-deficient nuisance: refit only identified columns
_id_mask = ~np.isnan(coefficients)
_id_cols = np.where(_id_mask)[0]
_att_idx_reduced = int(np.searchsorted(_id_cols, att_idx))
def _refit_did_absorb(w_r):
nz = w_r > 0
wd = data[nz].copy()
w_nz = w_r[nz]
wd["_treat_time"] = (
wd[treatment].values.astype(float) * wd[time].values.astype(float)
)
vars_dm = [outcome, treatment, time, "_treat_time"] + (covariates or [])
for ab_var in _absorb_list:
wd, _ = demean_by_group(wd, vars_dm, ab_var, inplace=True, weights=w_nz)
y_r = wd[outcome].values.astype(float)
d_r = wd[treatment].values.astype(float)
t_r = wd[time].values.astype(float)
dt_r = wd["_treat_time"].values.astype(float)
X_r = np.column_stack([np.ones(len(y_r)), d_r, t_r, dt_r])
if covariates:
for cov in covariates:
X_r = np.column_stack([X_r, wd[cov].values.astype(float)])
coef_r, _, _ = solve_ols(
X_r[:, _id_cols], y_r,
weights=w_nz, weight_type=survey_weight_type,
rank_deficient_action="silent", return_vcov=False,
)
return coef_r
vcov_reduced, _n_valid_rep = compute_replicate_refit_variance(
_refit_did_absorb, coefficients[_id_mask], resolved_survey
)
vcov = _expand_vcov_with_nan(vcov_reduced, len(coefficients), _id_cols)
se = float(np.sqrt(max(vcov[att_idx, att_idx], 0.0)))
_df_rep = (
survey_metadata.df_survey
if survey_metadata and survey_metadata.df_survey
else 0 # rank-deficient replicate → NaN inference
)
if _n_valid_rep < resolved_survey.n_replicates:
_df_rep = _n_valid_rep - 1 if _n_valid_rep > 1 else 0
if survey_metadata is not None:
survey_metadata.df_survey = _df_rep if _df_rep > 0 else None
t_stat, p_value, conf_int = safe_inference(
att, se, alpha=self.alpha, df=_df_rep
)
elif self.inference == "wild_bootstrap" and self.cluster is not None:
# Override with wild cluster bootstrap inference
se, p_value, conf_int, t_stat, vcov, _ = self._run_wild_bootstrap_inference(
X, y, residuals, cluster_ids, att_idx
)
else:
# Use analytical inference from LinearRegression
# (handles replicate vcov for no-absorb path automatically)
vcov = reg.vcov_
inference = reg.get_inference(att_idx)
se = inference.se
t_stat = inference.t_stat
p_value = inference.p_value
conf_int = inference.conf_int
r_squared = compute_r_squared(y, residuals)
# Count observations (use raw counts to avoid demeaned values from absorb)
n_treated = n_treated_raw
n_control = n_control_raw
# Create coefficient dictionary
coef_dict = {name: coef for name, coef in zip(var_names, coefficients)}
# Determine inference method and bootstrap info
inference_method = "analytical"
n_bootstrap_used = None
n_clusters_used = None
if self._bootstrap_results is not None:
inference_method = "wild_bootstrap"
n_bootstrap_used = self._bootstrap_results.n_bootstrap
n_clusters_used = self._bootstrap_results.n_clusters
# Store results
self.results_ = DiDResults(
att=att,
se=se,
t_stat=t_stat,
p_value=p_value,
conf_int=conf_int,
n_obs=len(y),
n_treated=n_treated,
n_control=n_control,
alpha=self.alpha,
coefficients=coef_dict,
vcov=vcov,
residuals=residuals,
fitted_values=fitted,
r_squared=r_squared,
inference_method=inference_method,
n_bootstrap=n_bootstrap_used,
n_clusters=n_clusters_used,
survey_metadata=survey_metadata,
)
self._coefficients = coefficients
self._vcov = vcov
self.is_fitted_ = True
return self.results_
def _fit_ols(
self, X: np.ndarray, y: np.ndarray
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, float]:
"""
Fit OLS regression.
This method is kept for backwards compatibility. Internally uses the
unified solve_ols from diff_diff.linalg for optimized computation.
Parameters
----------
X : np.ndarray
Design matrix.
y : np.ndarray
Outcome vector.
Returns
-------
tuple
(coefficients, residuals, fitted_values, r_squared)
"""
# Use unified OLS backend
coefficients, residuals, fitted, _ = solve_ols(X, y, return_fitted=True, return_vcov=False)
r_squared = compute_r_squared(y, residuals)
return coefficients, residuals, fitted, r_squared
def _run_wild_bootstrap_inference(
self,
X: np.ndarray,
y: np.ndarray,
residuals: np.ndarray,
cluster_ids: np.ndarray,
coefficient_index: int,
) -> Tuple[float, float, Tuple[float, float], float, np.ndarray, WildBootstrapResults]:
"""
Run wild cluster bootstrap inference.
Parameters
----------
X : np.ndarray
Design matrix.
y : np.ndarray
Outcome vector.
residuals : np.ndarray
OLS residuals.
cluster_ids : np.ndarray
Cluster identifiers for each observation.
coefficient_index : int
Index of the coefficient to compute inference for.
Returns
-------
tuple
(se, p_value, conf_int, t_stat, vcov, bootstrap_results)
"""
bootstrap_results = wild_bootstrap_se(
X,
y,
residuals,
cluster_ids,
coefficient_index=coefficient_index,
n_bootstrap=self.n_bootstrap,
weight_type=self.bootstrap_weights,
alpha=self.alpha,
seed=self.seed,
return_distribution=False,
)
self._bootstrap_results = bootstrap_results
se = bootstrap_results.se
p_value = bootstrap_results.p_value
conf_int = (bootstrap_results.ci_lower, bootstrap_results.ci_upper)
t_stat = bootstrap_results.t_stat_original
# Also compute vcov for storage (using cluster-robust for consistency)
vcov = compute_robust_vcov(X, residuals, cluster_ids)
return se, p_value, conf_int, t_stat, vcov, bootstrap_results
def _parse_formula(
self, formula: str, data: pd.DataFrame
) -> Tuple[str, str, str, Optional[List[str]]]:
"""
Parse R-style formula.
Supports basic formulas like:
- "outcome ~ treatment * time"
- "outcome ~ treatment + time + treatment:time"
- "outcome ~ treatment * time + covariate1 + covariate2"
Parameters
----------
formula : str
R-style formula string.
data : pd.DataFrame
DataFrame to validate column names against.
Returns
-------
tuple
(outcome, treatment, time, covariates)
"""
# Split into LHS and RHS
if "~" not in formula:
raise ValueError("Formula must contain '~' to separate outcome from predictors")
lhs, rhs = formula.split("~")
outcome = lhs.strip()
# Parse RHS
rhs = rhs.strip()
# Check for interaction term
if "*" in rhs:
# Handle "treatment * time" syntax
parts = rhs.split("*")
if len(parts) != 2:
raise ValueError("Currently only supports single interaction (treatment * time)")
treatment = parts[0].strip()
time = parts[1].strip()
# Check for additional covariates after interaction
if "+" in time:
time_parts = time.split("+")
time = time_parts[0].strip()
covariates = [p.strip() for p in time_parts[1:]]
else:
covariates = None
elif ":" in rhs:
# Handle explicit interaction syntax
terms = [t.strip() for t in rhs.split("+")]
interaction_term = None
main_effects = []
covariates = []
for term in terms:
if ":" in term:
interaction_term = term
else:
main_effects.append(term)
if interaction_term is None:
raise ValueError("Formula must contain an interaction term (treatment:time)")
treatment, time = [t.strip() for t in interaction_term.split(":")]
# Remaining terms after treatment and time are covariates
for term in main_effects:
if term != treatment and term != time:
covariates.append(term)
covariates = covariates if covariates else None
else:
raise ValueError(
"Formula must contain interaction term. "
"Use 'outcome ~ treatment * time' or 'outcome ~ treatment + time + treatment:time'"
)
# Validate columns exist
for col in [outcome, treatment, time]:
if col not in data.columns:
raise ValueError(f"Column '{col}' not found in data")
if covariates:
for cov in covariates:
if cov not in data.columns:
raise ValueError(f"Covariate '{cov}' not found in data")
return outcome, treatment, time, covariates
def _validate_data(
self,
data: pd.DataFrame,
outcome: str,
treatment: str,
time: str,
covariates: Optional[List[str]] = None,
) -> None:
"""Validate input data."""
# Check DataFrame
if not isinstance(data, pd.DataFrame):
raise TypeError("data must be a pandas DataFrame")
# Check required columns exist
required_cols = [outcome, treatment, time]
if covariates:
required_cols.extend(covariates)
missing_cols = [col for col in required_cols if col not in data.columns]
if missing_cols:
raise ValueError(f"Missing columns in data: {missing_cols}")
# Check for missing values
for col in required_cols:
if data[col].isna().any():
raise ValueError(f"Column '{col}' contains missing values")
# Check for sufficient variation
if data[treatment].nunique() < 2:
raise ValueError("Treatment variable must have both 0 and 1 values")
if data[time].nunique() < 2:
raise ValueError("Time variable must have both 0 and 1 values")
def predict(self, data: pd.DataFrame) -> np.ndarray:
"""
Predict outcomes using fitted model.
Parameters
----------
data : pd.DataFrame
DataFrame with same structure as training data.
Returns
-------
np.ndarray
Predicted values.
"""
if not self.is_fitted_:
raise RuntimeError("Model must be fitted before calling predict()")
# This is a placeholder - would need to store column names
# for full implementation
raise NotImplementedError(
"predict() is not yet implemented. "
"Use results_.fitted_values for training data predictions."
)
def get_params(self) -> Dict[str, Any]:
"""
Get estimator parameters (sklearn-compatible).
Returns
-------
Dict[str, Any]
Estimator parameters.
"""
return {
"robust": self.robust,
"cluster": self.cluster,
"alpha": self.alpha,
"inference": self.inference,
"n_bootstrap": self.n_bootstrap,
"bootstrap_weights": self.bootstrap_weights,
"seed": self.seed,
"rank_deficient_action": self.rank_deficient_action,
}
def set_params(self, **params) -> "DifferenceInDifferences":
"""
Set estimator parameters (sklearn-compatible).
Parameters
----------
**params
Estimator parameters.
Returns
-------
self
"""
for key, value in params.items():
if hasattr(self, key):
setattr(self, key, value)
else:
raise ValueError(f"Unknown parameter: {key}")
return self
def summary(self) -> str:
"""
Get summary of estimation results.
Returns
-------
str
Formatted summary.
"""
if not self.is_fitted_:
raise RuntimeError("Model must be fitted before calling summary()")
assert self.results_ is not None
return self.results_.summary()
def print_summary(self) -> None:
"""Print summary to stdout."""
print(self.summary())
class MultiPeriodDiD(DifferenceInDifferences):
"""
Multi-Period Difference-in-Differences estimator.
Extends the standard DiD to handle multiple pre-treatment and
post-treatment time periods, providing period-specific treatment
effects as well as an aggregate average treatment effect.
Parameters
----------
robust : bool, default=True
Whether to use heteroskedasticity-robust standard errors (HC1).
cluster : str, optional
Column name for cluster-robust standard errors.
alpha : float, default=0.05
Significance level for confidence intervals.
Attributes
----------
results_ : MultiPeriodDiDResults
Estimation results after calling fit().
is_fitted_ : bool
Whether the model has been fitted.
Examples
--------
Basic usage with multiple time periods:
>>> import pandas as pd
>>> from diff_diff import MultiPeriodDiD
>>>
>>> # Create sample panel data with 6 time periods
>>> # Periods 0-2 are pre-treatment, periods 3-5 are post-treatment
>>> data = create_panel_data() # Your data
>>>
>>> # Fit the model
>>> did = MultiPeriodDiD()
>>> results = did.fit(
... data,
... outcome='sales',
... treatment='treated',
... time='period',
... post_periods=[3, 4, 5] # Specify which periods are post-treatment
... )
>>>
>>> # View period-specific effects
>>> for period, effect in results.period_effects.items():
... print(f"Period {period}: {effect.effect:.3f} (SE: {effect.se:.3f})")
>>>
>>> # View average treatment effect
>>> print(f"Average ATT: {results.avg_att:.3f}")
Notes
-----
The model estimates:
Y_it = α + β*D_i + Σ_t γ_t*Period_t + Σ_{t≠ref} δ_t*(D_i × 1{t}) + ε_it
Where:
- D_i is the treatment indicator
- Period_t are time period dummies (all non-reference periods)
- D_i × 1{t} are treatment-by-period interactions (all non-reference)
- δ_t are the period-specific treatment effects
- The reference period (default: last pre-period) has δ_ref = 0 by construction
Pre-treatment δ_t test the parallel trends assumption (should be ≈ 0).
Post-treatment δ_t estimate dynamic treatment effects.
The average ATT is computed from post-treatment δ_t only.
"""
def fit( # type: ignore[override]
self,
data: pd.DataFrame,
outcome: str,
treatment: str,
time: str,
post_periods: Optional[List[Any]] = None,
covariates: Optional[List[str]] = None,
fixed_effects: Optional[List[str]] = None,
absorb: Optional[List[str]] = None,
reference_period: Any = None,
unit: Optional[str] = None,
survey_design=None,
) -> MultiPeriodDiDResults:
"""
Fit the Multi-Period Difference-in-Differences model.
Parameters
----------
data : pd.DataFrame
DataFrame containing the outcome, treatment, and time variables.
outcome : str
Name of the outcome variable column.
treatment : str
Name of the treatment group indicator column (0/1). Should be a
time-invariant ever-treated indicator (D_i = 1 for all periods of
treated units). If treatment is time-varying (D_it), pre-period
interaction coefficients will be unidentified.
time : str
Name of the time period column (can have multiple values).
post_periods : list
List of time period values that are post-treatment.
All other periods are treated as pre-treatment.
covariates : list, optional
List of covariate column names to include as linear controls.
fixed_effects : list, optional
List of categorical column names to include as fixed effects.
absorb : list, optional
List of categorical column names for high-dimensional fixed effects.
reference_period : any, optional
The reference (omitted) time period for the period dummies.
Defaults to the last pre-treatment period (e=-1 convention).
unit : str, optional
Name of the unit identifier column. When provided, checks whether
treatment timing varies across units and warns if staggered adoption
is detected (suggests CallawaySantAnna instead). Does NOT affect
standard error computation -- use the ``cluster`` parameter for
cluster-robust SEs.
survey_design : SurveyDesign, optional
Survey design specification for design-based inference. When provided,
uses Taylor Series Linearization for variance estimation and
applies sampling weights to the regression.
Returns
-------
MultiPeriodDiDResults
Object containing period-specific and average treatment effects.
Raises
------
ValueError
If required parameters are missing or data validation fails.
"""
# Fall back to analytical inference if wild bootstrap requested
# (must happen before _resolve_survey_for_fit which rejects bootstrap+survey)
effective_inference = self.inference
if self.inference == "wild_bootstrap":
warnings.warn(
"Wild bootstrap inference is not yet supported for MultiPeriodDiD. "
"Using analytical inference instead.",
UserWarning,
)
effective_inference = "analytical"
# Validate basic inputs
if outcome is None or treatment is None or time is None:
raise ValueError("Must provide 'outcome', 'treatment', and 'time'")
# Validate columns exist
self._validate_data(data, outcome, treatment, time, covariates)
# Validate treatment is binary
validate_binary(data[treatment].values, "treatment")
# Validate unit column and check for staggered adoption
if unit is not None:
if unit not in data.columns:
raise ValueError(f"Unit column '{unit}' not found in data")
# Check for staggered treatment timing and absorbing treatment
unit_time_sorted = data.sort_values([unit, time])
adoption_times = {}
has_reversal = False
for u, group in unit_time_sorted.groupby(unit):
d_vals = group[treatment].values
# Check for treatment reversal (non-absorbing treatment)
if not has_reversal and len(d_vals) > 1 and np.any(np.diff(d_vals) < 0):
warnings.warn(
f"Treatment reversal detected (unit '{u}' transitions from "
f"treated to untreated). MultiPeriodDiD assumes treatment is "
f"an absorbing state (once treated, always treated). "
f"Treatment reversals violate this assumption and may "
f"produce unreliable estimates.",
UserWarning,
stacklevel=2,
)
has_reversal = True
# Only use units with observed 0→1 transition for adoption timing
# (skip units that are always treated — can't determine adoption time)
if 0 in d_vals and 1 in d_vals:
adoption_times[u] = group.loc[group[treatment] == 1, time].iloc[0]
if len(adoption_times) > 0:
unique_adoption = len(set(adoption_times.values()))
if unique_adoption > 1:
warnings.warn(
"Treatment timing varies across units (staggered adoption "
"detected). MultiPeriodDiD assumes simultaneous adoption "
"and may produce biased estimates with staggered treatment. "
"Consider using CallawaySantAnna or SunAbraham instead.",
UserWarning,
stacklevel=2,
)
# Check for time-varying treatment (D_it instead of D_i)
# If any unit has a 0→1 transition, the treatment column is D_it.
# MultiPeriodDiD expects a time-invariant ever-treated indicator.
warnings.warn(
"Treatment indicator varies within units (time-varying "
"treatment detected). MultiPeriodDiD's event-study "
"specification expects a time-invariant ever-treated "
"indicator (D_i = 1 for all periods of eventually-treated "
"units). With time-varying treatment, pre-period "
"interaction coefficients will be unidentified. Consider: "
f"df['ever_treated'] = df.groupby('{unit}')['{treatment}']"
".transform('max')",
UserWarning,
stacklevel=2,
)
# Get all unique time periods