diff-diff 3.0.1__cp314-cp314-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.
Files changed (62) hide show
  1. diff_diff/__init__.py +382 -0
  2. diff_diff/_backend.py +134 -0
  3. diff_diff/_rust_backend.cp314-win_amd64.pyd +0 -0
  4. diff_diff/bacon.py +1140 -0
  5. diff_diff/bootstrap_utils.py +730 -0
  6. diff_diff/continuous_did.py +1626 -0
  7. diff_diff/continuous_did_bspline.py +190 -0
  8. diff_diff/continuous_did_results.py +374 -0
  9. diff_diff/datasets.py +815 -0
  10. diff_diff/diagnostics.py +882 -0
  11. diff_diff/efficient_did.py +1770 -0
  12. diff_diff/efficient_did_bootstrap.py +359 -0
  13. diff_diff/efficient_did_covariates.py +899 -0
  14. diff_diff/efficient_did_results.py +368 -0
  15. diff_diff/efficient_did_weights.py +617 -0
  16. diff_diff/estimators.py +1501 -0
  17. diff_diff/honest_did.py +2585 -0
  18. diff_diff/imputation.py +2458 -0
  19. diff_diff/imputation_bootstrap.py +418 -0
  20. diff_diff/imputation_results.py +448 -0
  21. diff_diff/linalg.py +2538 -0
  22. diff_diff/power.py +2588 -0
  23. diff_diff/practitioner.py +869 -0
  24. diff_diff/prep.py +1738 -0
  25. diff_diff/prep_dgp.py +1718 -0
  26. diff_diff/pretrends.py +1105 -0
  27. diff_diff/results.py +918 -0
  28. diff_diff/stacked_did.py +1049 -0
  29. diff_diff/stacked_did_results.py +339 -0
  30. diff_diff/staggered.py +3895 -0
  31. diff_diff/staggered_aggregation.py +864 -0
  32. diff_diff/staggered_bootstrap.py +752 -0
  33. diff_diff/staggered_results.py +416 -0
  34. diff_diff/staggered_triple_diff.py +1545 -0
  35. diff_diff/staggered_triple_diff_results.py +416 -0
  36. diff_diff/sun_abraham.py +1685 -0
  37. diff_diff/survey.py +1981 -0
  38. diff_diff/synthetic_did.py +1136 -0
  39. diff_diff/triple_diff.py +2047 -0
  40. diff_diff/trop.py +952 -0
  41. diff_diff/trop_global.py +1270 -0
  42. diff_diff/trop_local.py +1307 -0
  43. diff_diff/trop_results.py +356 -0
  44. diff_diff/twfe.py +542 -0
  45. diff_diff/two_stage.py +1952 -0
  46. diff_diff/two_stage_bootstrap.py +520 -0
  47. diff_diff/two_stage_results.py +400 -0
  48. diff_diff/utils.py +1902 -0
  49. diff_diff/visualization/__init__.py +61 -0
  50. diff_diff/visualization/_common.py +328 -0
  51. diff_diff/visualization/_continuous.py +274 -0
  52. diff_diff/visualization/_diagnostic.py +817 -0
  53. diff_diff/visualization/_event_study.py +1086 -0
  54. diff_diff/visualization/_power.py +661 -0
  55. diff_diff/visualization/_staggered.py +833 -0
  56. diff_diff/visualization/_synthetic.py +197 -0
  57. diff_diff/wooldridge.py +1285 -0
  58. diff_diff/wooldridge_results.py +349 -0
  59. diff_diff-3.0.1.dist-info/METADATA +2997 -0
  60. diff_diff-3.0.1.dist-info/RECORD +62 -0
  61. diff_diff-3.0.1.dist-info/WHEEL +4 -0
  62. diff_diff-3.0.1.dist-info/sboms/diff_diff_rust.cyclonedx.json +5843 -0
