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.
diff_diff/prep_dgp.py ADDED
@@ -0,0 +1,777 @@
1
+ """
2
+ Data generation utilities for difference-in-differences analysis.
3
+
4
+ This module provides functions to generate synthetic datasets for testing
5
+ and validating DiD estimators, including basic 2x2 DiD, staggered adoption,
6
+ factor model data, triple difference, and event study designs.
7
+ """
8
+
9
+ from typing import List, Optional
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+
15
+ def generate_did_data(
16
+ n_units: int = 100,
17
+ n_periods: int = 4,
18
+ treatment_effect: float = 5.0,
19
+ treatment_fraction: float = 0.5,
20
+ treatment_period: int = 2,
21
+ unit_fe_sd: float = 2.0,
22
+ time_trend: float = 0.5,
23
+ noise_sd: float = 1.0,
24
+ seed: Optional[int] = None
25
+ ) -> pd.DataFrame:
26
+ """
27
+ Generate synthetic data for DiD analysis with known treatment effect.
28
+
29
+ Creates a balanced panel dataset with realistic features including
30
+ unit fixed effects, time trends, and a known treatment effect.
31
+
32
+ Parameters
33
+ ----------
34
+ n_units : int, default=100
35
+ Number of units in the panel.
36
+ n_periods : int, default=4
37
+ Number of time periods.
38
+ treatment_effect : float, default=5.0
39
+ True average treatment effect on the treated.
40
+ treatment_fraction : float, default=0.5
41
+ Fraction of units that receive treatment.
42
+ treatment_period : int, default=2
43
+ First post-treatment period (0-indexed). Periods >= this are post.
44
+ unit_fe_sd : float, default=2.0
45
+ Standard deviation of unit fixed effects.
46
+ time_trend : float, default=0.5
47
+ Linear time trend coefficient.
48
+ noise_sd : float, default=1.0
49
+ Standard deviation of idiosyncratic noise.
50
+ seed : int, optional
51
+ Random seed for reproducibility.
52
+
53
+ Returns
54
+ -------
55
+ pd.DataFrame
56
+ Synthetic panel data with columns:
57
+ - unit: Unit identifier
58
+ - period: Time period
59
+ - treated: Treatment indicator (0/1)
60
+ - post: Post-treatment indicator (0/1)
61
+ - outcome: Outcome variable
62
+ - true_effect: The true treatment effect (for validation)
63
+
64
+ Examples
65
+ --------
66
+ Generate simple data for testing:
67
+
68
+ >>> data = generate_did_data(n_units=50, n_periods=4, treatment_effect=3.0, seed=42)
69
+ >>> len(data)
70
+ 200
71
+ >>> data.columns.tolist()
72
+ ['unit', 'period', 'treated', 'post', 'outcome', 'true_effect']
73
+
74
+ Verify treatment effect recovery:
75
+
76
+ >>> from diff_diff import DifferenceInDifferences
77
+ >>> did = DifferenceInDifferences()
78
+ >>> results = did.fit(data, outcome='outcome', treatment='treated', time='post')
79
+ >>> abs(results.att - 3.0) < 1.0 # Close to true effect
80
+ True
81
+ """
82
+ rng = np.random.default_rng(seed)
83
+
84
+ # Determine treated units
85
+ n_treated = int(n_units * treatment_fraction)
86
+ treated_units = set(range(n_treated))
87
+
88
+ # Generate unit fixed effects
89
+ unit_fe = rng.normal(0, unit_fe_sd, n_units)
90
+
91
+ # Build data
92
+ records = []
93
+ for unit in range(n_units):
94
+ is_treated = unit in treated_units
95
+
96
+ for period in range(n_periods):
97
+ is_post = period >= treatment_period
98
+
99
+ # Base outcome
100
+ y = 10.0 # Baseline
101
+ y += unit_fe[unit] # Unit fixed effect
102
+ y += time_trend * period # Time trend
103
+
104
+ # Treatment effect (only for treated units in post-period)
105
+ effect = 0.0
106
+ if is_treated and is_post:
107
+ effect = treatment_effect
108
+ y += effect
109
+
110
+ # Add noise
111
+ y += rng.normal(0, noise_sd)
112
+
113
+ records.append({
114
+ "unit": unit,
115
+ "period": period,
116
+ "treated": int(is_treated),
117
+ "post": int(is_post),
118
+ "outcome": y,
119
+ "true_effect": effect
120
+ })
121
+
122
+ return pd.DataFrame(records)
123
+
124
+
125
+ def generate_staggered_data(
126
+ n_units: int = 100,
127
+ n_periods: int = 10,
128
+ cohort_periods: Optional[List[int]] = None,
129
+ never_treated_frac: float = 0.3,
130
+ treatment_effect: float = 2.0,
131
+ dynamic_effects: bool = True,
132
+ effect_growth: float = 0.1,
133
+ unit_fe_sd: float = 2.0,
134
+ time_trend: float = 0.1,
135
+ noise_sd: float = 0.5,
136
+ seed: Optional[int] = None,
137
+ ) -> pd.DataFrame:
138
+ """
139
+ Generate synthetic data for staggered adoption DiD analysis.
140
+
141
+ Creates panel data where different units receive treatment at different
142
+ times (staggered rollout). Useful for testing CallawaySantAnna,
143
+ SunAbraham, and other staggered DiD estimators.
144
+
145
+ Parameters
146
+ ----------
147
+ n_units : int, default=100
148
+ Total number of units in the panel.
149
+ n_periods : int, default=10
150
+ Number of time periods.
151
+ cohort_periods : list of int, optional
152
+ Periods when treatment cohorts are first treated.
153
+ If None, defaults to [3, 5, 7] for a 10-period panel.
154
+ never_treated_frac : float, default=0.3
155
+ Fraction of units that are never treated (cohort 0).
156
+ treatment_effect : float, default=2.0
157
+ Base treatment effect at time of treatment.
158
+ dynamic_effects : bool, default=True
159
+ If True, treatment effects grow over time since treatment.
160
+ effect_growth : float, default=0.1
161
+ Per-period growth in treatment effect (if dynamic_effects=True).
162
+ Effect at time t since treatment: effect * (1 + effect_growth * t).
163
+ unit_fe_sd : float, default=2.0
164
+ Standard deviation of unit fixed effects.
165
+ time_trend : float, default=0.1
166
+ Linear time trend coefficient.
167
+ noise_sd : float, default=0.5
168
+ Standard deviation of idiosyncratic noise.
169
+ seed : int, optional
170
+ Random seed for reproducibility.
171
+
172
+ Returns
173
+ -------
174
+ pd.DataFrame
175
+ Synthetic staggered adoption data with columns:
176
+ - unit: Unit identifier
177
+ - period: Time period
178
+ - outcome: Outcome variable
179
+ - first_treat: First treatment period (0 = never treated)
180
+ - treated: Binary indicator (1 if treated at this observation)
181
+ - treat: Binary unit-level ever-treated indicator
182
+ - true_effect: The true treatment effect for this observation
183
+
184
+ Examples
185
+ --------
186
+ Generate staggered adoption data:
187
+
188
+ >>> data = generate_staggered_data(n_units=100, n_periods=10, seed=42)
189
+ >>> data['first_treat'].value_counts().sort_index()
190
+ 0 30
191
+ 3 24
192
+ 5 23
193
+ 7 23
194
+ Name: first_treat, dtype: int64
195
+
196
+ Use with Callaway-Sant'Anna estimator:
197
+
198
+ >>> from diff_diff import CallawaySantAnna
199
+ >>> cs = CallawaySantAnna()
200
+ >>> results = cs.fit(data, outcome='outcome', unit='unit',
201
+ ... time='period', first_treat='first_treat')
202
+ >>> results.overall_att > 0
203
+ True
204
+ """
205
+ rng = np.random.default_rng(seed)
206
+
207
+ # Default cohort periods if not specified
208
+ if cohort_periods is None:
209
+ cohort_periods = [3, 5, 7] if n_periods >= 8 else [n_periods // 3, 2 * n_periods // 3]
210
+
211
+ # Validate cohort periods
212
+ for cp in cohort_periods:
213
+ if cp < 1 or cp >= n_periods:
214
+ raise ValueError(
215
+ f"Cohort period {cp} must be between 1 and {n_periods - 1}"
216
+ )
217
+
218
+ # Determine number of never-treated and treated units
219
+ n_never = int(n_units * never_treated_frac)
220
+ n_treated = n_units - n_never
221
+
222
+ # Assign treatment cohorts
223
+ first_treat = np.zeros(n_units, dtype=int)
224
+ if n_treated > 0:
225
+ cohort_assignments = rng.choice(len(cohort_periods), size=n_treated)
226
+ first_treat[n_never:] = [cohort_periods[c] for c in cohort_assignments]
227
+
228
+ # Generate unit fixed effects
229
+ unit_fe = rng.normal(0, unit_fe_sd, n_units)
230
+
231
+ # Build data
232
+ records = []
233
+ for unit in range(n_units):
234
+ unit_first_treat = first_treat[unit]
235
+ is_ever_treated = unit_first_treat > 0
236
+
237
+ for period in range(n_periods):
238
+ # Check if treated at this observation
239
+ is_treated = is_ever_treated and period >= unit_first_treat
240
+
241
+ # Base outcome: unit FE + time trend
242
+ y = 10.0 + unit_fe[unit] + time_trend * period
243
+
244
+ # Treatment effect
245
+ effect = 0.0
246
+ if is_treated:
247
+ time_since_treatment = period - unit_first_treat
248
+ if dynamic_effects:
249
+ effect = treatment_effect * (1 + effect_growth * time_since_treatment)
250
+ else:
251
+ effect = treatment_effect
252
+ y += effect
253
+
254
+ # Add noise
255
+ y += rng.normal(0, noise_sd)
256
+
257
+ records.append({
258
+ "unit": unit,
259
+ "period": period,
260
+ "outcome": y,
261
+ "first_treat": unit_first_treat,
262
+ "treated": int(is_treated),
263
+ "treat": int(is_ever_treated),
264
+ "true_effect": effect,
265
+ })
266
+
267
+ return pd.DataFrame(records)
268
+
269
+
270
+ def generate_factor_data(
271
+ n_units: int = 50,
272
+ n_pre: int = 10,
273
+ n_post: int = 5,
274
+ n_treated: int = 10,
275
+ n_factors: int = 2,
276
+ treatment_effect: float = 2.0,
277
+ factor_strength: float = 1.0,
278
+ treated_loading_shift: float = 0.5,
279
+ unit_fe_sd: float = 1.0,
280
+ noise_sd: float = 0.5,
281
+ seed: Optional[int] = None,
282
+ ) -> pd.DataFrame:
283
+ """
284
+ Generate synthetic panel data with interactive fixed effects (factor model).
285
+
286
+ Creates data following the DGP:
287
+ Y_it = mu + alpha_i + beta_t + Lambda_i'F_t + tau*D_it + eps_it
288
+
289
+ where Lambda_i'F_t is the interactive fixed effects component. Useful for
290
+ testing TROP (Triply Robust Panel) and comparing with SyntheticDiD.
291
+
292
+ Parameters
293
+ ----------
294
+ n_units : int, default=50
295
+ Total number of units in the panel.
296
+ n_pre : int, default=10
297
+ Number of pre-treatment periods.
298
+ n_post : int, default=5
299
+ Number of post-treatment periods.
300
+ n_treated : int, default=10
301
+ Number of treated units (assigned to first n_treated unit IDs).
302
+ n_factors : int, default=2
303
+ Number of latent factors in the interactive fixed effects.
304
+ treatment_effect : float, default=2.0
305
+ True average treatment effect on the treated.
306
+ factor_strength : float, default=1.0
307
+ Scaling factor for interactive fixed effects.
308
+ treated_loading_shift : float, default=0.5
309
+ Shift in factor loadings for treated units (creates confounding).
310
+ unit_fe_sd : float, default=1.0
311
+ Standard deviation of unit fixed effects.
312
+ noise_sd : float, default=0.5
313
+ Standard deviation of idiosyncratic noise.
314
+ seed : int, optional
315
+ Random seed for reproducibility.
316
+
317
+ Returns
318
+ -------
319
+ pd.DataFrame
320
+ Synthetic factor model data with columns:
321
+ - unit: Unit identifier
322
+ - period: Time period
323
+ - outcome: Outcome variable
324
+ - treated: Binary indicator (1 if treated at this observation)
325
+ - treat: Binary unit-level ever-treated indicator
326
+ - true_effect: The true treatment effect for this observation
327
+
328
+ Examples
329
+ --------
330
+ Generate data with factor structure:
331
+
332
+ >>> data = generate_factor_data(n_units=50, n_factors=2, seed=42)
333
+ >>> data.shape
334
+ (750, 6)
335
+
336
+ Use with TROP estimator:
337
+
338
+ >>> from diff_diff import TROP
339
+ >>> trop = TROP(n_bootstrap=50, seed=42)
340
+ >>> results = trop.fit(data, outcome='outcome', treatment='treated',
341
+ ... unit='unit', time='period',
342
+ ... post_periods=list(range(10, 15)))
343
+
344
+ Notes
345
+ -----
346
+ The treated units have systematically different factor loadings
347
+ (shifted by `treated_loading_shift`), which creates confounding
348
+ that standard DiD cannot address but TROP can handle.
349
+ """
350
+ rng = np.random.default_rng(seed)
351
+
352
+ n_control = n_units - n_treated
353
+ n_periods = n_pre + n_post
354
+
355
+ if n_treated > n_units:
356
+ raise ValueError(f"n_treated ({n_treated}) cannot exceed n_units ({n_units})")
357
+ if n_treated < 1:
358
+ raise ValueError("n_treated must be at least 1")
359
+
360
+ # Generate factors F: (n_periods, n_factors)
361
+ F = rng.normal(0, 1, (n_periods, n_factors))
362
+
363
+ # Generate loadings Lambda: (n_factors, n_units)
364
+ # Treated units have shifted loadings (creates confounding)
365
+ Lambda = rng.normal(0, 1, (n_factors, n_units))
366
+ Lambda[:, :n_treated] += treated_loading_shift
367
+
368
+ # Unit fixed effects (treated units have higher baseline)
369
+ alpha = rng.normal(0, unit_fe_sd, n_units)
370
+ alpha[:n_treated] += 1.0
371
+
372
+ # Time fixed effects (linear trend)
373
+ beta = np.linspace(0, 2, n_periods)
374
+
375
+ # Generate outcomes
376
+ records = []
377
+ for i in range(n_units):
378
+ is_ever_treated = i < n_treated
379
+
380
+ for t in range(n_periods):
381
+ post = t >= n_pre
382
+
383
+ # Base outcome
384
+ y = 10.0 + alpha[i] + beta[t]
385
+
386
+ # Interactive fixed effects: Lambda_i' F_t
387
+ y += factor_strength * (Lambda[:, i] @ F[t, :])
388
+
389
+ # Treatment effect
390
+ effect = 0.0
391
+ if is_ever_treated and post:
392
+ effect = treatment_effect
393
+ y += effect
394
+
395
+ # Add noise
396
+ y += rng.normal(0, noise_sd)
397
+
398
+ records.append({
399
+ "unit": i,
400
+ "period": t,
401
+ "outcome": y,
402
+ "treated": int(is_ever_treated and post),
403
+ "treat": int(is_ever_treated),
404
+ "true_effect": effect,
405
+ })
406
+
407
+ return pd.DataFrame(records)
408
+
409
+
410
+ def generate_ddd_data(
411
+ n_per_cell: int = 100,
412
+ treatment_effect: float = 2.0,
413
+ group_effect: float = 2.0,
414
+ partition_effect: float = 1.0,
415
+ time_effect: float = 0.5,
416
+ noise_sd: float = 1.0,
417
+ add_covariates: bool = False,
418
+ seed: Optional[int] = None,
419
+ ) -> pd.DataFrame:
420
+ """
421
+ Generate synthetic data for Triple Difference (DDD) analysis.
422
+
423
+ Creates data following the DGP:
424
+ Y = mu + G + P + T + G*P + G*T + P*T + tau*G*P*T + eps
425
+
426
+ where G=group, P=partition, T=time. The treatment effect (tau) only
427
+ applies to units that are in the treated group (G=1), eligible
428
+ partition (P=1), and post-treatment period (T=1).
429
+
430
+ Parameters
431
+ ----------
432
+ n_per_cell : int, default=100
433
+ Number of observations per cell (8 cells total: 2x2x2).
434
+ treatment_effect : float, default=2.0
435
+ True average treatment effect on the treated (G=1, P=1, T=1).
436
+ group_effect : float, default=2.0
437
+ Main effect of being in treated group.
438
+ partition_effect : float, default=1.0
439
+ Main effect of being in eligible partition.
440
+ time_effect : float, default=0.5
441
+ Main effect of post-treatment period.
442
+ noise_sd : float, default=1.0
443
+ Standard deviation of idiosyncratic noise.
444
+ add_covariates : bool, default=False
445
+ If True, adds age and education covariates that affect outcome.
446
+ seed : int, optional
447
+ Random seed for reproducibility.
448
+
449
+ Returns
450
+ -------
451
+ pd.DataFrame
452
+ Synthetic DDD data with columns:
453
+ - outcome: Outcome variable
454
+ - group: Group indicator (0=control, 1=treated)
455
+ - partition: Partition indicator (0=ineligible, 1=eligible)
456
+ - time: Time indicator (0=pre, 1=post)
457
+ - unit_id: Unique unit identifier
458
+ - true_effect: The true treatment effect for this observation
459
+ - age: Age covariate (if add_covariates=True)
460
+ - education: Education covariate (if add_covariates=True)
461
+
462
+ Examples
463
+ --------
464
+ Generate DDD data:
465
+
466
+ >>> data = generate_ddd_data(n_per_cell=100, treatment_effect=3.0, seed=42)
467
+ >>> data.shape
468
+ (800, 6)
469
+ >>> data.groupby(['group', 'partition', 'time']).size()
470
+ group partition time
471
+ 0 0 0 100
472
+ 1 100
473
+ 1 0 100
474
+ 1 100
475
+ 1 0 0 100
476
+ 1 100
477
+ 1 0 100
478
+ 1 100
479
+ dtype: int64
480
+
481
+ Use with TripleDifference estimator:
482
+
483
+ >>> from diff_diff import TripleDifference
484
+ >>> ddd = TripleDifference()
485
+ >>> results = ddd.fit(data, outcome='outcome', group='group',
486
+ ... partition='partition', time='time')
487
+ >>> abs(results.att - 3.0) < 1.0
488
+ True
489
+ """
490
+ rng = np.random.default_rng(seed)
491
+
492
+ records = []
493
+ unit_id = 0
494
+
495
+ for g in [0, 1]: # group (0=control state, 1=treated state)
496
+ for p in [0, 1]: # partition (0=ineligible, 1=eligible)
497
+ for t in [0, 1]: # time (0=pre, 1=post)
498
+ for _ in range(n_per_cell):
499
+ # Base outcome with main effects
500
+ y = 50 + group_effect * g + partition_effect * p + time_effect * t
501
+
502
+ # Second-order interactions (non-treatment)
503
+ y += 1.5 * g * p # group-partition interaction
504
+ y += 1.0 * g * t # group-time interaction (diff trends)
505
+ y += 0.5 * p * t # partition-time interaction
506
+
507
+ # Treatment effect: ONLY for G=1, P=1, T=1
508
+ effect = 0.0
509
+ if g == 1 and p == 1 and t == 1:
510
+ effect = treatment_effect
511
+ y += effect
512
+
513
+ # Covariates (always generated for consistency)
514
+ age = rng.normal(40, 10)
515
+ education = rng.choice([12, 14, 16, 18], p=[0.3, 0.3, 0.25, 0.15])
516
+
517
+ if add_covariates:
518
+ y += 0.1 * age + 0.5 * education
519
+
520
+ # Add noise
521
+ y += rng.normal(0, noise_sd)
522
+
523
+ record = {
524
+ "outcome": y,
525
+ "group": g,
526
+ "partition": p,
527
+ "time": t,
528
+ "unit_id": unit_id,
529
+ "true_effect": effect,
530
+ }
531
+
532
+ if add_covariates:
533
+ record["age"] = age
534
+ record["education"] = education
535
+
536
+ records.append(record)
537
+ unit_id += 1
538
+
539
+ return pd.DataFrame(records)
540
+
541
+
542
+ def generate_panel_data(
543
+ n_units: int = 100,
544
+ n_periods: int = 8,
545
+ treatment_period: int = 4,
546
+ treatment_fraction: float = 0.5,
547
+ treatment_effect: float = 5.0,
548
+ parallel_trends: bool = True,
549
+ trend_violation: float = 1.0,
550
+ unit_fe_sd: float = 2.0,
551
+ noise_sd: float = 0.5,
552
+ seed: Optional[int] = None,
553
+ ) -> pd.DataFrame:
554
+ """
555
+ Generate synthetic panel data for parallel trends testing.
556
+
557
+ Creates panel data with optional violation of parallel trends, useful
558
+ for testing parallel trends diagnostics, placebo tests, and sensitivity
559
+ analysis methods.
560
+
561
+ Parameters
562
+ ----------
563
+ n_units : int, default=100
564
+ Total number of units in the panel.
565
+ n_periods : int, default=8
566
+ Number of time periods.
567
+ treatment_period : int, default=4
568
+ First post-treatment period (0-indexed).
569
+ treatment_fraction : float, default=0.5
570
+ Fraction of units that receive treatment.
571
+ treatment_effect : float, default=5.0
572
+ True average treatment effect on the treated.
573
+ parallel_trends : bool, default=True
574
+ If True, treated and control groups have parallel pre-treatment trends.
575
+ If False, treated group has a steeper pre-treatment trend.
576
+ trend_violation : float, default=1.0
577
+ Size of the differential trend for treated group when parallel_trends=False.
578
+ Treated units have trend = common_trend + trend_violation.
579
+ unit_fe_sd : float, default=2.0
580
+ Standard deviation of unit fixed effects.
581
+ noise_sd : float, default=0.5
582
+ Standard deviation of idiosyncratic noise.
583
+ seed : int, optional
584
+ Random seed for reproducibility.
585
+
586
+ Returns
587
+ -------
588
+ pd.DataFrame
589
+ Synthetic panel data with columns:
590
+ - unit: Unit identifier
591
+ - period: Time period
592
+ - treated: Binary unit-level treatment indicator
593
+ - post: Binary post-treatment indicator
594
+ - outcome: Outcome variable
595
+ - true_effect: The true treatment effect for this observation
596
+
597
+ Examples
598
+ --------
599
+ Generate data with parallel trends:
600
+
601
+ >>> data_parallel = generate_panel_data(parallel_trends=True, seed=42)
602
+ >>> from diff_diff.utils import check_parallel_trends
603
+ >>> result = check_parallel_trends(data_parallel, outcome='outcome',
604
+ ... time='period', treatment_group='treated',
605
+ ... pre_periods=[0, 1, 2, 3])
606
+ >>> result['parallel_trends_plausible']
607
+ True
608
+
609
+ Generate data with trend violation:
610
+
611
+ >>> data_violation = generate_panel_data(parallel_trends=False, seed=42)
612
+ >>> result = check_parallel_trends(data_violation, outcome='outcome',
613
+ ... time='period', treatment_group='treated',
614
+ ... pre_periods=[0, 1, 2, 3])
615
+ >>> result['parallel_trends_plausible']
616
+ False
617
+ """
618
+ rng = np.random.default_rng(seed)
619
+
620
+ if treatment_period < 1:
621
+ raise ValueError("treatment_period must be at least 1")
622
+ if treatment_period >= n_periods:
623
+ raise ValueError(f"treatment_period must be less than n_periods ({n_periods})")
624
+
625
+ n_treated = int(n_units * treatment_fraction)
626
+
627
+ records = []
628
+ for unit in range(n_units):
629
+ is_treated = unit < n_treated
630
+ unit_fe = rng.normal(0, unit_fe_sd)
631
+
632
+ for period in range(n_periods):
633
+ post = period >= treatment_period
634
+
635
+ # Base time effect (common trend)
636
+ if parallel_trends:
637
+ time_effect = period * 1.0
638
+ else:
639
+ # Different trends: treated has steeper pre-treatment trend
640
+ if is_treated:
641
+ time_effect = period * (1.0 + trend_violation)
642
+ else:
643
+ time_effect = period * 1.0
644
+
645
+ y = 10.0 + unit_fe + time_effect
646
+
647
+ # Treatment effect (only for treated in post-period)
648
+ effect = 0.0
649
+ if is_treated and post:
650
+ effect = treatment_effect
651
+ y += effect
652
+
653
+ # Add noise
654
+ y += rng.normal(0, noise_sd)
655
+
656
+ records.append({
657
+ "unit": unit,
658
+ "period": period,
659
+ "treated": int(is_treated),
660
+ "post": int(post),
661
+ "outcome": y,
662
+ "true_effect": effect,
663
+ })
664
+
665
+ return pd.DataFrame(records)
666
+
667
+
668
+ def generate_event_study_data(
669
+ n_units: int = 300,
670
+ n_pre: int = 5,
671
+ n_post: int = 5,
672
+ treatment_fraction: float = 0.5,
673
+ treatment_effect: float = 5.0,
674
+ unit_fe_sd: float = 2.0,
675
+ noise_sd: float = 2.0,
676
+ seed: Optional[int] = None,
677
+ ) -> pd.DataFrame:
678
+ """
679
+ Generate synthetic data for event study analysis.
680
+
681
+ Creates panel data with simultaneous treatment at period n_pre.
682
+ Useful for testing MultiPeriodDiD, pre-trends power analysis,
683
+ and HonestDiD sensitivity analysis.
684
+
685
+ Parameters
686
+ ----------
687
+ n_units : int, default=300
688
+ Total number of units in the panel.
689
+ n_pre : int, default=5
690
+ Number of pre-treatment periods.
691
+ n_post : int, default=5
692
+ Number of post-treatment periods.
693
+ treatment_fraction : float, default=0.5
694
+ Fraction of units that receive treatment.
695
+ treatment_effect : float, default=5.0
696
+ True average treatment effect on the treated.
697
+ unit_fe_sd : float, default=2.0
698
+ Standard deviation of unit fixed effects.
699
+ noise_sd : float, default=2.0
700
+ Standard deviation of idiosyncratic noise.
701
+ seed : int, optional
702
+ Random seed for reproducibility.
703
+
704
+ Returns
705
+ -------
706
+ pd.DataFrame
707
+ Synthetic event study data with columns:
708
+ - unit: Unit identifier
709
+ - period: Time period
710
+ - treated: Binary unit-level treatment indicator
711
+ - post: Binary post-treatment indicator
712
+ - outcome: Outcome variable
713
+ - event_time: Time relative to treatment (negative=pre, 0+=post)
714
+ - true_effect: The true treatment effect for this observation
715
+
716
+ Examples
717
+ --------
718
+ Generate event study data:
719
+
720
+ >>> data = generate_event_study_data(n_units=300, n_pre=5, n_post=5, seed=42)
721
+ >>> data['event_time'].unique()
722
+ array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
723
+
724
+ Use with MultiPeriodDiD:
725
+
726
+ >>> from diff_diff import MultiPeriodDiD
727
+ >>> mp_did = MultiPeriodDiD()
728
+ >>> results = mp_did.fit(data, outcome='outcome', treatment='treated',
729
+ ... time='period', post_periods=[5, 6, 7, 8, 9])
730
+
731
+ Notes
732
+ -----
733
+ The event_time column is relative to treatment:
734
+ - Negative values: pre-treatment periods
735
+ - 0: first post-treatment period
736
+ - Positive values: subsequent post-treatment periods
737
+ """
738
+ rng = np.random.default_rng(seed)
739
+
740
+ n_periods = n_pre + n_post
741
+ treatment_period = n_pre
742
+ n_treated = int(n_units * treatment_fraction)
743
+
744
+ records = []
745
+ for unit in range(n_units):
746
+ is_treated = unit < n_treated
747
+ unit_fe = rng.normal(0, unit_fe_sd)
748
+
749
+ for period in range(n_periods):
750
+ post = period >= treatment_period
751
+ event_time = period - treatment_period
752
+
753
+ # Common time trend
754
+ time_effect = period * 0.5
755
+
756
+ y = 10.0 + unit_fe + time_effect
757
+
758
+ # Treatment effect (only for treated in post-period)
759
+ effect = 0.0
760
+ if is_treated and post:
761
+ effect = treatment_effect
762
+ y += effect
763
+
764
+ # Add noise
765
+ y += rng.normal(0, noise_sd)
766
+
767
+ records.append({
768
+ "unit": unit,
769
+ "period": period,
770
+ "treated": int(is_treated),
771
+ "post": int(post),
772
+ "outcome": y,
773
+ "event_time": event_time,
774
+ "true_effect": effect,
775
+ })
776
+
777
+ return pd.DataFrame(records)