diff-diff 2.3.2__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1322 @@
1
+ """
2
+ Triple Difference (DDD) estimators.
3
+
4
+ Implements the methodology from Ortiz-Villavicencio & Sant'Anna (2025)
5
+ "Better Understanding Triple Differences Estimators" for causal inference
6
+ when treatment requires satisfying two criteria:
7
+ 1. Belonging to a treated group (e.g., a state with a policy)
8
+ 2. Being in an eligible partition (e.g., women, low-income, etc.)
9
+
10
+ This module provides regression adjustment, inverse probability weighting,
11
+ and doubly robust estimators that correctly handle covariate adjustment,
12
+ unlike naive implementations.
13
+
14
+ Current Implementation (v1.3):
15
+ - 2-period DDD (pre/post binary time indicator)
16
+ - Regression adjustment, IPW, and doubly robust estimation
17
+ - Analytical standard errors with robust/cluster options
18
+ - Proper covariate handling
19
+
20
+ Planned for v1.4 (see ROADMAP.md):
21
+ - Staggered adoption support (multiple treatment timing)
22
+ - Event study aggregation for dynamic treatment effects
23
+ - Multiplier bootstrap inference
24
+ - Integration with plot_event_study() visualization
25
+
26
+ Reference:
27
+ Ortiz-Villavicencio, M., & Sant'Anna, P. H. C. (2025).
28
+ Better Understanding Triple Differences Estimators.
29
+ arXiv:2505.09942.
30
+ """
31
+
32
+ import warnings
33
+ from dataclasses import dataclass, field
34
+ from typing import Any, Dict, List, Optional, Tuple
35
+
36
+ import numpy as np
37
+ import pandas as pd
38
+ from scipy import optimize
39
+
40
+ from diff_diff.linalg import LinearRegression, compute_robust_vcov, solve_ols
41
+ from diff_diff.results import _get_significance_stars
42
+ from diff_diff.utils import (
43
+ compute_confidence_interval,
44
+ compute_p_value,
45
+ )
46
+
47
+ # =============================================================================
48
+ # Results Classes
49
+ # =============================================================================
50
+
51
+
52
+ @dataclass
53
+ class TripleDifferenceResults:
54
+ """
55
+ Results from Triple Difference (DDD) estimation.
56
+
57
+ Provides access to the estimated average treatment effect on the treated
58
+ (ATT), standard errors, confidence intervals, and diagnostic information.
59
+
60
+ Attributes
61
+ ----------
62
+ att : float
63
+ Average Treatment effect on the Treated (ATT).
64
+ This is the effect on units in the treated group (G=1) and eligible
65
+ partition (P=1) after treatment (T=1).
66
+ se : float
67
+ Standard error of the ATT estimate.
68
+ t_stat : float
69
+ T-statistic for the ATT estimate.
70
+ p_value : float
71
+ P-value for the null hypothesis that ATT = 0.
72
+ conf_int : tuple[float, float]
73
+ Confidence interval for the ATT.
74
+ n_obs : int
75
+ Total number of observations used in estimation.
76
+ n_treated_eligible : int
77
+ Number of observations in treated group and eligible partition.
78
+ n_treated_ineligible : int
79
+ Number of observations in treated group and ineligible partition.
80
+ n_control_eligible : int
81
+ Number of observations in control group and eligible partition.
82
+ n_control_ineligible : int
83
+ Number of observations in control group and ineligible partition.
84
+ estimation_method : str
85
+ Estimation method used: "dr" (doubly robust), "reg" (regression
86
+ adjustment), or "ipw" (inverse probability weighting).
87
+ alpha : float
88
+ Significance level used for confidence intervals.
89
+ """
90
+
91
+ att: float
92
+ se: float
93
+ t_stat: float
94
+ p_value: float
95
+ conf_int: Tuple[float, float]
96
+ n_obs: int
97
+ n_treated_eligible: int
98
+ n_treated_ineligible: int
99
+ n_control_eligible: int
100
+ n_control_ineligible: int
101
+ estimation_method: str
102
+ alpha: float = 0.05
103
+ # Group means for diagnostics
104
+ group_means: Optional[Dict[str, float]] = field(default=None)
105
+ # Propensity score diagnostics (for IPW/DR)
106
+ pscore_stats: Optional[Dict[str, float]] = field(default=None)
107
+ # Regression diagnostics
108
+ r_squared: Optional[float] = field(default=None)
109
+ # Covariate balance statistics
110
+ covariate_balance: Optional[pd.DataFrame] = field(default=None, repr=False)
111
+ # Inference details
112
+ inference_method: str = field(default="analytical")
113
+ n_bootstrap: Optional[int] = field(default=None)
114
+ n_clusters: Optional[int] = field(default=None)
115
+
116
+ def __repr__(self) -> str:
117
+ """Concise string representation."""
118
+ return (
119
+ f"TripleDifferenceResults(ATT={self.att:.4f}{self.significance_stars}, "
120
+ f"SE={self.se:.4f}, p={self.p_value:.4f}, method={self.estimation_method})"
121
+ )
122
+
123
+ def summary(self, alpha: Optional[float] = None) -> str:
124
+ """
125
+ Generate a formatted summary of the estimation results.
126
+
127
+ Parameters
128
+ ----------
129
+ alpha : float, optional
130
+ Significance level for confidence intervals. Defaults to the
131
+ alpha used during estimation.
132
+
133
+ Returns
134
+ -------
135
+ str
136
+ Formatted summary table.
137
+ """
138
+ alpha = alpha or self.alpha
139
+ conf_level = int((1 - alpha) * 100)
140
+
141
+ lines = [
142
+ "=" * 75,
143
+ "Triple Difference (DDD) Estimation Results".center(75),
144
+ "=" * 75,
145
+ "",
146
+ f"{'Estimation method:':<30} {self.estimation_method:>15}",
147
+ f"{'Total observations:':<30} {self.n_obs:>15}",
148
+ "",
149
+ "Sample Composition by Cell:",
150
+ f" {'Treated group, Eligible:':<28} {self.n_treated_eligible:>15}",
151
+ f" {'Treated group, Ineligible:':<28} {self.n_treated_ineligible:>15}",
152
+ f" {'Control group, Eligible:':<28} {self.n_control_eligible:>15}",
153
+ f" {'Control group, Ineligible:':<28} {self.n_control_ineligible:>15}",
154
+ ]
155
+
156
+ if self.r_squared is not None:
157
+ lines.append(f"{'R-squared:':<30} {self.r_squared:>15.4f}")
158
+
159
+ if self.inference_method != "analytical":
160
+ lines.append(f"{'Inference method:':<30} {self.inference_method:>15}")
161
+ if self.n_bootstrap is not None:
162
+ lines.append(f"{'Bootstrap replications:':<30} {self.n_bootstrap:>15}")
163
+ if self.n_clusters is not None:
164
+ lines.append(f"{'Number of clusters:':<30} {self.n_clusters:>15}")
165
+
166
+ lines.extend([
167
+ "",
168
+ "-" * 75,
169
+ f"{'Parameter':<15} {'Estimate':>12} {'Std. Err.':>12} {'t-stat':>10} {'P>|t|':>10} {'':>5}",
170
+ "-" * 75,
171
+ 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}",
172
+ "-" * 75,
173
+ "",
174
+ f"{conf_level}% Confidence Interval: [{self.conf_int[0]:.4f}, {self.conf_int[1]:.4f}]",
175
+ ])
176
+
177
+ # Show group means if available
178
+ if self.group_means:
179
+ lines.extend([
180
+ "",
181
+ "-" * 75,
182
+ "Cell Means (Y):",
183
+ "-" * 75,
184
+ ])
185
+ for cell, mean in self.group_means.items():
186
+ lines.append(f" {cell:<35} {mean:>12.4f}")
187
+
188
+ # Show propensity score diagnostics if available
189
+ if self.pscore_stats:
190
+ lines.extend([
191
+ "",
192
+ "-" * 75,
193
+ "Propensity Score Diagnostics:",
194
+ "-" * 75,
195
+ ])
196
+ for stat, value in self.pscore_stats.items():
197
+ lines.append(f" {stat:<35} {value:>12.4f}")
198
+
199
+ lines.extend([
200
+ "",
201
+ "Signif. codes: '***' 0.001, '**' 0.01, '*' 0.05, '.' 0.1",
202
+ "=" * 75,
203
+ ])
204
+
205
+ return "\n".join(lines)
206
+
207
+ def print_summary(self, alpha: Optional[float] = None) -> None:
208
+ """Print the summary to stdout."""
209
+ print(self.summary(alpha))
210
+
211
+ def to_dict(self) -> Dict[str, Any]:
212
+ """
213
+ Convert results to a dictionary.
214
+
215
+ Returns
216
+ -------
217
+ Dict[str, Any]
218
+ Dictionary containing all estimation results.
219
+ """
220
+ result = {
221
+ "att": self.att,
222
+ "se": self.se,
223
+ "t_stat": self.t_stat,
224
+ "p_value": self.p_value,
225
+ "conf_int_lower": self.conf_int[0],
226
+ "conf_int_upper": self.conf_int[1],
227
+ "n_obs": self.n_obs,
228
+ "n_treated_eligible": self.n_treated_eligible,
229
+ "n_treated_ineligible": self.n_treated_ineligible,
230
+ "n_control_eligible": self.n_control_eligible,
231
+ "n_control_ineligible": self.n_control_ineligible,
232
+ "estimation_method": self.estimation_method,
233
+ "inference_method": self.inference_method,
234
+ }
235
+ if self.r_squared is not None:
236
+ result["r_squared"] = self.r_squared
237
+ if self.n_bootstrap is not None:
238
+ result["n_bootstrap"] = self.n_bootstrap
239
+ if self.n_clusters is not None:
240
+ result["n_clusters"] = self.n_clusters
241
+ return result
242
+
243
+ def to_dataframe(self) -> pd.DataFrame:
244
+ """
245
+ Convert results to a pandas DataFrame.
246
+
247
+ Returns
248
+ -------
249
+ pd.DataFrame
250
+ DataFrame with estimation results.
251
+ """
252
+ return pd.DataFrame([self.to_dict()])
253
+
254
+ @property
255
+ def is_significant(self) -> bool:
256
+ """Check if the ATT is statistically significant at the alpha level."""
257
+ return bool(self.p_value < self.alpha)
258
+
259
+ @property
260
+ def significance_stars(self) -> str:
261
+ """Return significance stars based on p-value."""
262
+ return _get_significance_stars(self.p_value)
263
+
264
+
265
+ # =============================================================================
266
+ # Helper Functions
267
+ # =============================================================================
268
+
269
+
270
+ def _logistic_regression(
271
+ X: np.ndarray,
272
+ y: np.ndarray,
273
+ max_iter: int = 100,
274
+ tol: float = 1e-6,
275
+ ) -> Tuple[np.ndarray, np.ndarray]:
276
+ """
277
+ Fit logistic regression using scipy optimize.
278
+
279
+ Parameters
280
+ ----------
281
+ X : np.ndarray
282
+ Feature matrix (n_samples, n_features). Intercept added automatically.
283
+ y : np.ndarray
284
+ Binary outcome (0/1).
285
+ max_iter : int
286
+ Maximum iterations.
287
+ tol : float
288
+ Convergence tolerance.
289
+
290
+ Returns
291
+ -------
292
+ beta : np.ndarray
293
+ Fitted coefficients (including intercept).
294
+ probs : np.ndarray
295
+ Predicted probabilities.
296
+ """
297
+ n, p = X.shape
298
+ X_with_intercept = np.column_stack([np.ones(n), X])
299
+
300
+ def neg_log_likelihood(beta: np.ndarray) -> float:
301
+ z = X_with_intercept @ beta
302
+ z = np.clip(z, -500, 500)
303
+ log_lik = np.sum(y * z - np.log(1 + np.exp(z)))
304
+ return -log_lik
305
+
306
+ def gradient(beta: np.ndarray) -> np.ndarray:
307
+ z = X_with_intercept @ beta
308
+ z = np.clip(z, -500, 500)
309
+ probs = 1 / (1 + np.exp(-z))
310
+ return -X_with_intercept.T @ (y - probs)
311
+
312
+ beta_init = np.zeros(p + 1)
313
+
314
+ result = optimize.minimize(
315
+ neg_log_likelihood,
316
+ beta_init,
317
+ method='BFGS',
318
+ jac=gradient,
319
+ options={'maxiter': max_iter, 'gtol': tol}
320
+ )
321
+
322
+ beta = result.x
323
+ z = X_with_intercept @ beta
324
+ z = np.clip(z, -500, 500)
325
+ probs = 1 / (1 + np.exp(-z))
326
+
327
+ return beta, probs
328
+
329
+
330
+ def _linear_regression(
331
+ X: np.ndarray,
332
+ y: np.ndarray,
333
+ rank_deficient_action: str = "warn",
334
+ ) -> Tuple[np.ndarray, np.ndarray, float]:
335
+ """
336
+ Fit OLS regression.
337
+
338
+ Parameters
339
+ ----------
340
+ X : np.ndarray
341
+ Feature matrix (n_samples, n_features). Intercept added automatically.
342
+ y : np.ndarray
343
+ Outcome variable.
344
+ rank_deficient_action : str, default "warn"
345
+ Action when design matrix is rank-deficient:
346
+ - "warn": Issue warning and drop linearly dependent columns (default)
347
+ - "error": Raise ValueError
348
+ - "silent": Drop columns silently without warning
349
+
350
+ Returns
351
+ -------
352
+ beta : np.ndarray
353
+ Fitted coefficients (including intercept).
354
+ fitted : np.ndarray
355
+ Fitted values.
356
+ r_squared : float
357
+ R-squared of the regression.
358
+ """
359
+ n = X.shape[0]
360
+ X_with_intercept = np.column_stack([np.ones(n), X])
361
+
362
+ # Use unified OLS backend
363
+ beta, residuals, fitted, _ = solve_ols(
364
+ X_with_intercept, y, return_fitted=True, return_vcov=False,
365
+ rank_deficient_action=rank_deficient_action,
366
+ )
367
+
368
+ # Compute R-squared
369
+ ss_res = np.sum(residuals**2)
370
+ ss_tot = np.sum((y - np.mean(y)) ** 2)
371
+ r_squared = 1 - (ss_res / ss_tot) if ss_tot > 0 else 0.0
372
+
373
+ return beta, fitted, r_squared
374
+
375
+
376
+ # =============================================================================
377
+ # Main Estimator Class
378
+ # =============================================================================
379
+
380
+
381
+ class TripleDifference:
382
+ """
383
+ Triple Difference (DDD) estimator.
384
+
385
+ Estimates the Average Treatment effect on the Treated (ATT) when treatment
386
+ requires satisfying two criteria: belonging to a treated group AND being
387
+ in an eligible partition of the population.
388
+
389
+ This implementation follows Ortiz-Villavicencio & Sant'Anna (2025), which
390
+ shows that naive DDD implementations (difference of two DiDs, three-way
391
+ fixed effects) are invalid when covariates are needed for identification.
392
+
393
+ Parameters
394
+ ----------
395
+ estimation_method : str, default="dr"
396
+ Estimation method to use:
397
+ - "dr": Doubly robust (recommended). Consistent if either the outcome
398
+ model or propensity score model is correctly specified.
399
+ - "reg": Regression adjustment (outcome regression).
400
+ - "ipw": Inverse probability weighting.
401
+ robust : bool, default=True
402
+ Whether to use heteroskedasticity-robust standard errors (HC1).
403
+ cluster : str, optional
404
+ Column name for cluster-robust standard errors.
405
+ alpha : float, default=0.05
406
+ Significance level for confidence intervals.
407
+ pscore_trim : float, default=0.01
408
+ Trimming threshold for propensity scores. Scores below this value
409
+ or above (1 - pscore_trim) are clipped to avoid extreme weights.
410
+ rank_deficient_action : str, default="warn"
411
+ Action when design matrix is rank-deficient (linearly dependent columns):
412
+ - "warn": Issue warning and drop linearly dependent columns (default)
413
+ - "error": Raise ValueError
414
+ - "silent": Drop columns silently without warning
415
+
416
+ Attributes
417
+ ----------
418
+ results_ : TripleDifferenceResults
419
+ Estimation results after calling fit().
420
+ is_fitted_ : bool
421
+ Whether the model has been fitted.
422
+
423
+ Examples
424
+ --------
425
+ Basic usage with a DataFrame:
426
+
427
+ >>> import pandas as pd
428
+ >>> from diff_diff import TripleDifference
429
+ >>>
430
+ >>> # Data where treatment affects women (partition=1) in states
431
+ >>> # that enacted a policy (group=1)
432
+ >>> data = pd.DataFrame({
433
+ ... 'outcome': [...],
434
+ ... 'group': [1, 1, 0, 0, ...], # 1=policy state, 0=control state
435
+ ... 'partition': [1, 0, 1, 0, ...], # 1=women, 0=men
436
+ ... 'post': [0, 0, 1, 1, ...], # 1=post-treatment period
437
+ ... })
438
+ >>>
439
+ >>> # Fit using doubly robust estimation
440
+ >>> ddd = TripleDifference(estimation_method="dr")
441
+ >>> results = ddd.fit(
442
+ ... data,
443
+ ... outcome='outcome',
444
+ ... group='group',
445
+ ... partition='partition',
446
+ ... time='post'
447
+ ... )
448
+ >>> print(results.att) # ATT estimate
449
+
450
+ With covariates (properly handled unlike naive DDD):
451
+
452
+ >>> results = ddd.fit(
453
+ ... data,
454
+ ... outcome='outcome',
455
+ ... group='group',
456
+ ... partition='partition',
457
+ ... time='post',
458
+ ... covariates=['age', 'income']
459
+ ... )
460
+
461
+ Notes
462
+ -----
463
+ The DDD estimator is appropriate when:
464
+
465
+ 1. Treatment affects only units satisfying BOTH criteria:
466
+ - Belonging to a treated group (G=1), e.g., states with a policy
467
+ - Being in an eligible partition (P=1), e.g., women, low-income
468
+
469
+ 2. The DDD parallel trends assumption holds: the differential trend
470
+ between eligible and ineligible partitions would have been the same
471
+ across treated and control groups, absent treatment.
472
+
473
+ This is weaker than requiring separate parallel trends for two DiDs,
474
+ as biases can cancel out in the differencing.
475
+
476
+ References
477
+ ----------
478
+ .. [1] Ortiz-Villavicencio, M., & Sant'Anna, P. H. C. (2025).
479
+ Better Understanding Triple Differences Estimators.
480
+ arXiv:2505.09942.
481
+
482
+ .. [2] Gruber, J. (1994). The incidence of mandated maternity benefits.
483
+ American Economic Review, 84(3), 622-641.
484
+ """
485
+
486
+ def __init__(
487
+ self,
488
+ estimation_method: str = "dr",
489
+ robust: bool = True,
490
+ cluster: Optional[str] = None,
491
+ alpha: float = 0.05,
492
+ pscore_trim: float = 0.01,
493
+ rank_deficient_action: str = "warn",
494
+ ):
495
+ if estimation_method not in ("dr", "reg", "ipw"):
496
+ raise ValueError(
497
+ f"estimation_method must be 'dr', 'reg', or 'ipw', "
498
+ f"got '{estimation_method}'"
499
+ )
500
+ if rank_deficient_action not in ["warn", "error", "silent"]:
501
+ raise ValueError(
502
+ f"rank_deficient_action must be 'warn', 'error', or 'silent', "
503
+ f"got '{rank_deficient_action}'"
504
+ )
505
+ self.estimation_method = estimation_method
506
+ self.robust = robust
507
+ self.cluster = cluster
508
+ self.alpha = alpha
509
+ self.pscore_trim = pscore_trim
510
+ self.rank_deficient_action = rank_deficient_action
511
+
512
+ self.is_fitted_ = False
513
+ self.results_: Optional[TripleDifferenceResults] = None
514
+
515
+ def fit(
516
+ self,
517
+ data: pd.DataFrame,
518
+ outcome: str,
519
+ group: str,
520
+ partition: str,
521
+ time: str,
522
+ covariates: Optional[List[str]] = None,
523
+ ) -> TripleDifferenceResults:
524
+ """
525
+ Fit the Triple Difference model.
526
+
527
+ Parameters
528
+ ----------
529
+ data : pd.DataFrame
530
+ DataFrame containing all variables.
531
+ outcome : str
532
+ Name of the outcome variable column.
533
+ group : str
534
+ Name of the group indicator column (0/1).
535
+ 1 = treated group (e.g., states that enacted policy).
536
+ 0 = control group.
537
+ partition : str
538
+ Name of the partition/eligibility indicator column (0/1).
539
+ 1 = eligible partition (e.g., women, targeted demographic).
540
+ 0 = ineligible partition.
541
+ time : str
542
+ Name of the time period indicator column (0/1).
543
+ 1 = post-treatment period.
544
+ 0 = pre-treatment period.
545
+ covariates : list of str, optional
546
+ List of covariate column names to adjust for.
547
+ These are properly incorporated using the selected estimation
548
+ method (unlike naive DDD implementations).
549
+
550
+ Returns
551
+ -------
552
+ TripleDifferenceResults
553
+ Object containing estimation results.
554
+
555
+ Raises
556
+ ------
557
+ ValueError
558
+ If required columns are missing or data validation fails.
559
+ """
560
+ # Validate inputs
561
+ self._validate_data(data, outcome, group, partition, time, covariates)
562
+
563
+ # Extract data
564
+ y = data[outcome].values.astype(float)
565
+ G = data[group].values.astype(float)
566
+ P = data[partition].values.astype(float)
567
+ T = data[time].values.astype(float)
568
+
569
+ # Get covariates if specified
570
+ X = None
571
+ if covariates:
572
+ X = data[covariates].values.astype(float)
573
+ if np.any(np.isnan(X)):
574
+ raise ValueError("Covariates contain missing values")
575
+
576
+ # Count observations in each cell
577
+ n_obs = len(y)
578
+ n_treated_eligible = int(np.sum((G == 1) & (P == 1)))
579
+ n_treated_ineligible = int(np.sum((G == 1) & (P == 0)))
580
+ n_control_eligible = int(np.sum((G == 0) & (P == 1)))
581
+ n_control_ineligible = int(np.sum((G == 0) & (P == 0)))
582
+
583
+ # Compute cell means for diagnostics
584
+ group_means = self._compute_cell_means(y, G, P, T)
585
+
586
+ # Estimate ATT based on method
587
+ if self.estimation_method == "reg":
588
+ att, se, r_squared, pscore_stats = self._regression_adjustment(
589
+ y, G, P, T, X
590
+ )
591
+ elif self.estimation_method == "ipw":
592
+ att, se, r_squared, pscore_stats = self._ipw_estimation(
593
+ y, G, P, T, X
594
+ )
595
+ else: # doubly robust
596
+ att, se, r_squared, pscore_stats = self._doubly_robust(
597
+ y, G, P, T, X
598
+ )
599
+
600
+ # Compute inference
601
+ t_stat = att / se if np.isfinite(se) and se > 0 else np.nan
602
+ df = n_obs - 8 # Approximate df (8 cell means)
603
+ if covariates:
604
+ df -= len(covariates)
605
+ df = max(df, 1)
606
+
607
+ p_value = compute_p_value(t_stat, df=df)
608
+ conf_int = compute_confidence_interval(att, se, self.alpha, df=df) if np.isfinite(se) and se > 0 else (np.nan, np.nan)
609
+
610
+ # Get number of clusters if clustering
611
+ n_clusters = None
612
+ if self.cluster is not None:
613
+ n_clusters = data[self.cluster].nunique()
614
+
615
+ # Create results object
616
+ self.results_ = TripleDifferenceResults(
617
+ att=att,
618
+ se=se,
619
+ t_stat=t_stat,
620
+ p_value=p_value,
621
+ conf_int=conf_int,
622
+ n_obs=n_obs,
623
+ n_treated_eligible=n_treated_eligible,
624
+ n_treated_ineligible=n_treated_ineligible,
625
+ n_control_eligible=n_control_eligible,
626
+ n_control_ineligible=n_control_ineligible,
627
+ estimation_method=self.estimation_method,
628
+ alpha=self.alpha,
629
+ group_means=group_means,
630
+ pscore_stats=pscore_stats,
631
+ r_squared=r_squared,
632
+ inference_method="analytical",
633
+ n_clusters=n_clusters,
634
+ )
635
+
636
+ self.is_fitted_ = True
637
+ return self.results_
638
+
639
+ def _validate_data(
640
+ self,
641
+ data: pd.DataFrame,
642
+ outcome: str,
643
+ group: str,
644
+ partition: str,
645
+ time: str,
646
+ covariates: Optional[List[str]] = None,
647
+ ) -> None:
648
+ """Validate input data."""
649
+ if not isinstance(data, pd.DataFrame):
650
+ raise TypeError("data must be a pandas DataFrame")
651
+
652
+ # Check required columns exist
653
+ required_cols = [outcome, group, partition, time]
654
+ if covariates:
655
+ required_cols.extend(covariates)
656
+
657
+ missing_cols = [col for col in required_cols if col not in data.columns]
658
+ if missing_cols:
659
+ raise ValueError(f"Missing columns in data: {missing_cols}")
660
+
661
+ # Check for missing values in required columns
662
+ for col in [outcome, group, partition, time]:
663
+ if data[col].isna().any():
664
+ raise ValueError(f"Column '{col}' contains missing values")
665
+
666
+ # Validate binary variables
667
+ for col, name in [(group, "group"), (partition, "partition"), (time, "time")]:
668
+ unique_vals = set(data[col].unique())
669
+ if not unique_vals.issubset({0, 1, 0.0, 1.0}):
670
+ raise ValueError(
671
+ f"'{name}' column must be binary (0/1), "
672
+ f"got values: {sorted(unique_vals)}"
673
+ )
674
+ if len(unique_vals) < 2:
675
+ raise ValueError(
676
+ f"'{name}' column must have both 0 and 1 values"
677
+ )
678
+
679
+ # Check we have observations in all cells
680
+ G = data[group].values
681
+ P = data[partition].values
682
+ T = data[time].values
683
+
684
+ cells = [
685
+ ((G == 1) & (P == 1) & (T == 0), "treated, eligible, pre"),
686
+ ((G == 1) & (P == 1) & (T == 1), "treated, eligible, post"),
687
+ ((G == 1) & (P == 0) & (T == 0), "treated, ineligible, pre"),
688
+ ((G == 1) & (P == 0) & (T == 1), "treated, ineligible, post"),
689
+ ((G == 0) & (P == 1) & (T == 0), "control, eligible, pre"),
690
+ ((G == 0) & (P == 1) & (T == 1), "control, eligible, post"),
691
+ ((G == 0) & (P == 0) & (T == 0), "control, ineligible, pre"),
692
+ ((G == 0) & (P == 0) & (T == 1), "control, ineligible, post"),
693
+ ]
694
+
695
+ for mask, cell_name in cells:
696
+ if np.sum(mask) == 0:
697
+ raise ValueError(
698
+ f"No observations in cell: {cell_name}. "
699
+ "DDD requires observations in all 8 cells."
700
+ )
701
+
702
+ def _compute_cell_means(
703
+ self,
704
+ y: np.ndarray,
705
+ G: np.ndarray,
706
+ P: np.ndarray,
707
+ T: np.ndarray,
708
+ ) -> Dict[str, float]:
709
+ """Compute mean outcomes for each of the 8 DDD cells."""
710
+ means = {}
711
+ for g_val, g_name in [(1, "Treated"), (0, "Control")]:
712
+ for p_val, p_name in [(1, "Eligible"), (0, "Ineligible")]:
713
+ for t_val, t_name in [(0, "Pre"), (1, "Post")]:
714
+ mask = (G == g_val) & (P == p_val) & (T == t_val)
715
+ cell_name = f"{g_name}, {p_name}, {t_name}"
716
+ means[cell_name] = float(np.mean(y[mask]))
717
+ return means
718
+
719
+ def _regression_adjustment(
720
+ self,
721
+ y: np.ndarray,
722
+ G: np.ndarray,
723
+ P: np.ndarray,
724
+ T: np.ndarray,
725
+ X: Optional[np.ndarray],
726
+ ) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]]]:
727
+ """
728
+ Estimate ATT using regression adjustment.
729
+
730
+ Fits an outcome regression with full interactions and covariates,
731
+ then computes the DDD estimand.
732
+
733
+ With covariates, this properly conditions on X rather than naively
734
+ differencing two DiD estimates.
735
+ """
736
+ n = len(y)
737
+
738
+ # Build design matrix for DDD regression
739
+ # Full specification: Y = α + β_G*G + β_P*P + β_T*T
740
+ # + β_GP*G*P + β_GT*G*T + β_PT*P*T
741
+ # + β_GPT*G*P*T + γ'X + ε
742
+ # The DDD estimate is β_GPT
743
+
744
+ # Create interactions
745
+ GP = G * P
746
+ GT = G * T
747
+ PT = P * T
748
+ GPT = G * P * T
749
+
750
+ # Build design matrix
751
+ design_cols = [np.ones(n), G, P, T, GP, GT, PT, GPT]
752
+ col_names = ["const", "G", "P", "T", "G*P", "G*T", "P*T", "G*P*T"]
753
+
754
+ if X is not None:
755
+ for i in range(X.shape[1]):
756
+ design_cols.append(X[:, i])
757
+ col_names.append(f"X{i}")
758
+
759
+ design_matrix = np.column_stack(design_cols)
760
+
761
+ # Fit OLS using LinearRegression helper
762
+ reg = LinearRegression(
763
+ include_intercept=False, # Intercept already in design_matrix
764
+ robust=self.robust,
765
+ alpha=self.alpha,
766
+ rank_deficient_action=self.rank_deficient_action,
767
+ ).fit(design_matrix, y)
768
+
769
+ # ATT is the coefficient on G*P*T (index 7)
770
+ inference = reg.get_inference(7)
771
+ att = inference.coefficient
772
+ se = inference.se
773
+ r_squared = reg.r_squared()
774
+
775
+ return att, se, r_squared, None
776
+
777
+ def _ipw_estimation(
778
+ self,
779
+ y: np.ndarray,
780
+ G: np.ndarray,
781
+ P: np.ndarray,
782
+ T: np.ndarray,
783
+ X: Optional[np.ndarray],
784
+ ) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]]]:
785
+ """
786
+ Estimate ATT using inverse probability weighting.
787
+
788
+ Estimates propensity scores for cell membership and uses IPW
789
+ to reweight observations for the DDD estimand.
790
+ """
791
+ n = len(y)
792
+
793
+ # For DDD-IPW, we need to estimate probabilities for each cell
794
+ # and use them to construct weighted estimators
795
+
796
+ # Create cell indicators
797
+ # Cell 1: G=1, P=1 (treated, eligible) - "effectively treated"
798
+ # Cell 2: G=1, P=0 (treated, ineligible)
799
+ # Cell 3: G=0, P=1 (control, eligible)
800
+ # Cell 4: G=0, P=0 (control, ineligible)
801
+
802
+ cell_1 = (G == 1) & (P == 1)
803
+ cell_2 = (G == 1) & (P == 0)
804
+ cell_3 = (G == 0) & (P == 1)
805
+ cell_4 = (G == 0) & (P == 0)
806
+
807
+ if X is not None and X.shape[1] > 0:
808
+ # Estimate multinomial propensity scores
809
+ # For simplicity, we estimate binary propensity scores for each cell
810
+ # P(G=1|X) and P(P=1|X,G)
811
+
812
+ # Propensity for being in treated group
813
+ try:
814
+ _, p_G = _logistic_regression(X, G)
815
+ except Exception:
816
+ warnings.warn(
817
+ "Propensity score estimation for G failed. "
818
+ "Using unconditional probabilities.",
819
+ UserWarning,
820
+ stacklevel=3,
821
+ )
822
+ p_G = np.full(n, np.mean(G))
823
+
824
+ # Propensity for being in eligible partition (conditional on X)
825
+ try:
826
+ _, p_P = _logistic_regression(X, P)
827
+ except Exception:
828
+ warnings.warn(
829
+ "Propensity score estimation for P failed. "
830
+ "Using unconditional probabilities.",
831
+ UserWarning,
832
+ stacklevel=3,
833
+ )
834
+ p_P = np.full(n, np.mean(P))
835
+
836
+ # Clip propensity scores
837
+ p_G = np.clip(p_G, self.pscore_trim, 1 - self.pscore_trim)
838
+ p_P = np.clip(p_P, self.pscore_trim, 1 - self.pscore_trim)
839
+
840
+ # Cell probabilities (assuming independence conditional on X)
841
+ p_cell_1 = p_G * p_P # P(G=1, P=1|X)
842
+ p_cell_2 = p_G * (1 - p_P) # P(G=1, P=0|X)
843
+ p_cell_3 = (1 - p_G) * p_P # P(G=0, P=1|X)
844
+ p_cell_4 = (1 - p_G) * (1 - p_P) # P(G=0, P=0|X)
845
+
846
+ pscore_stats = {
847
+ "P(G=1) mean": float(np.mean(p_G)),
848
+ "P(G=1) std": float(np.std(p_G)),
849
+ "P(P=1) mean": float(np.mean(p_P)),
850
+ "P(P=1) std": float(np.std(p_P)),
851
+ }
852
+ else:
853
+ # Unconditional probabilities
854
+ p_cell_1 = np.full(n, np.mean(cell_1))
855
+ p_cell_2 = np.full(n, np.mean(cell_2))
856
+ p_cell_3 = np.full(n, np.mean(cell_3))
857
+ p_cell_4 = np.full(n, np.mean(cell_4))
858
+ pscore_stats = None
859
+
860
+ # Clip cell probabilities
861
+ p_cell_1 = np.clip(p_cell_1, self.pscore_trim, 1 - self.pscore_trim)
862
+ p_cell_2 = np.clip(p_cell_2, self.pscore_trim, 1 - self.pscore_trim)
863
+ p_cell_3 = np.clip(p_cell_3, self.pscore_trim, 1 - self.pscore_trim)
864
+ p_cell_4 = np.clip(p_cell_4, self.pscore_trim, 1 - self.pscore_trim)
865
+
866
+ # IPW estimator for DDD
867
+ # The DDD-IPW estimator reweights each cell to have the same
868
+ # covariate distribution as the effectively treated (G=1, P=1)
869
+
870
+ # Pre-period means
871
+ pre_mask = T == 0
872
+ post_mask = T == 1
873
+
874
+ def weighted_mean(y_vals, weights):
875
+ """Compute weighted mean, handling edge cases."""
876
+ w_sum = np.sum(weights)
877
+ if w_sum <= 0:
878
+ return 0.0
879
+ return np.sum(y_vals * weights) / w_sum
880
+
881
+ # Cell 1 (G=1, P=1): weight = 1 (reference)
882
+ w1_pre = cell_1 & pre_mask
883
+ w1_post = cell_1 & post_mask
884
+ y_11_pre = np.mean(y[w1_pre]) if np.sum(w1_pre) > 0 else 0
885
+ y_11_post = np.mean(y[w1_post]) if np.sum(w1_post) > 0 else 0
886
+
887
+ # Cell 2 (G=1, P=0): reweight to match X-distribution of cell 1
888
+ w2_pre = (cell_2 & pre_mask).astype(float) * (p_cell_1 / p_cell_2)
889
+ w2_post = (cell_2 & post_mask).astype(float) * (p_cell_1 / p_cell_2)
890
+ y_10_pre = weighted_mean(y, w2_pre)
891
+ y_10_post = weighted_mean(y, w2_post)
892
+
893
+ # Cell 3 (G=0, P=1): reweight to match X-distribution of cell 1
894
+ w3_pre = (cell_3 & pre_mask).astype(float) * (p_cell_1 / p_cell_3)
895
+ w3_post = (cell_3 & post_mask).astype(float) * (p_cell_1 / p_cell_3)
896
+ y_01_pre = weighted_mean(y, w3_pre)
897
+ y_01_post = weighted_mean(y, w3_post)
898
+
899
+ # Cell 4 (G=0, P=0): reweight to match X-distribution of cell 1
900
+ w4_pre = (cell_4 & pre_mask).astype(float) * (p_cell_1 / p_cell_4)
901
+ w4_post = (cell_4 & post_mask).astype(float) * (p_cell_1 / p_cell_4)
902
+ y_00_pre = weighted_mean(y, w4_pre)
903
+ y_00_post = weighted_mean(y, w4_post)
904
+
905
+ # DDD estimate
906
+ att = (
907
+ (y_11_post - y_11_pre)
908
+ - (y_10_post - y_10_pre)
909
+ - (y_01_post - y_01_pre)
910
+ + (y_00_post - y_00_pre)
911
+ )
912
+
913
+ # Standard error (approximate, using delta method)
914
+ # For simplicity, use influence function approach
915
+ se = self._compute_ipw_se(
916
+ y, G, P, T, cell_1, cell_2, cell_3, cell_4,
917
+ p_cell_1, p_cell_2, p_cell_3, p_cell_4, att
918
+ )
919
+
920
+ return att, se, None, pscore_stats
921
+
922
+ def _doubly_robust(
923
+ self,
924
+ y: np.ndarray,
925
+ G: np.ndarray,
926
+ P: np.ndarray,
927
+ T: np.ndarray,
928
+ X: Optional[np.ndarray],
929
+ ) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]]]:
930
+ """
931
+ Estimate ATT using doubly robust estimation.
932
+
933
+ Combines outcome regression and IPW for robustness:
934
+ consistent if either the outcome model or propensity score
935
+ model is correctly specified.
936
+ """
937
+ n = len(y)
938
+
939
+ # Cell indicators
940
+ cell_1 = (G == 1) & (P == 1)
941
+ cell_2 = (G == 1) & (P == 0)
942
+ cell_3 = (G == 0) & (P == 1)
943
+ cell_4 = (G == 0) & (P == 0)
944
+
945
+ # Step 1: Outcome regression for each cell-time combination
946
+ # Predict E[Y|X,T] for each cell
947
+ if X is not None and X.shape[1] > 0:
948
+ # Fit outcome models for each cell
949
+ mu_fitted = np.zeros(n)
950
+
951
+ for cell_mask, cell_name in [
952
+ (cell_1, "cell_1"), (cell_2, "cell_2"),
953
+ (cell_3, "cell_3"), (cell_4, "cell_4")
954
+ ]:
955
+ for t_val in [0, 1]:
956
+ mask = cell_mask & (T == t_val)
957
+ if np.sum(mask) > 1:
958
+ X_cell = np.column_stack([X[mask], T[mask]])
959
+ try:
960
+ _, fitted, _ = _linear_regression(
961
+ X_cell, y[mask],
962
+ rank_deficient_action=self.rank_deficient_action,
963
+ )
964
+ mu_fitted[mask] = fitted
965
+ except Exception:
966
+ mu_fitted[mask] = np.mean(y[mask])
967
+ elif np.sum(mask) == 1:
968
+ mu_fitted[mask] = y[mask]
969
+
970
+ # Propensity scores
971
+ try:
972
+ _, p_G = _logistic_regression(X, G)
973
+ except Exception:
974
+ p_G = np.full(n, np.mean(G))
975
+
976
+ try:
977
+ _, p_P = _logistic_regression(X, P)
978
+ except Exception:
979
+ p_P = np.full(n, np.mean(P))
980
+
981
+ p_G = np.clip(p_G, self.pscore_trim, 1 - self.pscore_trim)
982
+ p_P = np.clip(p_P, self.pscore_trim, 1 - self.pscore_trim)
983
+
984
+ p_cell_1 = p_G * p_P
985
+ p_cell_2 = p_G * (1 - p_P)
986
+ p_cell_3 = (1 - p_G) * p_P
987
+ p_cell_4 = (1 - p_G) * (1 - p_P)
988
+
989
+ pscore_stats = {
990
+ "P(G=1) mean": float(np.mean(p_G)),
991
+ "P(G=1) std": float(np.std(p_G)),
992
+ "P(P=1) mean": float(np.mean(p_P)),
993
+ "P(P=1) std": float(np.std(p_P)),
994
+ }
995
+ else:
996
+ # No covariates: use cell means as predictions
997
+ mu_fitted = np.zeros(n)
998
+ for cell_mask in [cell_1, cell_2, cell_3, cell_4]:
999
+ for t_val in [0, 1]:
1000
+ mask = cell_mask & (T == t_val)
1001
+ if np.sum(mask) > 0:
1002
+ mu_fitted[mask] = np.mean(y[mask])
1003
+
1004
+ # Unconditional probabilities
1005
+ p_cell_1 = np.full(n, np.mean(cell_1))
1006
+ p_cell_2 = np.full(n, np.mean(cell_2))
1007
+ p_cell_3 = np.full(n, np.mean(cell_3))
1008
+ p_cell_4 = np.full(n, np.mean(cell_4))
1009
+ pscore_stats = None
1010
+
1011
+ # Clip cell probabilities
1012
+ p_cell_1 = np.clip(p_cell_1, self.pscore_trim, 1 - self.pscore_trim)
1013
+ p_cell_2 = np.clip(p_cell_2, self.pscore_trim, 1 - self.pscore_trim)
1014
+ p_cell_3 = np.clip(p_cell_3, self.pscore_trim, 1 - self.pscore_trim)
1015
+ p_cell_4 = np.clip(p_cell_4, self.pscore_trim, 1 - self.pscore_trim)
1016
+
1017
+ # Step 2: Doubly robust estimator
1018
+ # For each cell, compute the augmented IPW term:
1019
+ # (Y - mu(X)) * weight + mu(X)
1020
+
1021
+ pre_mask = T == 0
1022
+ post_mask = T == 1
1023
+
1024
+ # Influence function components for each observation
1025
+ n_1 = np.sum(cell_1)
1026
+ p_ref = n_1 / n
1027
+
1028
+ # Cell 1 (G=1, P=1) - effectively treated
1029
+ inf_11 = np.zeros(n)
1030
+ inf_11[cell_1] = (y[cell_1] - mu_fitted[cell_1]) / p_ref
1031
+ # Add outcome model contribution
1032
+ inf_11 += mu_fitted * cell_1.astype(float) / p_ref
1033
+
1034
+ # Cell 2 (G=1, P=0)
1035
+ w_10 = cell_2.astype(float) * (p_cell_1 / p_cell_2)
1036
+ inf_10 = w_10 * (y - mu_fitted) / p_ref
1037
+ # Add outcome model contribution for cell 2 (vectorized)
1038
+ inf_10[cell_2] += mu_fitted[cell_2] * (p_cell_1[cell_2] / p_cell_2[cell_2]) / p_ref
1039
+
1040
+ # Cell 3 (G=0, P=1)
1041
+ w_01 = cell_3.astype(float) * (p_cell_1 / p_cell_3)
1042
+ inf_01 = w_01 * (y - mu_fitted) / p_ref
1043
+ # Add outcome model contribution for cell 3 (vectorized)
1044
+ inf_01[cell_3] += mu_fitted[cell_3] * (p_cell_1[cell_3] / p_cell_3[cell_3]) / p_ref
1045
+
1046
+ # Cell 4 (G=0, P=0)
1047
+ w_00 = cell_4.astype(float) * (p_cell_1 / p_cell_4)
1048
+ inf_00 = w_00 * (y - mu_fitted) / p_ref
1049
+ # Add outcome model contribution for cell 4 (vectorized)
1050
+ inf_00[cell_4] += mu_fitted[cell_4] * (p_cell_1[cell_4] / p_cell_4[cell_4]) / p_ref
1051
+
1052
+ # Compute cell-time means using DR formula
1053
+ def dr_mean(inf_vals, t_mask):
1054
+ return np.mean(inf_vals[t_mask])
1055
+
1056
+ y_11_pre = dr_mean(inf_11, pre_mask)
1057
+ y_11_post = dr_mean(inf_11, post_mask)
1058
+ y_10_pre = dr_mean(inf_10, pre_mask)
1059
+ y_10_post = dr_mean(inf_10, post_mask)
1060
+ y_01_pre = dr_mean(inf_01, pre_mask)
1061
+ y_01_post = dr_mean(inf_01, post_mask)
1062
+ y_00_pre = dr_mean(inf_00, pre_mask)
1063
+ y_00_post = dr_mean(inf_00, post_mask)
1064
+
1065
+ # DDD estimate
1066
+ att = (
1067
+ (y_11_post - y_11_pre)
1068
+ - (y_10_post - y_10_pre)
1069
+ - (y_01_post - y_01_pre)
1070
+ + (y_00_post - y_00_pre)
1071
+ )
1072
+
1073
+ # Standard error computation
1074
+ # Use the simpler variance formula for the DDD estimator
1075
+ # Var(DDD) ≈ sum of variances of cell means / cell_sizes
1076
+
1077
+ # Compute variances within each cell-time combination
1078
+ def cell_var(cell_mask, t_mask, y_vals):
1079
+ mask = cell_mask & t_mask
1080
+ if np.sum(mask) > 1:
1081
+ return np.var(y_vals[mask], ddof=1), np.sum(mask)
1082
+ return 0.0, max(1, np.sum(mask))
1083
+
1084
+ # Variance components for each of the 8 cells
1085
+ var_components = []
1086
+ for cell_mask in [cell_1, cell_2, cell_3, cell_4]:
1087
+ for t_mask in [pre_mask, post_mask]:
1088
+ v, n_cell = cell_var(cell_mask, t_mask, y)
1089
+ if n_cell > 0:
1090
+ var_components.append(v / n_cell)
1091
+
1092
+ # Total variance is sum of components (assuming independence)
1093
+ total_var = sum(var_components)
1094
+ se = np.sqrt(total_var)
1095
+
1096
+ # R-squared from outcome regression
1097
+ if X is not None:
1098
+ ss_res = np.sum((y - mu_fitted) ** 2)
1099
+ ss_tot = np.sum((y - np.mean(y)) ** 2)
1100
+ r_squared = 1 - (ss_res / ss_tot) if ss_tot > 0 else 0.0
1101
+ else:
1102
+ r_squared = None
1103
+
1104
+ return att, se, r_squared, pscore_stats
1105
+
1106
+ def _compute_se(
1107
+ self,
1108
+ X: np.ndarray,
1109
+ residuals: np.ndarray,
1110
+ coef_idx: int,
1111
+ ) -> float:
1112
+ """Compute standard error for a coefficient using robust or clustered SE."""
1113
+ n, k = X.shape
1114
+
1115
+ if self.robust:
1116
+ # HC1 robust standard errors
1117
+ vcov = compute_robust_vcov(X, residuals, cluster_ids=None)
1118
+ else:
1119
+ # Classical OLS standard errors
1120
+ mse = np.sum(residuals**2) / (n - k)
1121
+ try:
1122
+ vcov = np.linalg.solve(X.T @ X, mse * np.eye(k))
1123
+ except np.linalg.LinAlgError:
1124
+ vcov = np.linalg.pinv(X.T @ X) * mse
1125
+
1126
+ return float(np.sqrt(vcov[coef_idx, coef_idx]))
1127
+
1128
+ def _compute_ipw_se(
1129
+ self,
1130
+ y: np.ndarray,
1131
+ G: np.ndarray,
1132
+ P: np.ndarray,
1133
+ T: np.ndarray,
1134
+ cell_1: np.ndarray,
1135
+ cell_2: np.ndarray,
1136
+ cell_3: np.ndarray,
1137
+ cell_4: np.ndarray,
1138
+ p_cell_1: np.ndarray,
1139
+ p_cell_2: np.ndarray,
1140
+ p_cell_3: np.ndarray,
1141
+ p_cell_4: np.ndarray,
1142
+ att: float,
1143
+ ) -> float:
1144
+ """Compute standard error for IPW estimator using influence function."""
1145
+ n = len(y)
1146
+ post_mask = T == 1
1147
+
1148
+ # Influence function for IPW estimator (vectorized)
1149
+ inf_func = np.zeros(n)
1150
+
1151
+ n_ref = np.sum(cell_1)
1152
+ p_ref = n_ref / n
1153
+
1154
+ # Sign: +1 for post, -1 for pre
1155
+ sign = np.where(post_mask, 1.0, -1.0)
1156
+
1157
+ # Cell 1 (G=1, P=1): sign * (y - att) / p_ref
1158
+ inf_func[cell_1] = sign[cell_1] * (y[cell_1] - att) / p_ref
1159
+
1160
+ # Cell 2 (G=1, P=0): -sign * y * (p_cell_1 / p_cell_2) / p_ref
1161
+ w_2 = p_cell_1[cell_2] / p_cell_2[cell_2]
1162
+ inf_func[cell_2] = -sign[cell_2] * y[cell_2] * w_2 / p_ref
1163
+
1164
+ # Cell 3 (G=0, P=1): -sign * y * (p_cell_1 / p_cell_3) / p_ref
1165
+ w_3 = p_cell_1[cell_3] / p_cell_3[cell_3]
1166
+ inf_func[cell_3] = -sign[cell_3] * y[cell_3] * w_3 / p_ref
1167
+
1168
+ # Cell 4 (G=0, P=0): sign * y * (p_cell_1 / p_cell_4) / p_ref
1169
+ w_4 = p_cell_1[cell_4] / p_cell_4[cell_4]
1170
+ inf_func[cell_4] = sign[cell_4] * y[cell_4] * w_4 / p_ref
1171
+
1172
+ var_inf = np.var(inf_func, ddof=1)
1173
+ se = np.sqrt(var_inf / n)
1174
+
1175
+ return se
1176
+
1177
+ def get_params(self) -> Dict[str, Any]:
1178
+ """
1179
+ Get estimator parameters (sklearn-compatible).
1180
+
1181
+ Returns
1182
+ -------
1183
+ Dict[str, Any]
1184
+ Estimator parameters.
1185
+ """
1186
+ return {
1187
+ "estimation_method": self.estimation_method,
1188
+ "robust": self.robust,
1189
+ "cluster": self.cluster,
1190
+ "alpha": self.alpha,
1191
+ "pscore_trim": self.pscore_trim,
1192
+ "rank_deficient_action": self.rank_deficient_action,
1193
+ }
1194
+
1195
+ def set_params(self, **params) -> "TripleDifference":
1196
+ """
1197
+ Set estimator parameters (sklearn-compatible).
1198
+
1199
+ Parameters
1200
+ ----------
1201
+ **params
1202
+ Estimator parameters.
1203
+
1204
+ Returns
1205
+ -------
1206
+ self
1207
+ """
1208
+ for key, value in params.items():
1209
+ if hasattr(self, key):
1210
+ setattr(self, key, value)
1211
+ else:
1212
+ raise ValueError(f"Unknown parameter: {key}")
1213
+ return self
1214
+
1215
+ def summary(self) -> str:
1216
+ """
1217
+ Get summary of estimation results.
1218
+
1219
+ Returns
1220
+ -------
1221
+ str
1222
+ Formatted summary.
1223
+ """
1224
+ if not self.is_fitted_:
1225
+ raise RuntimeError("Model must be fitted before calling summary()")
1226
+ assert self.results_ is not None
1227
+ return self.results_.summary()
1228
+
1229
+ def print_summary(self) -> None:
1230
+ """Print summary to stdout."""
1231
+ print(self.summary())
1232
+
1233
+
1234
+ # =============================================================================
1235
+ # Convenience function
1236
+ # =============================================================================
1237
+
1238
+
1239
+ def triple_difference(
1240
+ data: pd.DataFrame,
1241
+ outcome: str,
1242
+ group: str,
1243
+ partition: str,
1244
+ time: str,
1245
+ covariates: Optional[List[str]] = None,
1246
+ estimation_method: str = "dr",
1247
+ robust: bool = True,
1248
+ cluster: Optional[str] = None,
1249
+ alpha: float = 0.05,
1250
+ rank_deficient_action: str = "warn",
1251
+ ) -> TripleDifferenceResults:
1252
+ """
1253
+ Estimate Triple Difference (DDD) treatment effect.
1254
+
1255
+ Convenience function that creates a TripleDifference estimator and
1256
+ fits it to the data in one step.
1257
+
1258
+ Parameters
1259
+ ----------
1260
+ data : pd.DataFrame
1261
+ DataFrame containing all variables.
1262
+ outcome : str
1263
+ Name of the outcome variable column.
1264
+ group : str
1265
+ Name of the group indicator column (0/1).
1266
+ 1 = treated group (e.g., states that enacted policy).
1267
+ partition : str
1268
+ Name of the partition/eligibility indicator column (0/1).
1269
+ 1 = eligible partition (e.g., women, targeted demographic).
1270
+ time : str
1271
+ Name of the time period indicator column (0/1).
1272
+ 1 = post-treatment period.
1273
+ covariates : list of str, optional
1274
+ List of covariate column names to adjust for.
1275
+ estimation_method : str, default="dr"
1276
+ Estimation method: "dr" (doubly robust), "reg" (regression),
1277
+ or "ipw" (inverse probability weighting).
1278
+ robust : bool, default=True
1279
+ Whether to use robust standard errors.
1280
+ cluster : str, optional
1281
+ Column name for cluster-robust standard errors.
1282
+ alpha : float, default=0.05
1283
+ Significance level for confidence intervals.
1284
+ rank_deficient_action : str, default="warn"
1285
+ Action when design matrix is rank-deficient:
1286
+ - "warn": Issue warning and drop linearly dependent columns (default)
1287
+ - "error": Raise ValueError
1288
+ - "silent": Drop columns silently without warning
1289
+
1290
+ Returns
1291
+ -------
1292
+ TripleDifferenceResults
1293
+ Object containing estimation results.
1294
+
1295
+ Examples
1296
+ --------
1297
+ >>> from diff_diff import triple_difference
1298
+ >>> results = triple_difference(
1299
+ ... data,
1300
+ ... outcome='earnings',
1301
+ ... group='policy_state',
1302
+ ... partition='female',
1303
+ ... time='post_policy',
1304
+ ... covariates=['age', 'education']
1305
+ ... )
1306
+ >>> print(f"ATT: {results.att:.3f} (SE: {results.se:.3f})")
1307
+ """
1308
+ estimator = TripleDifference(
1309
+ estimation_method=estimation_method,
1310
+ robust=robust,
1311
+ cluster=cluster,
1312
+ alpha=alpha,
1313
+ rank_deficient_action=rank_deficient_action,
1314
+ )
1315
+ return estimator.fit(
1316
+ data=data,
1317
+ outcome=outcome,
1318
+ group=group,
1319
+ partition=partition,
1320
+ time=time,
1321
+ covariates=covariates,
1322
+ )