@@ -0,0 +1,1086 @@
1
+ """Event study visualization functions."""
2
+
3
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ if TYPE_CHECKING:
9
+ from diff_diff.honest_did import HonestDiDResults
10
+ from diff_diff.imputation import ImputationDiDResults
11
+ from diff_diff.results import MultiPeriodDiDResults
12
+ from diff_diff.stacked_did import StackedDiDResults
13
+ from diff_diff.staggered import CallawaySantAnnaResults
14
+ from diff_diff.sun_abraham import SunAbrahamResults
15
+ from diff_diff.two_stage import TwoStageDiDResults
16
+
17
+ # Type alias for results that can be plotted
18
+ PlottableResults = Union[
19
+ "MultiPeriodDiDResults",
20
+ "CallawaySantAnnaResults",
21
+ "SunAbrahamResults",
22
+ "ImputationDiDResults",
23
+ "TwoStageDiDResults",
24
+ "StackedDiDResults",
25
+ pd.DataFrame,
26
+ ]
27
+
28
+
29
+ def plot_event_study(
30
+ results: Optional[PlottableResults] = None,
31
+ *,
32
+ effects: Optional[Dict[Any, float]] = None,
33
+ se: Optional[Dict[Any, float]] = None,
34
+ periods: Optional[List[Any]] = None,
35
+ reference_period: Optional[Any] = None,
36
+ pre_periods: Optional[List[Any]] = None,
37
+ post_periods: Optional[List[Any]] = None,
38
+ alpha: float = 0.05,
39
+ figsize: Tuple[float, float] = (10, 6),
40
+ title: str = "Event Study",
41
+ xlabel: str = "Period Relative to Treatment",
42
+ ylabel: str = "Treatment Effect",
43
+ color: str = "#2563eb",
44
+ marker: str = "o",
45
+ markersize: int = 8,
46
+ linewidth: float = 1.5,
47
+ capsize: int = 4,
48
+ show_zero_line: bool = True,
49
+ show_reference_line: bool = True,
50
+ shade_pre: bool = True,
51
+ shade_color: str = "#f0f0f0",
52
+ ax: Optional[Any] = None,
53
+ show: bool = True,
54
+ use_cband: bool = True,
55
+ backend: str = "matplotlib",
56
+ ) -> Any:
57
+ """
58
+ Create an event study plot showing treatment effects over time.
59
+
60
+ This function creates a coefficient plot with point estimates and
61
+ confidence intervals for each time period, commonly used to visualize
62
+ dynamic treatment effects and assess pre-trends.
63
+
64
+ Parameters
65
+ ----------
66
+ results : MultiPeriodDiDResults, CallawaySantAnnaResults, or DataFrame, optional
67
+ Results object from MultiPeriodDiD, CallawaySantAnna, or a DataFrame
68
+ with columns 'period', 'effect', 'se' (and optionally 'conf_int_lower',
69
+ 'conf_int_upper'). If None, must provide effects and se directly.
70
+ effects : dict, optional
71
+ Dictionary mapping periods to effect estimates. Used if results is None.
72
+ se : dict, optional
73
+ Dictionary mapping periods to standard errors. Used if results is None.
74
+ periods : list, optional
75
+ List of periods to plot. If None, uses all periods from results.
76
+ reference_period : any, optional
77
+ The reference period to highlight. When explicitly provided, effects
78
+ are normalized (ref effect subtracted) and ref SE is set to NaN.
79
+ When None and auto-inferred from results, only hollow marker styling
80
+ is applied (no normalization). If None, tries to infer from results.
81
+ pre_periods : list, optional
82
+ List of pre-treatment periods. Used for shading.
83
+ post_periods : list, optional
84
+ List of post-treatment periods. Used for shading.
85
+ alpha : float, default=0.05
86
+ Significance level for confidence intervals.
87
+ figsize : tuple, default=(10, 6)
88
+ Figure size (width, height) in inches.
89
+ title : str, default="Event Study"
90
+ Plot title.
91
+ xlabel : str, default="Period Relative to Treatment"
92
+ X-axis label.
93
+ ylabel : str, default="Treatment Effect"
94
+ Y-axis label.
95
+ color : str, default="#2563eb"
96
+ Color for points and error bars.
97
+ marker : str, default="o"
98
+ Marker style for point estimates.
99
+ markersize : int, default=8
100
+ Size of markers.
101
+ linewidth : float, default=1.5
102
+ Width of error bar lines.
103
+ capsize : int, default=4
104
+ Size of error bar caps.
105
+ show_zero_line : bool, default=True
106
+ Whether to show a horizontal line at y=0.
107
+ show_reference_line : bool, default=True
108
+ Whether to show a vertical line at the reference period.
109
+ shade_pre : bool, default=True
110
+ Whether to shade the pre-treatment region.
111
+ shade_color : str, default="#f0f0f0"
112
+ Color for pre-treatment shading.
113
+ ax : matplotlib.axes.Axes, optional
114
+ Axes to plot on. If None, creates new figure.
115
+ show : bool, default=True
116
+ Whether to call plt.show() at the end.
117
+ use_cband : bool, default=True
118
+ Whether to use simultaneous confidence band CIs when available
119
+ from CallawaySantAnna results. When False, pointwise CIs from
120
+ ``alpha`` are used regardless.
121
+ backend : str, default="matplotlib"
122
+ Plotting backend: ``"matplotlib"`` for static plots or
123
+ ``"plotly"`` for interactive plots.
124
+
125
+ Returns
126
+ -------
127
+ matplotlib.axes.Axes or plotly.graph_objects.Figure
128
+ The axes object (matplotlib) or figure (plotly) containing the plot.
129
+
130
+ Examples
131
+ --------
132
+ Using with MultiPeriodDiD results:
133
+
134
+ >>> from diff_diff import MultiPeriodDiD, plot_event_study
135
+ >>> did = MultiPeriodDiD()
136
+ >>> results = did.fit(data, outcome='y', treatment='treated',
137
+ ... time='period', post_periods=[3, 4, 5])
138
+ >>> plot_event_study(results)
139
+
140
+ Using with a DataFrame:
141
+
142
+ >>> df = pd.DataFrame({
143
+ ... 'period': [-2, -1, 0, 1, 2],
144
+ ... 'effect': [0.1, 0.05, 0.0, 0.5, 0.6],
145
+ ... 'se': [0.1, 0.1, 0.0, 0.15, 0.15]
146
+ ... })
147
+ >>> plot_event_study(df, reference_period=0)
148
+
149
+ Using with manual effects:
150
+
151
+ >>> effects = {-2: 0.1, -1: 0.05, 0: 0.0, 1: 0.5, 2: 0.6}
152
+ >>> se = {-2: 0.1, -1: 0.1, 0: 0.0, 1: 0.15, 2: 0.15}
153
+ >>> plot_event_study(effects=effects, se=se, reference_period=0)
154
+
155
+ Notes
156
+ -----
157
+ Event study plots are a standard visualization in difference-in-differences
158
+ analysis. They show:
159
+
160
+ 1. **Pre-treatment periods**: Effects should be close to zero if parallel
161
+ trends holds. Large pre-treatment effects suggest the assumption may
162
+ be violated.
163
+
164
+ 2. **Reference period**: Usually the last pre-treatment period (t=-1).
165
+ When explicitly specified via ``reference_period``, effects are normalized
166
+ to zero at this period. When auto-inferred, shown with hollow marker only.
167
+
168
+ 3. **Post-treatment periods**: The treatment effects of interest. These
169
+ show how the outcome evolved after treatment.
170
+
171
+ The confidence intervals help assess statistical significance. Effects
172
+ whose CIs don't include zero are typically considered significant.
173
+ """
174
+ from scipy import stats as scipy_stats
175
+
176
+ # Track if reference_period was explicitly provided by user
177
+ reference_period_explicit = reference_period is not None
178
+
179
+ # Extract data from results if provided
180
+ ci_lower_override = None
181
+ ci_upper_override = None
182
+ if results is not None:
183
+ (
184
+ effects,
185
+ se,
186
+ periods,
187
+ pre_periods,
188
+ post_periods,
189
+ reference_period,
190
+ reference_inferred,
191
+ ci_lower_override,
192
+ ci_upper_override,
193
+ ) = _extract_plot_data(results, periods, pre_periods, post_periods, reference_period)
194
+ # If reference was inferred from results, it was NOT explicitly provided
195
+ if reference_inferred:
196
+ reference_period_explicit = False
197
+ # Suppress simultaneous confidence band overrides when user opts out
198
+ if not use_cband:
199
+ ci_lower_override = None
200
+ ci_upper_override = None
201
+ elif effects is None or se is None:
202
+ raise ValueError("Must provide either 'results' or both 'effects' and 'se'")
203
+
204
+ # Ensure effects and se are dicts
205
+ if not isinstance(effects, dict):
206
+ raise TypeError("effects must be a dictionary mapping periods to values")
207
+ if not isinstance(se, dict):
208
+ raise TypeError("se must be a dictionary mapping periods to values")
209
+
210
+ # Get periods to plot
211
+ if periods is None:
212
+ periods = sorted(effects.keys())
213
+
214
+ # Compute confidence intervals
215
+ critical_value = scipy_stats.norm.ppf(1 - alpha / 2)
216
+
217
+ # Normalize effects to reference period ONLY if explicitly specified by user
218
+ # Auto-inferred reference periods (from CallawaySantAnna) just get hollow marker styling,
219
+ # NO normalization. This prevents unintended normalization when the reference period
220
+ # isn't a true identifying constraint (e.g., CallawaySantAnna with base_period="varying").
221
+ if reference_period is not None and reference_period in effects and reference_period_explicit:
222
+ ref_effect = effects[reference_period]
223
+ if np.isfinite(ref_effect):
224
+ effects = {p: e - ref_effect for p, e in effects.items()}
225
+ # Set reference SE to NaN (it's now a constraint, not an estimate)
226
+ # This follows fixest convention where the omitted category has no SE/CI
227
+ se = {p: (np.nan if p == reference_period else s) for p, s in se.items()}
228
+
229
+ plot_data = []
230
+ for period in periods:
231
+ effect = effects.get(period, np.nan)
232
+ std_err = se.get(period, np.nan)
233
+
234
+ # Skip entries with NaN effect, but allow NaN SE (will plot without error bars)
235
+ if np.isnan(effect):
236
+ continue
237
+
238
+ # Use cband CI overrides when available, otherwise compute pointwise
239
+ if ci_lower_override is not None and period in ci_lower_override:
240
+ ci_lower = ci_lower_override[period]
241
+ assert ci_upper_override is not None
242
+ ci_upper = ci_upper_override[period]
243
+ elif np.isfinite(std_err):
244
+ ci_lower = effect - critical_value * std_err
245
+ ci_upper = effect + critical_value * std_err
246
+ else:
247
+ ci_lower = np.nan
248
+ ci_upper = np.nan
249
+
250
+ plot_data.append(
251
+ {
252
+ "period": period,
253
+ "effect": effect,
254
+ "se": std_err,
255
+ "ci_lower": ci_lower,
256
+ "ci_upper": ci_upper,
257
+ "is_reference": period == reference_period,
258
+ }
259
+ )
260
+
261
+ if not plot_data:
262
+ raise ValueError("No valid data to plot")
263
+
264
+ df = pd.DataFrame(plot_data)
265
+
266
+ if backend == "plotly":
267
+ return _render_event_study_plotly(
268
+ df,
269
+ reference_period=reference_period,
270
+ pre_periods=pre_periods,
271
+ title=title,
272
+ xlabel=xlabel,
273
+ ylabel=ylabel,
274
+ color=color,
275
+ marker=marker,
276
+ markersize=markersize,
277
+ shade_pre=shade_pre,
278
+ shade_color=shade_color,
279
+ show_zero_line=show_zero_line,
280
+ show_reference_line=show_reference_line,
281
+ show=show,
282
+ )
283
+
284
+ return _render_event_study_mpl(
285
+ df,
286
+ reference_period=reference_period,
287
+ pre_periods=pre_periods,
288
+ figsize=figsize,
289
+ title=title,
290
+ xlabel=xlabel,
291
+ ylabel=ylabel,
292
+ color=color,
293
+ marker=marker,
294
+ markersize=markersize,
295
+ linewidth=linewidth,
296
+ capsize=capsize,
297
+ shade_pre=shade_pre,
298
+ shade_color=shade_color,
299
+ show_zero_line=show_zero_line,
300
+ show_reference_line=show_reference_line,
301
+ ax=ax,
302
+ show=show,
303
+ )
304
+
305
+
306
+ def _render_event_study_mpl(
307
+ df,
308
+ *,
309
+ reference_period,
310
+ pre_periods,
311
+ figsize,
312
+ title,
313
+ xlabel,
314
+ ylabel,
315
+ color,
316
+ marker,
317
+ markersize,
318
+ linewidth,
319
+ capsize,
320
+ shade_pre,
321
+ shade_color,
322
+ show_zero_line,
323
+ show_reference_line,
324
+ ax,
325
+ show,
326
+ ):
327
+ """Render event study plot with matplotlib."""
328
+ from diff_diff.visualization._common import _require_matplotlib
329
+
330
+ plt = _require_matplotlib()
331
+
332
+ # Create figure if needed
333
+ if ax is None:
334
+ fig, ax = plt.subplots(figsize=figsize)
335
+ else:
336
+ fig = ax.get_figure()
337
+
338
+ # Convert periods to numeric for plotting
339
+ period_to_x = {p: i for i, p in enumerate(df["period"])}
340
+ x_vals = [period_to_x[p] for p in df["period"]]
341
+
342
+ # Shade pre-treatment region
343
+ if shade_pre and pre_periods is not None:
344
+ pre_x = [period_to_x[p] for p in pre_periods if p in period_to_x]
345
+ if pre_x:
346
+ ax.axvspan(min(pre_x) - 0.5, max(pre_x) + 0.5, color=shade_color, alpha=0.5, zorder=0)
347
+
348
+ # Draw horizontal zero line
349
+ if show_zero_line:
350
+ ax.axhline(y=0, color="gray", linestyle="--", linewidth=1, zorder=1)
351
+
352
+ # Draw vertical reference line
353
+ if show_reference_line and reference_period is not None:
354
+ if reference_period in period_to_x:
355
+ ref_x = period_to_x[reference_period]
356
+ ax.axvline(x=ref_x, color="gray", linestyle=":", linewidth=1, zorder=1)
357
+
358
+ # Plot error bars (only for entries with finite CI)
359
+ has_ci = df["ci_lower"].notna() & df["ci_upper"].notna()
360
+ if has_ci.any():
361
+ df_with_ci = df[has_ci]
362
+ x_with_ci = [period_to_x[p] for p in df_with_ci["period"]]
363
+ yerr = [
364
+ df_with_ci["effect"] - df_with_ci["ci_lower"],
365
+ df_with_ci["ci_upper"] - df_with_ci["effect"],
366
+ ]
367
+ ax.errorbar(
368
+ x_with_ci,
369
+ df_with_ci["effect"],
370
+ yerr=yerr,
371
+ fmt="none",
372
+ color=color,
373
+ capsize=capsize,
374
+ linewidth=linewidth,
375
+ capthick=linewidth,
376
+ zorder=2,
377
+ )
378
+
379
+ # Plot point estimates
380
+ for i, row in df.iterrows():
381
+ x = period_to_x[row["period"]]
382
+ if row["is_reference"]:
383
+ # Hollow marker for reference period
384
+ ax.plot(
385
+ x,
386
+ row["effect"],
387
+ marker=marker,
388
+ markersize=markersize,
389
+ markerfacecolor="white",
390
+ markeredgecolor=color,
391
+ markeredgewidth=2,
392
+ zorder=3,
393
+ )
394
+ else:
395
+ ax.plot(x, row["effect"], marker=marker, markersize=markersize, color=color, zorder=3)
396
+
397
+ # Set labels and title
398
+ ax.set_xlabel(xlabel)
399
+ ax.set_ylabel(ylabel)
400
+ ax.set_title(title)
401
+
402
+ # Set x-axis ticks
403
+ ax.set_xticks(x_vals)
404
+ ax.set_xticklabels([str(p) for p in df["period"]])
405
+
406
+ # Add grid
407
+ ax.grid(True, alpha=0.3, axis="y")
408
+
409
+ # Tight layout
410
+ fig.tight_layout()
411
+
412
+ if show:
413
+ plt.show()
414
+
415
+ return ax
416
+
417
+
418
+ def _render_event_study_plotly(
419
+ df,
420
+ *,
421
+ reference_period,
422
+ pre_periods,
423
+ title,
424
+ xlabel,
425
+ ylabel,
426
+ color,
427
+ marker,
428
+ markersize,
429
+ shade_pre,
430
+ shade_color,
431
+ show_zero_line,
432
+ show_reference_line,
433
+ show,
434
+ ):
435
+ """Render event study plot with plotly."""
436
+ from diff_diff.visualization._common import (
437
+ _color_to_rgba,
438
+ _mpl_marker_to_plotly_symbol,
439
+ _plotly_default_layout,
440
+ _require_plotly,
441
+ )
442
+
443
+ go = _require_plotly()
444
+
445
+ fig = go.Figure()
446
+
447
+ periods = df["period"].tolist()
448
+ effects = df["effect"].tolist()
449
+ ci_lower = df["ci_lower"].tolist()
450
+ ci_upper = df["ci_upper"].tolist()
451
+ is_ref = df["is_reference"].tolist()
452
+
453
+ # Map periods to ordinal x positions (matching matplotlib renderer).
454
+ # This ensures string, timestamp, and other non-numeric periods work correctly.
455
+ period_to_x = {p: i for i, p in enumerate(periods)}
456
+ x_vals = list(range(len(periods)))
457
+ tick_labels = [str(p) for p in periods]
458
+
459
+ # Shade pre-treatment region
460
+ if shade_pre and pre_periods is not None:
461
+ pre_x = [period_to_x[p] for p in pre_periods if p in period_to_x]
462
+ if pre_x:
463
+ fig.add_vrect(
464
+ x0=min(pre_x) - 0.5,
465
+ x1=max(pre_x) + 0.5,
466
+ fillcolor=_color_to_rgba(shade_color, 0.5),
467
+ line_width=0,
468
+ layer="below",
469
+ )
470
+
471
+ # Zero line
472
+ if show_zero_line:
473
+ fig.add_hline(y=0, line_dash="dash", line_color="gray", line_width=1)
474
+
475
+ # Reference line
476
+ if show_reference_line and reference_period is not None and reference_period in period_to_x:
477
+ fig.add_vline(
478
+ x=period_to_x[reference_period], line_dash="dot", line_color="gray", line_width=1
479
+ )
480
+
481
+ # CI band (filled area)
482
+ has_ci = [not (np.isnan(lo) or np.isnan(hi)) for lo, hi in zip(ci_lower, ci_upper)]
483
+ ci_x = [period_to_x[p] for p, h in zip(periods, has_ci) if h]
484
+ ci_lo = [lo for lo, h in zip(ci_lower, has_ci) if h]
485
+ ci_hi = [hi for hi, h in zip(ci_upper, has_ci) if h]
486
+
487
+ if ci_x:
488
+ fig.add_trace(
489
+ go.Scatter(
490
+ x=ci_x + ci_x[::-1],
491
+ y=ci_hi + ci_lo[::-1],
492
+ fill="toself",
493
+ fillcolor=_color_to_rgba(color, 0.15),
494
+ line=dict(color="rgba(0,0,0,0)"),
495
+ showlegend=False,
496
+ hoverinfo="skip",
497
+ )
498
+ )
499
+
500
+ # Point estimates — separate reference vs non-reference.
501
+ # Attach original period labels via customdata + hovertemplate so hover
502
+ # shows real periods instead of ordinal positions.
503
+ non_ref_x = [period_to_x[p] for p, r in zip(periods, is_ref) if not r]
504
+ non_ref_e = [e for e, r in zip(effects, is_ref) if not r]
505
+ non_ref_labels = [str(p) for p, r in zip(periods, is_ref) if not r]
506
+ ref_x = [period_to_x[p] for p, r in zip(periods, is_ref) if r]
507
+ ref_e = [e for e, r in zip(effects, is_ref) if r]
508
+ ref_labels = [str(p) for p, r in zip(periods, is_ref) if r]
509
+
510
+ hover_tpl = "Period: %{customdata}<br>Effect: %{y:.4f}<extra></extra>"
511
+
512
+ symbol = _mpl_marker_to_plotly_symbol(marker)
513
+
514
+ if non_ref_x:
515
+ fig.add_trace(
516
+ go.Scatter(
517
+ x=non_ref_x,
518
+ y=non_ref_e,
519
+ mode="markers",
520
+ marker=dict(color=color, size=markersize, symbol=symbol),
521
+ name="Effect",
522
+ customdata=non_ref_labels,
523
+ hovertemplate=hover_tpl,
524
+ )
525
+ )
526
+
527
+ if ref_x:
528
+ fig.add_trace(
529
+ go.Scatter(
530
+ x=ref_x,
531
+ y=ref_e,
532
+ mode="markers",
533
+ marker=dict(
534
+ color="white",
535
+ size=markersize,
536
+ symbol=symbol,
537
+ line=dict(color=color, width=2),
538
+ ),
539
+ name="Reference",
540
+ customdata=ref_labels,
541
+ hovertemplate=hover_tpl,
542
+ )
543
+ )
544
+
545
+ # Set tick labels to show original period values
546
+ fig.update_xaxes(tickvals=x_vals, ticktext=tick_labels)
547
+
548
+ _plotly_default_layout(fig, title=title, xlabel=xlabel, ylabel=ylabel)
549
+
550
+ if show:
551
+ fig.show()
552
+
553
+ return fig
554
+
555
+
556
+ def _extract_plot_data(
557
+ results: PlottableResults,
558
+ periods: Optional[List[Any]],
559
+ pre_periods: Optional[List[Any]],
560
+ post_periods: Optional[List[Any]],
561
+ reference_period: Optional[Any],
562
+ ) -> Tuple[Dict, Dict, List, List, List, Any, bool, Optional[Dict], Optional[Dict]]:
563
+ """
564
+ Extract plotting data from various result types.
565
+
566
+ Returns
567
+ -------
568
+ effects : dict
569
+ Mapping of period to effect estimate.
570
+ se : dict
571
+ Mapping of period to standard error.
572
+ periods : list
573
+ Ordered list of periods to plot.
574
+ pre_periods : list
575
+ Pre-treatment periods.
576
+ post_periods : list
577
+ Post-treatment periods.
578
+ reference_period : any
579
+ The reference period (explicit or inferred).
580
+ reference_inferred : bool
581
+ True if reference_period was auto-detected from results
582
+ rather than explicitly provided by the user.
583
+ ci_lower_override : dict or None
584
+ Simultaneous confidence band lower bounds, if available.
585
+ ci_upper_override : dict or None
586
+ Simultaneous confidence band upper bounds, if available.
587
+ """
588
+ # Handle DataFrame input
589
+ if isinstance(results, pd.DataFrame):
590
+ if "period" not in results.columns:
591
+ raise ValueError("DataFrame must have 'period' column")
592
+ if "effect" not in results.columns:
593
+ raise ValueError("DataFrame must have 'effect' column")
594
+ if "se" not in results.columns:
595
+ raise ValueError("DataFrame must have 'se' column")
596
+
597
+ effects = dict(zip(results["period"], results["effect"]))
598
+ se = dict(zip(results["period"], results["se"]))
599
+
600
+ if periods is None:
601
+ periods = list(results["period"])
602
+
603
+ # Extract simultaneous confidence bands if present and finite
604
+ ci_lower_override = None
605
+ ci_upper_override = None
606
+ if "cband_lower" in results.columns and "cband_upper" in results.columns:
607
+ finite_mask = results["cband_lower"].notna() & results["cband_upper"].notna()
608
+ if finite_mask.any():
609
+ finite_rows = results[finite_mask]
610
+ ci_lower_override = dict(zip(finite_rows["period"], finite_rows["cband_lower"]))
611
+ ci_upper_override = dict(zip(finite_rows["period"], finite_rows["cband_upper"]))
612
+
613
+ # DataFrame input: reference_period was already set by caller, never inferred here
614
+ return (
615
+ effects,
616
+ se,
617
+ periods,
618
+ pre_periods,
619
+ post_periods,
620
+ reference_period,
621
+ False,
622
+ ci_lower_override,
623
+ ci_upper_override,
624
+ )
625
+
626
+ # Handle MultiPeriodDiDResults
627
+ if hasattr(results, "period_effects"):
628
+ effects = {}
629
+ se = {}
630
+
631
+ for period, pe in results.period_effects.items():
632
+ effects[period] = pe.effect
633
+ se[period] = pe.se
634
+
635
+ if pre_periods is None and hasattr(results, "pre_periods"):
636
+ pre_periods = results.pre_periods
637
+
638
+ if post_periods is None and hasattr(results, "post_periods"):
639
+ post_periods = results.post_periods
640
+
641
+ if periods is None:
642
+ periods = sorted(results.period_effects.keys())
643
+
644
+ # Auto-detect reference period from results if not explicitly provided
645
+ ref_inferred = False
646
+ if (
647
+ reference_period is None
648
+ and hasattr(results, "reference_period")
649
+ and results.reference_period is not None
650
+ ):
651
+ reference_period = results.reference_period
652
+ ref_inferred = True
653
+
654
+ return (
655
+ effects,
656
+ se,
657
+ periods,
658
+ pre_periods,
659
+ post_periods,
660
+ reference_period,
661
+ ref_inferred,
662
+ None,
663
+ None,
664
+ )
665
+
666
+ # Handle CallawaySantAnnaResults (event study aggregation)
667
+ if hasattr(results, "event_study_effects") and results.event_study_effects is not None:
668
+ effects = {}
669
+ se = {}
670
+ ci_lower_override = {}
671
+ ci_upper_override = {}
672
+ has_cband = False
673
+
674
+ for rel_period, effect_data in results.event_study_effects.items():
675
+ effects[rel_period] = effect_data["effect"]
676
+ se[rel_period] = effect_data["se"]
677
+ # Use simultaneous CIs when available
678
+ if "cband_conf_int" in effect_data:
679
+ cband_ci = effect_data["cband_conf_int"]
680
+ ci_lower_override[rel_period] = cband_ci[0]
681
+ ci_upper_override[rel_period] = cband_ci[1]
682
+ has_cband = True
683
+
684
+ if periods is None:
685
+ periods = sorted(effects.keys())
686
+
687
+ # Track if reference_period was explicitly provided vs auto-inferred
688
+ reference_inferred = False
689
+
690
+ # Reference period is typically -1 for event study
691
+ if reference_period is None:
692
+ reference_inferred = True # We're about to infer it
693
+ # Detect reference period from n_groups=0 marker (normalization constraint)
694
+ # This handles anticipation > 0 where reference is at e = -1 - anticipation
695
+ for period, effect_data in results.event_study_effects.items():
696
+ if effect_data.get("n_groups", 1) == 0 or effect_data.get("n_obs", 1) == 0:
697
+ reference_period = period
698
+ break
699
+ # Fallback to -1 if no marker found (backward compatibility)
700
+ if reference_period is None:
701
+ reference_period = -1
702
+
703
+ if pre_periods is None:
704
+ pre_periods = [p for p in periods if p < 0]
705
+
706
+ if post_periods is None:
707
+ post_periods = [p for p in periods if p >= 0]
708
+
709
+ return (
710
+ effects,
711
+ se,
712
+ periods,
713
+ pre_periods,
714
+ post_periods,
715
+ reference_period,
716
+ reference_inferred,
717
+ ci_lower_override if has_cband else None,
718
+ ci_upper_override if has_cband else None,
719
+ )
720
+
721
+ raise TypeError(
722
+ f"Cannot extract plot data from {type(results).__name__}. "
723
+ "Expected MultiPeriodDiDResults, CallawaySantAnnaResults, "
724
+ "SunAbrahamResults, ImputationDiDResults, or DataFrame."
725
+ )
726
+
727
+
728
+ def plot_honest_event_study(
729
+ honest_results: "HonestDiDResults",
730
+ *,
731
+ periods: Optional[List[Any]] = None,
732
+ reference_period: Optional[Any] = None,
733
+ figsize: Tuple[float, float] = (10, 6),
734
+ title: str = "Event Study with Honest Confidence Intervals",
735
+ xlabel: str = "Period Relative to Treatment",
736
+ ylabel: str = "Treatment Effect",
737
+ original_color: str = "#6b7280",
738
+ honest_color: str = "#2563eb",
739
+ marker: str = "o",
740
+ markersize: int = 8,
741
+ capsize: int = 4,
742
+ ax: Optional[Any] = None,
743
+ show: bool = True,
744
+ backend: str = "matplotlib",
745
+ ) -> Any:
746
+ """
747
+ Create event study plot with Honest DiD confidence intervals.
748
+
749
+ Shows both the original confidence intervals (assuming parallel trends)
750
+ and the robust confidence intervals that allow for bounded violations.
751
+
752
+ Parameters
753
+ ----------
754
+ honest_results : HonestDiDResults
755
+ Results from HonestDiD.fit() that include event_study_bounds.
756
+ periods : list, optional
757
+ Periods to plot. If None, uses all available periods.
758
+ reference_period : any, optional
759
+ Reference period to show as hollow marker.
760
+ figsize : tuple, default=(10, 6)
761
+ Figure size.
762
+ title : str
763
+ Plot title.
764
+ xlabel : str
765
+ X-axis label.
766
+ ylabel : str
767
+ Y-axis label.
768
+ original_color : str
769
+ Color for original (standard) confidence intervals.
770
+ honest_color : str
771
+ Color for honest (robust) confidence intervals.
772
+ marker : str
773
+ Marker style.
774
+ markersize : int
775
+ Marker size.
776
+ capsize : int
777
+ Error bar cap size.
778
+ ax : matplotlib.axes.Axes, optional
779
+ Axes to plot on.
780
+ show : bool, default=True
781
+ Whether to call plt.show().
782
+ backend : str, default="matplotlib"
783
+ Plotting backend: ``"matplotlib"`` or ``"plotly"``.
784
+
785
+ Returns
786
+ -------
787
+ matplotlib.axes.Axes or plotly.graph_objects.Figure
788
+ The axes object (matplotlib) or figure (plotly).
789
+
790
+ Notes
791
+ -----
792
+ This function requires the HonestDiDResults to have been computed
793
+ with event_study_bounds. If only a scalar bound was computed,
794
+ use plot_sensitivity() instead.
795
+ """
796
+ from scipy import stats as scipy_stats
797
+
798
+ # Get original results for standard CIs
799
+ original_results = honest_results.original_results
800
+ if original_results is None:
801
+ raise ValueError("HonestDiDResults must have original_results to plot event study")
802
+
803
+ # Extract data from original results
804
+ if hasattr(original_results, "period_effects"):
805
+ # MultiPeriodDiDResults
806
+ effects_dict = {p: pe.effect for p, pe in original_results.period_effects.items()}
807
+ se_dict = {p: pe.se for p, pe in original_results.period_effects.items()}
808
+ if periods is None:
809
+ periods = list(original_results.period_effects.keys())
810
+ elif hasattr(original_results, "event_study_effects"):
811
+ # CallawaySantAnnaResults
812
+ effects_dict = {
813
+ t: data["effect"] for t, data in original_results.event_study_effects.items()
814
+ }
815
+ se_dict = {t: data["se"] for t, data in original_results.event_study_effects.items()}
816
+ if periods is None:
817
+ periods = sorted(original_results.event_study_effects.keys())
818
+ else:
819
+ raise TypeError("Cannot extract event study data from original_results")
820
+
821
+ # Compute CIs
822
+ alpha_val = honest_results.alpha
823
+ z = scipy_stats.norm.ppf(1 - alpha_val / 2)
824
+
825
+ effects = [effects_dict[p] for p in periods]
826
+ original_ci_lower = [effects_dict[p] - z * se_dict[p] for p in periods]
827
+ original_ci_upper = [effects_dict[p] + z * se_dict[p] for p in periods]
828
+
829
+ # Get honest bounds if available for each period
830
+ if honest_results.event_study_bounds:
831
+ honest_ci_lower = [honest_results.event_study_bounds[p]["ci_lb"] for p in periods]
832
+ honest_ci_upper = [honest_results.event_study_bounds[p]["ci_ub"] for p in periods]
833
+ else:
834
+ # Use scalar bounds applied to all periods
835
+ honest_ci_lower = [honest_results.ci_lb] * len(periods)
836
+ honest_ci_upper = [honest_results.ci_ub] * len(periods)
837
+
838
+ if backend == "plotly":
839
+ return _render_honest_event_study_plotly(
840
+ periods=periods,
841
+ effects=effects,
842
+ original_ci_lower=original_ci_lower,
843
+ original_ci_upper=original_ci_upper,
844
+ honest_ci_lower=honest_ci_lower,
845
+ honest_ci_upper=honest_ci_upper,
846
+ honest_M=honest_results.M,
847
+ reference_period=reference_period,
848
+ title=title,
849
+ xlabel=xlabel,
850
+ ylabel=ylabel,
851
+ original_color=original_color,
852
+ honest_color=honest_color,
853
+ marker=marker,
854
+ markersize=markersize,
855
+ show=show,
856
+ )
857
+
858
+ return _render_honest_event_study_mpl(
859
+ periods=periods,
860
+ effects=effects,
861
+ original_ci_lower=original_ci_lower,
862
+ original_ci_upper=original_ci_upper,
863
+ honest_ci_lower=honest_ci_lower,
864
+ honest_ci_upper=honest_ci_upper,
865
+ honest_M=honest_results.M,
866
+ reference_period=reference_period,
867
+ figsize=figsize,
868
+ title=title,
869
+ xlabel=xlabel,
870
+ ylabel=ylabel,
871
+ original_color=original_color,
872
+ honest_color=honest_color,
873
+ marker=marker,
874
+ markersize=markersize,
875
+ capsize=capsize,
876
+ ax=ax,
877
+ show=show,
878
+ )
879
+
880
+
881
+ def _render_honest_event_study_mpl(
882
+ *,
883
+ periods,
884
+ effects,
885
+ original_ci_lower,
886
+ original_ci_upper,
887
+ honest_ci_lower,
888
+ honest_ci_upper,
889
+ honest_M,
890
+ reference_period,
891
+ figsize,
892
+ title,
893
+ xlabel,
894
+ ylabel,
895
+ original_color,
896
+ honest_color,
897
+ marker,
898
+ markersize,
899
+ capsize,
900
+ ax,
901
+ show,
902
+ ):
903
+ """Render honest event study plot with matplotlib."""
904
+ from diff_diff.visualization._common import _require_matplotlib
905
+
906
+ plt = _require_matplotlib()
907
+
908
+ # Create figure
909
+ if ax is None:
910
+ fig, ax = plt.subplots(figsize=figsize)
911
+ else:
912
+ fig = ax.get_figure()
913
+
914
+ x_vals = list(range(len(periods)))
915
+
916
+ # Zero line
917
+ ax.axhline(y=0, color="gray", linestyle="--", linewidth=1, alpha=0.5)
918
+
919
+ # Plot original CIs (thinner, background)
920
+ yerr_orig = [
921
+ [e - lower for e, lower in zip(effects, original_ci_lower)],
922
+ [u - e for e, u in zip(effects, original_ci_upper)],
923
+ ]
924
+ ax.errorbar(
925
+ x_vals,
926
+ effects,
927
+ yerr=yerr_orig,
928
+ fmt="none",
929
+ color=original_color,
930
+ capsize=capsize - 1,
931
+ linewidth=1,
932
+ alpha=0.6,
933
+ label="Standard CI",
934
+ )
935
+
936
+ # Plot honest CIs (thicker, foreground)
937
+ yerr_honest = [
938
+ [e - lower for e, lower in zip(effects, honest_ci_lower)],
939
+ [u - e for e, u in zip(effects, honest_ci_upper)],
940
+ ]
941
+ ax.errorbar(
942
+ x_vals,
943
+ effects,
944
+ yerr=yerr_honest,
945
+ fmt="none",
946
+ color=honest_color,
947
+ capsize=capsize,
948
+ linewidth=2,
949
+ label=f"Honest CI (M={honest_M:.2f})",
950
+ )
951
+
952
+ # Plot point estimates
953
+ for i, (x, effect, period) in enumerate(zip(x_vals, effects, periods)):
954
+ is_ref = period == reference_period
955
+ if is_ref:
956
+ ax.plot(
957
+ x,
958
+ effect,
959
+ marker=marker,
960
+ markersize=markersize,
961
+ markerfacecolor="white",
962
+ markeredgecolor=honest_color,
963
+ markeredgewidth=2,
964
+ zorder=3,
965
+ )
966
+ else:
967
+ ax.plot(x, effect, marker=marker, markersize=markersize, color=honest_color, zorder=3)
968
+
969
+ ax.set_xlabel(xlabel)
970
+ ax.set_ylabel(ylabel)
971
+ ax.set_title(title)
972
+ ax.set_xticks(x_vals)
973
+ ax.set_xticklabels([str(p) for p in periods])
974
+ ax.legend(loc="best")
975
+ ax.grid(True, alpha=0.3, axis="y")
976
+
977
+ fig.tight_layout()
978
+
979
+ if show:
980
+ plt.show()
981
+
982
+ return ax
983
+
984
+
985
+ def _render_honest_event_study_plotly(
986
+ *,
987
+ periods,
988
+ effects,
989
+ original_ci_lower,
990
+ original_ci_upper,
991
+ honest_ci_lower,
992
+ honest_ci_upper,
993
+ honest_M,
994
+ reference_period,
995
+ title,
996
+ xlabel,
997
+ ylabel,
998
+ original_color,
999
+ honest_color,
1000
+ marker,
1001
+ markersize,
1002
+ show,
1003
+ ):
1004
+ """Render honest event study plot with plotly."""
1005
+ from diff_diff.visualization._common import (
1006
+ _color_to_rgba,
1007
+ _mpl_marker_to_plotly_symbol,
1008
+ _plotly_default_layout,
1009
+ _require_plotly,
1010
+ )
1011
+
1012
+ go = _require_plotly()
1013
+
1014
+ fig = go.Figure()
1015
+
1016
+ # Zero line
1017
+ fig.add_hline(y=0, line_dash="dash", line_color="gray", line_width=1, opacity=0.5)
1018
+
1019
+ # Original CI band
1020
+ fig.add_trace(
1021
+ go.Scatter(
1022
+ x=list(periods) + list(periods)[::-1],
1023
+ y=list(original_ci_upper) + list(original_ci_lower)[::-1],
1024
+ fill="toself",
1025
+ fillcolor=_color_to_rgba(original_color, 0.15),
1026
+ line=dict(color="rgba(0,0,0,0)"),
1027
+ name="Standard CI",
1028
+ hoverinfo="skip",
1029
+ )
1030
+ )
1031
+
1032
+ # Honest CI band
1033
+ fig.add_trace(
1034
+ go.Scatter(
1035
+ x=list(periods) + list(periods)[::-1],
1036
+ y=list(honest_ci_upper) + list(honest_ci_lower)[::-1],
1037
+ fill="toself",
1038
+ fillcolor=_color_to_rgba(honest_color, 0.15),
1039
+ line=dict(color="rgba(0,0,0,0)"),
1040
+ name=f"Honest CI (M={honest_M:.2f})",
1041
+ hoverinfo="skip",
1042
+ )
1043
+ )
1044
+
1045
+ # Point estimates
1046
+ is_ref = [p == reference_period for p in periods]
1047
+ non_ref_p = [p for p, r in zip(periods, is_ref) if not r]
1048
+ non_ref_e = [e for e, r in zip(effects, is_ref) if not r]
1049
+ ref_p = [p for p, r in zip(periods, is_ref) if r]
1050
+ ref_e = [e for e, r in zip(effects, is_ref) if r]
1051
+
1052
+ symbol = _mpl_marker_to_plotly_symbol(marker)
1053
+
1054
+ if non_ref_p:
1055
+ fig.add_trace(
1056
+ go.Scatter(
1057
+ x=non_ref_p,
1058
+ y=non_ref_e,
1059
+ mode="markers",
1060
+ marker=dict(color=honest_color, size=markersize, symbol=symbol),
1061
+ name="Effect",
1062
+ )
1063
+ )
1064
+
1065
+ if ref_p:
1066
+ fig.add_trace(
1067
+ go.Scatter(
1068
+ x=ref_p,
1069
+ y=ref_e,
1070
+ mode="markers",
1071
+ marker=dict(
1072
+ color="white",
1073
+ size=markersize,
1074
+ symbol=symbol,
1075
+ line=dict(color=honest_color, width=2),
1076
+ ),
1077
+ name="Reference",
1078
+ )
1079
+ )
1080
+
1081
+ _plotly_default_layout(fig, title=title, xlabel=xlabel, ylabel=ylabel)
1082
+
1083
+ if show:
1084
+ fig.show()
1085
+
1086
+ return fig