-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathresults.py
More file actions
895 lines (791 loc) · 30.4 KB
/
results.py
File metadata and controls
895 lines (791 loc) · 30.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
"""
Results classes for difference-in-differences estimation.
Provides statsmodels-style output with a more Pythonic interface.
"""
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
@dataclass
class DiDResults:
"""
Results from a Difference-in-Differences estimation.
Provides easy access to coefficients, standard errors, confidence intervals,
and summary statistics in a Pythonic way.
Attributes
----------
att : float
Average Treatment effect on the Treated (ATT).
se : float
Standard error of the ATT estimate.
t_stat : float
T-statistic for the ATT estimate.
p_value : float
P-value for the null hypothesis that ATT = 0.
conf_int : tuple[float, float]
Confidence interval for the ATT.
n_obs : int
Number of observations used in estimation.
n_treated : int
Number of treated units/observations.
n_control : int
Number of control units/observations.
"""
att: float
se: float
t_stat: float
p_value: float
conf_int: Tuple[float, float]
n_obs: int
n_treated: int
n_control: int
alpha: float = 0.05
coefficients: Optional[Dict[str, float]] = field(default=None)
vcov: Optional[np.ndarray] = field(default=None)
residuals: Optional[np.ndarray] = field(default=None)
fitted_values: Optional[np.ndarray] = field(default=None)
r_squared: Optional[float] = field(default=None)
# Bootstrap inference fields
inference_method: str = field(default="analytical")
n_bootstrap: Optional[int] = field(default=None)
n_clusters: Optional[int] = field(default=None)
bootstrap_distribution: Optional[np.ndarray] = field(default=None, repr=False)
# Survey design metadata (SurveyMetadata instance from diff_diff.survey)
survey_metadata: Optional[Any] = field(default=None)
def __repr__(self) -> str:
"""Concise string representation."""
return (
f"DiDResults(ATT={self.att:.4f}{self.significance_stars}, "
f"SE={self.se:.4f}, "
f"p={self.p_value:.4f})"
)
def summary(self, alpha: Optional[float] = None) -> str:
"""
Generate a formatted summary of the estimation results.
Parameters
----------
alpha : float, optional
Significance level for confidence intervals. Defaults to the
alpha used during estimation.
Returns
-------
str
Formatted summary table.
"""
alpha = alpha or self.alpha
conf_level = int((1 - alpha) * 100)
lines = [
"=" * 70,
"Difference-in-Differences Estimation Results".center(70),
"=" * 70,
"",
f"{'Observations:':<25} {self.n_obs:>10}",
f"{'Treated:':<25} {self.n_treated:>10}",
f"{'Control:':<25} {self.n_control:>10}",
]
if self.r_squared is not None:
lines.append(f"{'R-squared:':<25} {self.r_squared:>10.4f}")
# Add survey design info
if self.survey_metadata is not None:
sm = self.survey_metadata
lines.extend(
[
"",
"-" * 70,
"Survey Design".center(70),
"-" * 70,
f"{'Weight type:':<25} {sm.weight_type:>10}",
]
)
if sm.n_strata is not None:
lines.append(f"{'Strata:':<25} {sm.n_strata:>10}")
if sm.n_psu is not None:
lines.append(f"{'PSU/Cluster:':<25} {sm.n_psu:>10}")
lines.append(f"{'Effective sample size:':<25} {sm.effective_n:>10.1f}")
lines.append(f"{'Design effect (DEFF):':<25} {sm.design_effect:>10.2f}")
if sm.df_survey is not None:
lines.append(f"{'Survey d.f.:':<25} {sm.df_survey:>10}")
lines.append("-" * 70)
# Add inference method info
if self.inference_method != "analytical":
lines.append(f"{'Inference method:':<25} {self.inference_method:>10}")
if self.n_bootstrap is not None:
lines.append(f"{'Bootstrap replications:':<25} {self.n_bootstrap:>10}")
if self.n_clusters is not None:
lines.append(f"{'Number of clusters:':<25} {self.n_clusters:>10}")
lines.extend(
[
"",
"-" * 70,
f"{'Parameter':<15} {'Estimate':>12} {'Std. Err.':>12} {'t-stat':>10} {'P>|t|':>10} {'':>5}",
"-" * 70,
f"{'ATT':<15} {self.att:>12.4f} {self.se:>12.4f} {self.t_stat:>10.3f} {self.p_value:>10.4f} {self.significance_stars:>5}",
"-" * 70,
"",
f"{conf_level}% Confidence Interval: [{self.conf_int[0]:.4f}, {self.conf_int[1]:.4f}]",
]
)
# Add significance codes
lines.extend(
[
"",
"Signif. codes: '***' 0.001, '**' 0.01, '*' 0.05, '.' 0.1",
"=" * 70,
]
)
return "\n".join(lines)
def print_summary(self, alpha: Optional[float] = None) -> None:
"""Print the summary to stdout."""
print(self.summary(alpha))
def to_dict(self) -> Dict[str, Any]:
"""
Convert results to a dictionary.
Returns
-------
Dict[str, Any]
Dictionary containing all estimation results.
"""
result = {
"att": self.att,
"se": self.se,
"t_stat": self.t_stat,
"p_value": self.p_value,
"conf_int_lower": self.conf_int[0],
"conf_int_upper": self.conf_int[1],
"n_obs": self.n_obs,
"n_treated": self.n_treated,
"n_control": self.n_control,
"r_squared": self.r_squared,
"inference_method": self.inference_method,
}
if self.n_bootstrap is not None:
result["n_bootstrap"] = self.n_bootstrap
if self.n_clusters is not None:
result["n_clusters"] = self.n_clusters
if self.survey_metadata is not None:
sm = self.survey_metadata
result["weight_type"] = sm.weight_type
result["effective_n"] = sm.effective_n
result["design_effect"] = sm.design_effect
result["sum_weights"] = sm.sum_weights
result["n_strata"] = sm.n_strata
result["n_psu"] = sm.n_psu
result["df_survey"] = sm.df_survey
return result
def to_dataframe(self) -> pd.DataFrame:
"""
Convert results to a pandas DataFrame.
Returns
-------
pd.DataFrame
DataFrame with estimation results.
"""
return pd.DataFrame([self.to_dict()])
@property
def is_significant(self) -> bool:
"""Check if the ATT is statistically significant at the alpha level."""
return bool(self.p_value < self.alpha)
@property
def significance_stars(self) -> str:
"""Return significance stars based on p-value."""
return _get_significance_stars(self.p_value)
def _get_significance_stars(p_value: float) -> str:
"""Return significance stars based on p-value.
Returns empty string for NaN p-values (unidentified coefficients from
rank-deficient matrices).
"""
import numpy as np
if np.isnan(p_value):
return ""
if p_value < 0.001:
return "***"
elif p_value < 0.01:
return "**"
elif p_value < 0.05:
return "*"
elif p_value < 0.1:
return "."
return ""
@dataclass
class PeriodEffect:
"""
Treatment effect for a single time period.
Attributes
----------
period : any
The time period identifier.
effect : float
The treatment effect estimate for this period.
se : float
Standard error of the effect estimate.
t_stat : float
T-statistic for the effect estimate.
p_value : float
P-value for the null hypothesis that effect = 0.
conf_int : tuple[float, float]
Confidence interval for the effect.
"""
period: Any
effect: float
se: float
t_stat: float
p_value: float
conf_int: Tuple[float, float]
def __repr__(self) -> str:
"""Concise string representation."""
sig = _get_significance_stars(self.p_value)
return (
f"PeriodEffect(period={self.period}, effect={self.effect:.4f}{sig}, "
f"SE={self.se:.4f}, p={self.p_value:.4f})"
)
@property
def is_significant(self) -> bool:
"""Check if the effect is statistically significant at 0.05 level."""
return bool(self.p_value < 0.05)
@property
def significance_stars(self) -> str:
"""Return significance stars based on p-value."""
return _get_significance_stars(self.p_value)
@dataclass
class MultiPeriodDiDResults:
"""
Results from a Multi-Period Difference-in-Differences estimation.
Provides access to period-specific treatment effects as well as
an aggregate average treatment effect.
Attributes
----------
period_effects : dict[any, PeriodEffect]
Dictionary mapping period identifiers to their PeriodEffect objects.
Contains all estimated period effects (pre and post, excluding
the reference period which is normalized to zero).
avg_att : float
Average Treatment effect on the Treated across post-periods only.
avg_se : float
Standard error of the average ATT.
avg_t_stat : float
T-statistic for the average ATT.
avg_p_value : float
P-value for the null hypothesis that average ATT = 0.
avg_conf_int : tuple[float, float]
Confidence interval for the average ATT.
n_obs : int
Number of observations used in estimation.
n_treated : int
Number of treated units/observations.
n_control : int
Number of control units/observations.
pre_periods : list
List of pre-treatment period identifiers.
post_periods : list
List of post-treatment period identifiers.
reference_period : any, optional
The reference (omitted) period. Its coefficient is zero by
construction and it is excluded from ``period_effects``.
interaction_indices : dict, optional
Mapping from period identifier to column index in the full
variance-covariance matrix. Used internally for sub-VCV
extraction (e.g., by HonestDiD and PreTrendsPower).
"""
period_effects: Dict[Any, PeriodEffect]
avg_att: float
avg_se: float
avg_t_stat: float
avg_p_value: float
avg_conf_int: Tuple[float, float]
n_obs: int
n_treated: int
n_control: int
pre_periods: List[Any]
post_periods: List[Any]
alpha: float = 0.05
coefficients: Optional[Dict[str, float]] = field(default=None)
vcov: Optional[np.ndarray] = field(default=None)
residuals: Optional[np.ndarray] = field(default=None)
fitted_values: Optional[np.ndarray] = field(default=None)
r_squared: Optional[float] = field(default=None)
reference_period: Optional[Any] = field(default=None)
interaction_indices: Optional[Dict[Any, int]] = field(default=None, repr=False)
# Survey design metadata (SurveyMetadata instance from diff_diff.survey)
survey_metadata: Optional[Any] = field(default=None)
def __repr__(self) -> str:
"""Concise string representation."""
sig = _get_significance_stars(self.avg_p_value)
return (
f"MultiPeriodDiDResults(avg_ATT={self.avg_att:.4f}{sig}, "
f"SE={self.avg_se:.4f}, "
f"n_post_periods={len(self.post_periods)})"
)
@property
def pre_period_effects(self) -> Dict[Any, PeriodEffect]:
"""Pre-period effects only (for parallel trends assessment)."""
return {p: pe for p, pe in self.period_effects.items() if p in self.pre_periods}
@property
def post_period_effects(self) -> Dict[Any, PeriodEffect]:
"""Post-period effects only."""
return {p: pe for p, pe in self.period_effects.items() if p in self.post_periods}
def summary(self, alpha: Optional[float] = None) -> str:
"""
Generate a formatted summary of the estimation results.
Parameters
----------
alpha : float, optional
Significance level for confidence intervals. Defaults to the
alpha used during estimation.
Returns
-------
str
Formatted summary table.
"""
alpha = alpha or self.alpha
conf_level = int((1 - alpha) * 100)
lines = [
"=" * 80,
"Multi-Period Difference-in-Differences Estimation Results".center(80),
"=" * 80,
"",
f"{'Observations:':<25} {self.n_obs:>10}",
f"{'Treated observations:':<25} {self.n_treated:>10}",
f"{'Control observations:':<25} {self.n_control:>10}",
f"{'Pre-treatment periods:':<25} {len(self.pre_periods):>10}",
f"{'Post-treatment periods:':<25} {len(self.post_periods):>10}",
]
if self.r_squared is not None:
lines.append(f"{'R-squared:':<25} {self.r_squared:>10.4f}")
# Add survey design info
if self.survey_metadata is not None:
sm = self.survey_metadata
lines.extend(
[
"",
"-" * 80,
"Survey Design".center(80),
"-" * 80,
f"{'Weight type:':<25} {sm.weight_type:>10}",
]
)
if sm.n_strata is not None:
lines.append(f"{'Strata:':<25} {sm.n_strata:>10}")
if sm.n_psu is not None:
lines.append(f"{'PSU/Cluster:':<25} {sm.n_psu:>10}")
lines.append(f"{'Effective sample size:':<25} {sm.effective_n:>10.1f}")
lines.append(f"{'Design effect (DEFF):':<25} {sm.design_effect:>10.2f}")
if sm.df_survey is not None:
lines.append(f"{'Survey d.f.:':<25} {sm.df_survey:>10}")
lines.append("-" * 80)
# Pre-period effects (parallel trends test)
pre_effects = {p: pe for p, pe in self.period_effects.items() if p in self.pre_periods}
if pre_effects:
lines.extend(
[
"",
"-" * 80,
"Pre-Period Effects (Parallel Trends Test)".center(80),
"-" * 80,
f"{'Period':<15} {'Estimate':>12} {'Std. Err.':>12} {'t-stat':>10} {'P>|t|':>10} {'Sig.':>6}",
"-" * 80,
]
)
for period in self.pre_periods:
if period in self.period_effects:
pe = self.period_effects[period]
stars = pe.significance_stars
lines.append(
f"{str(period):<15} {pe.effect:>12.4f} {pe.se:>12.4f} "
f"{pe.t_stat:>10.3f} {pe.p_value:>10.4f} {stars:>6}"
)
# Show reference period
if self.reference_period is not None:
lines.append(
f"[ref: {self.reference_period}]"
f"{'0.0000':>21} {'---':>12} {'---':>10} {'---':>10} {'':>6}"
)
lines.append("-" * 80)
# Post-period treatment effects
lines.extend(
[
"",
"-" * 80,
"Post-Period Treatment Effects".center(80),
"-" * 80,
f"{'Period':<15} {'Estimate':>12} {'Std. Err.':>12} {'t-stat':>10} {'P>|t|':>10} {'Sig.':>6}",
"-" * 80,
]
)
for period in self.post_periods:
pe = self.period_effects[period]
stars = pe.significance_stars
lines.append(
f"{str(period):<15} {pe.effect:>12.4f} {pe.se:>12.4f} "
f"{pe.t_stat:>10.3f} {pe.p_value:>10.4f} {stars:>6}"
)
# Average effect
lines.extend(
[
"-" * 80,
"",
"-" * 80,
"Average Treatment Effect (across post-periods)".center(80),
"-" * 80,
f"{'Parameter':<15} {'Estimate':>12} {'Std. Err.':>12} {'t-stat':>10} {'P>|t|':>10} {'Sig.':>6}",
"-" * 80,
f"{'Avg ATT':<15} {self.avg_att:>12.4f} {self.avg_se:>12.4f} "
f"{self.avg_t_stat:>10.3f} {self.avg_p_value:>10.4f} {self.significance_stars:>6}",
"-" * 80,
"",
f"{conf_level}% Confidence Interval: [{self.avg_conf_int[0]:.4f}, {self.avg_conf_int[1]:.4f}]",
]
)
# Add significance codes
lines.extend(
[
"",
"Signif. codes: '***' 0.001, '**' 0.01, '*' 0.05, '.' 0.1",
"=" * 80,
]
)
return "\n".join(lines)
def print_summary(self, alpha: Optional[float] = None) -> None:
"""Print the summary to stdout."""
print(self.summary(alpha))
def get_effect(self, period) -> PeriodEffect:
"""
Get the treatment effect for a specific period.
Parameters
----------
period : any
The period identifier.
Returns
-------
PeriodEffect
The treatment effect for the specified period.
Raises
------
KeyError
If the period is not found in post-treatment periods.
"""
if period not in self.period_effects:
if hasattr(self, "reference_period") and period == self.reference_period:
raise KeyError(
f"Period '{period}' is the reference period (coefficient "
f"normalized to zero by construction). Its effect is 0.0 with "
f"no associated uncertainty."
)
raise KeyError(
f"Period '{period}' not found. "
f"Available periods: {list(self.period_effects.keys())}"
)
return self.period_effects[period]
def to_dict(self) -> Dict[str, Any]:
"""
Convert results to a dictionary.
Returns
-------
Dict[str, Any]
Dictionary containing all estimation results.
"""
result: Dict[str, Any] = {
"avg_att": self.avg_att,
"avg_se": self.avg_se,
"avg_t_stat": self.avg_t_stat,
"avg_p_value": self.avg_p_value,
"avg_conf_int_lower": self.avg_conf_int[0],
"avg_conf_int_upper": self.avg_conf_int[1],
"n_obs": self.n_obs,
"n_treated": self.n_treated,
"n_control": self.n_control,
"n_pre_periods": len(self.pre_periods),
"n_post_periods": len(self.post_periods),
"r_squared": self.r_squared,
"reference_period": self.reference_period,
}
# Add period-specific effects
for period, pe in self.period_effects.items():
result[f"effect_period_{period}"] = pe.effect
result[f"se_period_{period}"] = pe.se
result[f"pval_period_{period}"] = pe.p_value
# Add survey metadata if present
if self.survey_metadata is not None:
sm = self.survey_metadata
result["weight_type"] = sm.weight_type
result["effective_n"] = sm.effective_n
result["design_effect"] = sm.design_effect
result["sum_weights"] = sm.sum_weights
result["n_strata"] = sm.n_strata
result["n_psu"] = sm.n_psu
result["df_survey"] = sm.df_survey
return result
def to_dataframe(self) -> pd.DataFrame:
"""
Convert period-specific effects to a pandas DataFrame.
Returns
-------
pd.DataFrame
DataFrame with one row per estimated period (pre and post).
"""
rows = []
for period, pe in self.period_effects.items():
rows.append(
{
"period": period,
"effect": pe.effect,
"se": pe.se,
"t_stat": pe.t_stat,
"p_value": pe.p_value,
"conf_int_lower": pe.conf_int[0],
"conf_int_upper": pe.conf_int[1],
"is_significant": pe.is_significant,
"is_post": period in self.post_periods,
}
)
return pd.DataFrame(rows)
@property
def is_significant(self) -> bool:
"""Check if the average ATT is statistically significant at the alpha level."""
return bool(self.avg_p_value < self.alpha)
@property
def significance_stars(self) -> str:
"""Return significance stars for the average ATT based on p-value."""
return _get_significance_stars(self.avg_p_value)
@dataclass
class SyntheticDiDResults:
"""
Results from a Synthetic Difference-in-Differences estimation.
Combines DiD with synthetic control by re-weighting control units to match
pre-treatment trends of treated units.
Attributes
----------
att : float
Average Treatment effect on the Treated (ATT).
se : float
Standard error of the ATT estimate (bootstrap or placebo-based).
t_stat : float
T-statistic for the ATT estimate.
p_value : float
P-value for the null hypothesis that ATT = 0.
conf_int : tuple[float, float]
Confidence interval for the ATT.
n_obs : int
Number of observations used in estimation.
n_treated : int
Number of treated units/observations.
n_control : int
Number of control units/observations.
unit_weights : dict
Dictionary mapping control unit IDs to their synthetic weights.
time_weights : dict
Dictionary mapping pre-treatment periods to their time weights.
pre_periods : list
List of pre-treatment period identifiers.
post_periods : list
List of post-treatment period identifiers.
variance_method : str
Method used for variance estimation: "bootstrap" or "placebo".
"""
att: float
se: float
t_stat: float
p_value: float
conf_int: Tuple[float, float]
n_obs: int
n_treated: int
n_control: int
unit_weights: Dict[Any, float]
time_weights: Dict[Any, float]
pre_periods: List[Any]
post_periods: List[Any]
alpha: float = 0.05
variance_method: str = field(default="placebo")
noise_level: Optional[float] = field(default=None)
zeta_omega: Optional[float] = field(default=None)
zeta_lambda: Optional[float] = field(default=None)
pre_treatment_fit: Optional[float] = field(default=None)
placebo_effects: Optional[np.ndarray] = field(default=None)
n_bootstrap: Optional[int] = field(default=None)
# Survey design metadata (SurveyMetadata instance from diff_diff.survey)
survey_metadata: Optional[Any] = field(default=None)
def __repr__(self) -> str:
"""Concise string representation."""
sig = _get_significance_stars(self.p_value)
return (
f"SyntheticDiDResults(ATT={self.att:.4f}{sig}, "
f"SE={self.se:.4f}, "
f"p={self.p_value:.4f})"
)
def summary(self, alpha: Optional[float] = None) -> str:
"""
Generate a formatted summary of the estimation results.
Parameters
----------
alpha : float, optional
Significance level for confidence intervals. Defaults to the
alpha used during estimation.
Returns
-------
str
Formatted summary table.
"""
alpha = alpha or self.alpha
conf_level = int((1 - alpha) * 100)
lines = [
"=" * 75,
"Synthetic Difference-in-Differences Estimation Results".center(75),
"=" * 75,
"",
f"{'Observations:':<25} {self.n_obs:>10}",
f"{'Treated:':<25} {self.n_treated:>10}",
f"{'Control:':<25} {self.n_control:>10}",
f"{'Pre-treatment periods:':<25} {len(self.pre_periods):>10}",
f"{'Post-treatment periods:':<25} {len(self.post_periods):>10}",
]
if self.zeta_omega is not None:
lines.append(f"{'Zeta (unit weights):':<25} {self.zeta_omega:>10.4f}")
if self.zeta_lambda is not None:
lines.append(f"{'Zeta (time weights):':<25} {self.zeta_lambda:>10.6f}")
if self.noise_level is not None:
lines.append(f"{'Noise level:':<25} {self.noise_level:>10.4f}")
if self.pre_treatment_fit is not None:
lines.append(f"{'Pre-treatment fit (RMSE):':<25} {self.pre_treatment_fit:>10.4f}")
# Variance method info
lines.append(f"{'Variance method:':<25} {self.variance_method:>10}")
if self.variance_method == "bootstrap" and self.n_bootstrap is not None:
lines.append(f"{'Bootstrap replications:':<25} {self.n_bootstrap:>10}")
# Add survey design info
if self.survey_metadata is not None:
sm = self.survey_metadata
lines.extend(
[
"",
"-" * 75,
"Survey Design".center(75),
"-" * 75,
f"{'Weight type:':<25} {sm.weight_type:>10}",
]
)
if sm.n_strata is not None:
lines.append(f"{'Strata:':<25} {sm.n_strata:>10}")
if sm.n_psu is not None:
lines.append(f"{'PSU/Cluster:':<25} {sm.n_psu:>10}")
lines.append(f"{'Effective sample size:':<25} {sm.effective_n:>10.1f}")
lines.append(f"{'Design effect (DEFF):':<25} {sm.design_effect:>10.2f}")
if sm.df_survey is not None:
lines.append(f"{'Survey d.f.:':<25} {sm.df_survey:>10}")
lines.append("-" * 75)
lines.extend(
[
"",
"-" * 75,
f"{'Parameter':<15} {'Estimate':>12} {'Std. Err.':>12} {'t-stat':>10} {'P>|t|':>10} {'':>5}",
"-" * 75,
f"{'ATT':<15} {self.att:>12.4f} {self.se:>12.4f} {self.t_stat:>10.3f} {self.p_value:>10.4f} {self.significance_stars:>5}",
"-" * 75,
"",
f"{conf_level}% Confidence Interval: [{self.conf_int[0]:.4f}, {self.conf_int[1]:.4f}]",
]
)
# Show top unit weights
if self.unit_weights:
sorted_weights = sorted(self.unit_weights.items(), key=lambda x: x[1], reverse=True)
top_n = min(5, len(sorted_weights))
lines.extend(
[
"",
"-" * 75,
"Top Unit Weights (Synthetic Control)".center(75),
"-" * 75,
]
)
for unit, weight in sorted_weights[:top_n]:
if weight > 0.001: # Only show meaningful weights
lines.append(f" Unit {unit}: {weight:.4f}")
# Show how many units have non-trivial weight
n_nonzero = sum(1 for w in self.unit_weights.values() if w > 0.001)
lines.append(f" ({n_nonzero} units with weight > 0.001)")
# Add significance codes
lines.extend(
[
"",
"Signif. codes: '***' 0.001, '**' 0.01, '*' 0.05, '.' 0.1",
"=" * 75,
]
)
return "\n".join(lines)
def print_summary(self, alpha: Optional[float] = None) -> None:
"""Print the summary to stdout."""
print(self.summary(alpha))
def to_dict(self) -> Dict[str, Any]:
"""
Convert results to a dictionary.
Returns
-------
Dict[str, Any]
Dictionary containing all estimation results.
"""
result = {
"att": self.att,
"se": self.se,
"t_stat": self.t_stat,
"p_value": self.p_value,
"conf_int_lower": self.conf_int[0],
"conf_int_upper": self.conf_int[1],
"n_obs": self.n_obs,
"n_treated": self.n_treated,
"n_control": self.n_control,
"n_pre_periods": len(self.pre_periods),
"n_post_periods": len(self.post_periods),
"variance_method": self.variance_method,
"noise_level": self.noise_level,
"zeta_omega": self.zeta_omega,
"zeta_lambda": self.zeta_lambda,
"pre_treatment_fit": self.pre_treatment_fit,
}
if self.n_bootstrap is not None:
result["n_bootstrap"] = self.n_bootstrap
if self.survey_metadata is not None:
sm = self.survey_metadata
result["weight_type"] = sm.weight_type
result["effective_n"] = sm.effective_n
result["design_effect"] = sm.design_effect
result["sum_weights"] = sm.sum_weights
result["n_strata"] = sm.n_strata
result["n_psu"] = sm.n_psu
result["df_survey"] = sm.df_survey
return result
def to_dataframe(self) -> pd.DataFrame:
"""
Convert results to a pandas DataFrame.
Returns
-------
pd.DataFrame
DataFrame with estimation results.
"""
return pd.DataFrame([self.to_dict()])
def get_unit_weights_df(self) -> pd.DataFrame:
"""
Get unit weights as a pandas DataFrame.
Returns
-------
pd.DataFrame
DataFrame with unit IDs and their weights.
"""
return pd.DataFrame(
[{"unit": unit, "weight": weight} for unit, weight in self.unit_weights.items()]
).sort_values("weight", ascending=False)
def get_time_weights_df(self) -> pd.DataFrame:
"""
Get time weights as a pandas DataFrame.
Returns
-------
pd.DataFrame
DataFrame with time periods and their weights.
"""
return pd.DataFrame(
[{"period": period, "weight": weight} for period, weight in self.time_weights.items()]
)
@property
def is_significant(self) -> bool:
"""Check if the ATT is statistically significant at the alpha level."""
return bool(self.p_value < self.alpha)
@property
def significance_stars(self) -> str:
"""Return significance stars based on p-value."""
return _get_significance_stars(self.p_value)