Note
-
Download Jupyter notebook:
https://docs.doubleml.org/stable/examples/did/py_panel.ipynb.
Python: Panel Data with Multiple Time Periods#
In this example, a detailed guide on Difference-in-Differences with multiple time periods using the DoubleML-package. The implementation is based on Callaway and Sant’Anna(2021).
The notebook requires the following packages:
[1]:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from lightgbm import LGBMRegressor, LGBMClassifier
from sklearn.linear_model import LinearRegression, LogisticRegression
from doubleml.did import DoubleMLDIDMulti
from doubleml.data import DoubleMLPanelData
from doubleml.did.datasets import make_did_CS2021
Data#
We will rely on the make_did_CS2021
DGP, which is inspired by Callaway and Sant’Anna(2021) (Appendix SC) and Sant’Anna and Zhao (2020).
We will observe n_obs
units over n_periods
. Remark that the dataframe includes observations of the potential outcomes y0
and y1
, such that we can use oracle estimates as comparisons.
[2]:
n_obs = 5000
n_periods = 6
df = make_did_CS2021(n_obs, dgp_type=4, n_periods=n_periods, n_pre_treat_periods=3, time_type="datetime")
df["ite"] = df["y1"] - df["y0"]
print(df.shape)
df.head()
(30000, 11)
[2]:
id | y | y0 | y1 | d | t | Z1 | Z2 | Z3 | Z4 | ite | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 213.744689 | 213.744689 | 212.208360 | NaT | 2025-01-01 | -0.61784 | -0.019051 | -1.009152 | -0.507379 | -1.536328 |
1 | 0 | 213.150467 | 213.150467 | 214.613514 | NaT | 2025-02-01 | -0.61784 | -0.019051 | -1.009152 | -0.507379 | 1.463046 |
2 | 0 | 215.528680 | 215.528680 | 214.824800 | NaT | 2025-03-01 | -0.61784 | -0.019051 | -1.009152 | -0.507379 | -0.703880 |
3 | 0 | 215.570707 | 215.570707 | 215.525804 | NaT | 2025-04-01 | -0.61784 | -0.019051 | -1.009152 | -0.507379 | -0.044903 |
4 | 0 | 216.219067 | 216.219067 | 218.254971 | NaT | 2025-05-01 | -0.61784 | -0.019051 | -1.009152 | -0.507379 | 2.035904 |
Data Details#
Here, we slightly abuse the definition of the potential outcomes. :math:`Y_{i,t}(1)` corresponds to the (potential) outcome if unit :math:`i` would have received treatment at time period :math:`mathrm{g}` (where the group :math:`mathrm{g}` is drawn with probabilities based on :math:`Z`).
More specifically
where
\(f_t(Z)\) depends on pre-treatment observable covariates \(Z_1,\dots, Z_4\) and time \(t\)
\(\delta_t\) is a time fixed effect
\(\eta_i\) is a unit fixed effect
\(\epsilon_{i,t,\cdot}\) are time varying unobservables (iid. \(N(0,1)\))
\(\theta_{i,t,\mathrm{g}}\) correponds to the exposure effect of unit \(i\) based on group \(\mathrm{g}\) at time \(t\)
For the pre-treatment periods the exposure effect is set to
such that
The DoubleML Coverage Repository includes coverage simulations based on this DGP.
Data Description#
The data is a balanced panel where each unit is observed over n_periods
starting Janary 2025.
[3]:
df.groupby("t").size()
[3]:
t
2025-01-01 5000
2025-02-01 5000
2025-03-01 5000
2025-04-01 5000
2025-05-01 5000
2025-06-01 5000
dtype: int64
The treatment column d
indicates first treatment period of the corresponding unit, whereas NaT
units are never treated.
Generally, never treated units should take either on the value ``np.inf`` or ``pd.NaT`` depending on the data type (``float`` or ``datetime``).
The individual units are roughly uniformly divided between the groups, where treatment assignment depends on the pre-treatment covariates Z1
to Z4
.
[4]:
df.groupby("d", dropna=False).size()
[4]:
d
2025-04-01 7872
2025-05-01 7332
2025-06-01 7104
NaT 7692
dtype: int64
Here, the group indicates the first treated period and NaT
units are never treated. To simplify plotting and pands
[5]:
df.groupby("d", dropna=False).size()
[5]:
d
2025-04-01 7872
2025-05-01 7332
2025-06-01 7104
NaT 7692
dtype: int64
To get a better understanding of the underlying data and true effects, we will compare the unconditional averages and the true effects based on the oracle values of individual effects ite
.
[6]:
# rename for plotting
df["First Treated"] = df["d"].dt.strftime("%Y-%m").fillna("Never Treated")
# Create aggregation dictionary for means
def agg_dict(col_name):
return {
f'{col_name}_mean': (col_name, 'mean'),
f'{col_name}_lower_quantile': (col_name, lambda x: x.quantile(0.05)),
f'{col_name}_upper_quantile': (col_name, lambda x: x.quantile(0.95))
}
# Calculate means and confidence intervals
agg_dictionary = agg_dict("y") | agg_dict("ite")
agg_df = df.groupby(["t", "First Treated"]).agg(**agg_dictionary).reset_index()
agg_df.head()
[6]:
t | First Treated | y_mean | y_lower_quantile | y_upper_quantile | ite_mean | ite_lower_quantile | ite_upper_quantile | |
---|---|---|---|---|---|---|---|---|
0 | 2025-01-01 | 2025-04 | 208.802201 | 198.885207 | 218.587994 | 0.016866 | -2.288279 | 2.348429 |
1 | 2025-01-01 | 2025-05 | 210.275671 | 200.178191 | 220.086135 | 0.030629 | -2.342559 | 2.282605 |
2 | 2025-01-01 | 2025-06 | 212.132245 | 202.467266 | 221.896647 | 0.013908 | -2.295165 | 2.340990 |
3 | 2025-01-01 | Never Treated | 214.344418 | 203.878086 | 225.340213 | -0.026640 | -2.329972 | 2.290511 |
4 | 2025-02-01 | 2025-04 | 208.657120 | 189.644381 | 227.679744 | -0.051396 | -2.466918 | 2.260057 |
[7]:
def plot_data(df, col_name='y'):
"""
Create an improved plot with colorblind-friendly features
Parameters:
-----------
df : DataFrame
The dataframe containing the data
col_name : str, default='y'
Column name to plot (will use '{col_name}_mean')
"""
plt.figure(figsize=(12, 7))
n_colors = df["First Treated"].nunique()
color_palette = sns.color_palette("colorblind", n_colors=n_colors)
sns.lineplot(
data=df,
x='t',
y=f'{col_name}_mean',
hue='First Treated',
style='First Treated',
palette=color_palette,
markers=True,
dashes=True,
linewidth=2.5,
alpha=0.8
)
plt.title(f'Average Values {col_name} by Group Over Time', fontsize=16)
plt.xlabel('Time', fontsize=14)
plt.ylabel(f'Average Value {col_name}', fontsize=14)
plt.legend(title='First Treated', title_fontsize=13, fontsize=12,
frameon=True, framealpha=0.9, loc='best')
plt.grid(alpha=0.3, linestyle='-')
plt.tight_layout()
plt.show()
So let us take a look at the average values over time
[8]:
plot_data(agg_df, col_name='y')

Instead the true average treatment treatment effects can be obtained by averaging (usually unobserved) the ite
values.
The true effect just equals the exposure time (in months):
[9]:
plot_data(agg_df, col_name='ite')

DoubleMLPanelData#
Finally, we can construct our DoubleMLPanelData
, specifying
y_col
: the outcomed_cols
: the group variable indicating the first treated period for each unitid_col
: the unique identification column for each unitt_col
: the time columnx_cols
: the additional pre-treatment controlsdatetime_unit
: unit required fordatetime
columns and plotting
[10]:
dml_data = DoubleMLPanelData(
data=df,
y_col="y",
d_cols="d",
id_col="id",
t_col="t",
x_cols=["Z1", "Z2", "Z3", "Z4"],
datetime_unit="M"
)
print(dml_data)
================== DoubleMLPanelData Object ==================
------------------ Data summary ------------------
Outcome variable: y
Treatment variable(s): ['d']
Covariates: ['Z1', 'Z2', 'Z3', 'Z4']
Instrument variable(s): None
Time variable: t
Id variable: id
No. Observations: 5000
------------------ DataFrame info ------------------
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 30000 entries, 0 to 29999
Columns: 12 entries, id to First Treated
dtypes: datetime64[s](2), float64(8), int64(1), object(1)
memory usage: 2.7+ MB
ATT Estimation#
The DoubleML-package implements estimation of group-time average treatment effect via the DoubleMLDIDMulti
class (see model documentation).
Basics#
The class basically behaves like other DoubleML
classes and requires the specification of two learners (for more details on the regression elements, see score documentation).
The basic arguments of a DoubleMLDIDMulti
object include
ml_g
“outcome” regression learnerml_m
propensity Score learnercontrol_group
the control group for the parallel trend assumptiongt_combinations
combinations of \((\mathrm{g},t_\text{pre}, t_\text{eval})\)anticipation_periods
number of anticipation periods
We will construct a dict
with “default” arguments.
[11]:
default_args = {
"ml_g": LGBMRegressor(n_estimators=500, learning_rate=0.01, verbose=-1, random_state=123),
"ml_m": LGBMClassifier(n_estimators=500, learning_rate=0.01, verbose=-1, random_state=123),
"control_group": "never_treated",
"gt_combinations": "standard",
"anticipation_periods": 0,
"n_folds": 5,
"n_rep": 1,
}
The model will be estimated using the fit()
method.
[12]:
dml_obj = DoubleMLDIDMulti(dml_data, **default_args)
dml_obj.fit()
print(dml_obj)
================== DoubleMLDIDMulti Object ==================
------------------ Data summary ------------------
Outcome variable: y
Treatment variable(s): ['d']
Covariates: ['Z1', 'Z2', 'Z3', 'Z4']
Instrument variable(s): None
Time variable: t
Id variable: id
No. Observations: 5000
------------------ Score & algorithm ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
------------------ Machine learner ------------------
Learner ml_g: LGBMRegressor(learning_rate=0.01, n_estimators=500, random_state=123,
verbose=-1)
Learner ml_m: LGBMClassifier(learning_rate=0.01, n_estimators=500, random_state=123,
verbose=-1)
Out-of-sample Performance:
Regression:
Learner ml_g0 RMSE: [[1.94840552 1.98399144 1.89214907 2.86883342 3.86247065 1.95262806
2.02013742 1.85234351 1.94860613 2.96309975 1.92811018 1.96679584
1.86703441 1.98143076 1.991845 ]]
Learner ml_g1 RMSE: [[1.95948692 1.94667221 1.89861168 2.7797047 3.90313274 1.9507364
1.96113075 1.99140823 1.9028925 2.87714619 1.96745993 1.88393996
1.90302166 1.91001138 1.88390139]]
Classification:
Learner ml_m Log Loss: [[0.67980345 0.67161113 0.67838213 0.67656674 0.68066756 0.71322008
0.70390324 0.70375981 0.70596816 0.70075582 0.72802973 0.72613435
0.72646837 0.72263499 0.72185641]]
------------------ Resampling ------------------
No. folds: 5
No. repeated sample splits: 1
------------------ Fit summary ------------------
coef std err t P>|t| \
ATT(2025-04,2025-01,2025-02) 0.062371 0.138731 0.449579 6.530138e-01
ATT(2025-04,2025-02,2025-03) -0.057230 0.110253 -0.519080 6.037053e-01
ATT(2025-04,2025-03,2025-04) 0.973259 0.117646 8.272778 2.220446e-16
ATT(2025-04,2025-03,2025-05) 1.998808 0.199648 10.011653 0.000000e+00
ATT(2025-04,2025-03,2025-06) 2.956115 0.279151 10.589672 0.000000e+00
ATT(2025-05,2025-01,2025-02) 0.076977 0.110079 0.699286 4.843734e-01
ATT(2025-05,2025-02,2025-03) -0.220500 0.126290 -1.745982 8.081402e-02
ATT(2025-05,2025-03,2025-04) -0.011274 0.098512 -0.114447 9.088832e-01
ATT(2025-05,2025-04,2025-05) 0.864523 0.109679 7.882307 3.108624e-15
ATT(2025-05,2025-04,2025-06) 2.168677 0.188250 11.520171 0.000000e+00
ATT(2025-06,2025-01,2025-02) 0.121206 0.109693 1.104956 2.691788e-01
ATT(2025-06,2025-02,2025-03) -0.044786 0.089996 -0.497647 6.187331e-01
ATT(2025-06,2025-03,2025-04) -0.020597 0.092442 -0.222814 8.236801e-01
ATT(2025-06,2025-04,2025-05) -0.011044 0.100881 -0.109473 9.128270e-01
ATT(2025-06,2025-05,2025-06) 1.147511 0.088119 13.022325 0.000000e+00
2.5 % 97.5 %
ATT(2025-04,2025-01,2025-02) -0.209537 0.334279
ATT(2025-04,2025-02,2025-03) -0.273322 0.158862
ATT(2025-04,2025-03,2025-04) 0.742677 1.203841
ATT(2025-04,2025-03,2025-05) 1.607505 2.390111
ATT(2025-04,2025-03,2025-06) 2.408990 3.503241
ATT(2025-05,2025-01,2025-02) -0.138774 0.292728
ATT(2025-05,2025-02,2025-03) -0.468023 0.027024
ATT(2025-05,2025-03,2025-04) -0.204355 0.181806
ATT(2025-05,2025-04,2025-05) 0.649556 1.079489
ATT(2025-05,2025-04,2025-06) 1.799713 2.537641
ATT(2025-06,2025-01,2025-02) -0.093788 0.336200
ATT(2025-06,2025-02,2025-03) -0.221175 0.131602
ATT(2025-06,2025-03,2025-04) -0.201781 0.160586
ATT(2025-06,2025-04,2025-05) -0.208766 0.186679
ATT(2025-06,2025-05,2025-06) 0.974801 1.320220
The summary displays estimates of the \(ATT(g,t_\text{eval})\) effects for different combinations of \((g,t_\text{eval})\) via \(\widehat{ATT}(\mathrm{g},t_\text{pre},t_\text{eval})\), where
\(\mathrm{g}\) specifies the group
\(t_\text{pre}\) specifies the corresponding pre-treatment period
\(t_\text{eval}\) specifies the evaluation period
The choice gt_combinations="standard"
, used estimates all possible combinations of \(ATT(g,t_\text{eval})\) via \(\widehat{ATT}(\mathrm{g},t_\text{pre},t_\text{eval})\), where the standard choice is \(t_\text{pre} = \min(\mathrm{g}, t_\text{eval}) - 1\) (without anticipation).
Remark that this includes pre-tests effects if \(\mathrm{g} > t_{eval}\), e.g. \(\widehat{ATT}(g=\text{2025-04}, t_{\text{pre}}=\text{2025-01}, t_{\text{eval}}=\text{2025-02})\) which estimates the pre-trend from January to February even if the actual treatment occured in April.
As usual for the DoubleML-package, you can obtain joint confidence intervals via bootstrap.
[13]:
level = 0.95
ci = dml_obj.confint(level=level)
dml_obj.bootstrap(n_rep_boot=5000)
ci_joint = dml_obj.confint(level=level, joint=True)
ci_joint
[13]:
2.5 % | 97.5 % | |
---|---|---|
ATT(2025-04,2025-01,2025-02) | -0.334732 | 0.459473 |
ATT(2025-04,2025-02,2025-03) | -0.372817 | 0.258357 |
ATT(2025-04,2025-03,2025-04) | 0.636511 | 1.310008 |
ATT(2025-04,2025-03,2025-05) | 1.427337 | 2.570279 |
ATT(2025-04,2025-03,2025-06) | 2.157077 | 3.755154 |
ATT(2025-05,2025-01,2025-02) | -0.238112 | 0.392066 |
ATT(2025-05,2025-02,2025-03) | -0.581990 | 0.140991 |
ATT(2025-05,2025-03,2025-04) | -0.293255 | 0.270706 |
ATT(2025-05,2025-04,2025-05) | 0.550579 | 1.178466 |
ATT(2025-05,2025-04,2025-06) | 1.629831 | 2.707523 |
ATT(2025-06,2025-01,2025-02) | -0.192778 | 0.435189 |
ATT(2025-06,2025-02,2025-03) | -0.302389 | 0.212817 |
ATT(2025-06,2025-03,2025-04) | -0.285203 | 0.244009 |
ATT(2025-06,2025-04,2025-05) | -0.299804 | 0.277716 |
ATT(2025-06,2025-05,2025-06) | 0.895280 | 1.399741 |
A visualization of the effects can be obtained via the plot_effects()
method.
Remark that the plot used joint confidence intervals per default.
[14]:
dml_obj.plot_effects()
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
return math.isfinite(val)
[14]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])

Sensitivity Analysis#
As descripted in the Sensitivity Guide, robustness checks on omitted confounding/parallel trend violations are available, via the standard sensitivity_analysis()
method.
[15]:
dml_obj.sensitivity_analysis()
print(dml_obj.sensitivity_summary)
================== Sensitivity Analysis ==================
------------------ Scenario ------------------
Significance Level: level=0.95
Sensitivity parameters: cf_y=0.03; cf_d=0.03, rho=1.0
------------------ Bounds with CI ------------------
CI lower theta lower theta theta upper \
ATT(2025-04,2025-01,2025-02) -0.334356 0.023206 0.062371 0.101535
ATT(2025-04,2025-02,2025-03) -0.339526 -0.164613 -0.057230 0.050152
ATT(2025-04,2025-03,2025-04) 0.702307 0.884769 0.973259 1.061750
ATT(2025-04,2025-03,2025-05) 1.533188 1.847653 1.998808 2.149963
ATT(2025-04,2025-03,2025-06) 2.322367 2.800281 2.956115 3.111949
ATT(2025-05,2025-01,2025-02) -0.195116 -0.017968 0.076977 0.171921
ATT(2025-05,2025-02,2025-03) -0.517438 -0.310907 -0.220500 -0.130092
ATT(2025-05,2025-03,2025-04) -0.277160 -0.116965 -0.011274 0.094416
ATT(2025-05,2025-04,2025-05) 0.587129 0.765580 0.864523 0.963465
ATT(2025-05,2025-04,2025-06) 1.729485 2.031619 2.168677 2.305735
ATT(2025-06,2025-01,2025-02) -0.153862 0.019776 0.121206 0.222636
ATT(2025-06,2025-02,2025-03) -0.291811 -0.146191 -0.044786 0.056619
ATT(2025-06,2025-03,2025-04) -0.268853 -0.119523 -0.020597 0.078328
ATT(2025-06,2025-04,2025-05) -0.275587 -0.113897 -0.011044 0.091810
ATT(2025-06,2025-05,2025-06) 0.900118 1.043827 1.147511 1.251194
CI upper
ATT(2025-04,2025-01,2025-02) 0.372233
ATT(2025-04,2025-02,2025-03) 0.241258
ATT(2025-04,2025-03,2025-04) 1.273295
ATT(2025-04,2025-03,2025-05) 2.494716
ATT(2025-04,2025-03,2025-06) 3.590625
ATT(2025-05,2025-01,2025-02) 0.358822
ATT(2025-05,2025-02,2025-03) 0.082558
ATT(2025-05,2025-03,2025-04) 0.259316
ATT(2025-05,2025-04,2025-05) 1.147529
ATT(2025-05,2025-04,2025-06) 2.628883
ATT(2025-06,2025-01,2025-02) 0.410756
ATT(2025-06,2025-02,2025-03) 0.207771
ATT(2025-06,2025-03,2025-04) 0.233776
ATT(2025-06,2025-04,2025-05) 0.262867
ATT(2025-06,2025-05,2025-06) 1.398279
------------------ Robustness Values ------------------
H_0 RV (%) RVa (%)
ATT(2025-04,2025-01,2025-02) 0.0 4.734747 0.000597
ATT(2025-04,2025-02,2025-03) 0.0 1.610392 0.000607
ATT(2025-04,2025-03,2025-04) 0.0 28.356788 20.811795
ATT(2025-04,2025-03,2025-05) 0.0 32.975942 28.178920
ATT(2025-04,2025-03,2025-06) 0.0 43.451569 26.040615
ATT(2025-05,2025-01,2025-02) 0.0 2.439370 0.000387
ATT(2025-05,2025-02,2025-03) 0.0 7.158311 0.414080
ATT(2025-05,2025-03,2025-04) 0.0 0.324249 0.000607
ATT(2025-05,2025-04,2025-05) 0.0 23.308064 18.473491
ATT(2025-05,2025-04,2025-06) 0.0 37.962408 30.176759
ATT(2025-06,2025-01,2025-02) 0.0 3.574332 0.000609
ATT(2025-06,2025-02,2025-03) 0.0 1.336410 0.000604
ATT(2025-06,2025-03,2025-04) 0.0 0.632372 0.000590
ATT(2025-06,2025-04,2025-05) 0.0 0.326372 0.000555
ATT(2025-06,2025-05,2025-06) 0.0 28.505020 24.921347
In this example one can clearly, distinguish the robustness of the non-zero effects vs. the pre-treatment periods.
Control Groups#
The current implementation support the following control groups
"never_treated"
"not_yet_treated"
Remark that the ``”not_yet_treated” depends on anticipation.
For differences and recommendations, we refer to Callaway and Sant’Anna(2021).
[16]:
dml_obj_nyt = DoubleMLDIDMulti(dml_data, **(default_args | {"control_group": "not_yet_treated"}))
dml_obj_nyt.fit()
dml_obj_nyt.bootstrap(n_rep_boot=5000)
dml_obj_nyt.plot_effects()
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
return math.isfinite(val)
[16]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])

Linear Covariate Adjustment#
Remark that we relied on boosted trees to adjust for conditional parallel trends which allow for a nonlinear adjustment. In comparison to linear adjustment, we could rely on linear learners.
Remark that the DGP (``dgp_type=4``) is based on nonlinear conditional expectations such that the estimates will be biased
[17]:
linear_learners = {
"ml_g": LinearRegression(),
"ml_m": LogisticRegression(),
}
dml_obj_linear = DoubleMLDIDMulti(dml_data, **(default_args | linear_learners))
dml_obj_linear.fit()
dml_obj_linear.bootstrap(n_rep_boot=5000)
dml_obj_linear.plot_effects()
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
return math.isfinite(val)
[17]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])

Aggregated Effects#
As the did-R-package, the \(ATT\)’s can be aggregated to summarize multiple effects. For details on different aggregations and details on their interpretations see Callaway and Sant’Anna(2021).
The aggregations are implemented via the aggregate()
method.
Group Aggregation#
To obtain group-specific effects one can would like to average \(ATT(\mathrm{g}, t_\text{eval})\) over \(t_\text{eval}\). As a sample oracle we will combine all ite
’s based on group \(\mathrm{g}\).
[18]:
df_post_treatment = df[df["t"] >= df["d"]]
df_post_treatment.groupby("d")["ite"].mean()
[18]:
d
2025-04-01 1.968232
2025-05-01 1.485281
2025-06-01 1.044536
Name: ite, dtype: float64
To obtain group-specific effects it is possible to aggregate several \(\widehat{ATT}(\mathrm{g},t_\text{pre},t_\text{eval})\) values based on the group \(\mathrm{g}\) by setting the aggregation="group"
argument.
[19]:
aggregated_group = dml_obj.aggregate(aggregation="group")
print(aggregated_group)
_ = aggregated_group.plot_effects()
================== DoubleMLDIDAggregation Object ==================
Group Aggregation
------------------ Overall Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
1.561197 0.108387 14.403869 0.0 1.348761 1.773632
------------------ Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
2025-04 1.976061 0.176267 11.210624 0.0 1.630584 2.321537
2025-05 1.516600 0.137400 11.037817 0.0 1.247300 1.785900
2025-06 1.147511 0.088119 13.022325 0.0 0.974801 1.320220
------------------ Additional Information ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
/home/runner/work/doubleml-docs/doubleml-docs/doubleml-for-py/doubleml/did/did_aggregation.py:368: UserWarning: Joint confidence intervals require bootstrapping which hasn't been performed yet. Automatically applying '.aggregated_frameworks.bootstrap(method="normal", n_rep_boot=500)' with default values. For different bootstrap settings, call bootstrap() explicitly before plotting.
warnings.warn(

The output is a DoubleMLDIDAggregation
object which includes an overall aggregation summary based on group size.
Time Aggregation#
To obtain time-specific effects one can would like to average \(ATT(\mathrm{g}, t_\text{eval})\) over \(\mathrm{g}\) (respecting group size). As a sample oracle we will combine all ite
’s based on group \(\mathrm{g}\). As oracle values, we obtain
[20]:
df_post_treatment.groupby("t")["ite"].mean()
[20]:
t
2025-04-01 1.029986
2025-05-01 1.459174
2025-06-01 2.034650
Name: ite, dtype: float64
To aggregate \(\widehat{ATT}(\mathrm{g},t_\text{pre},t_\text{eval})\), based on \(t_\text{eval}\), but weighted with respect to group size. Corresponds to Calendar Time Effects from the did-R-package.
For calendar time effects set aggregation="time"
.
[21]:
aggregated_time = dml_obj.aggregate("time")
print(aggregated_time)
fig, ax = aggregated_time.plot_effects()
================== DoubleMLDIDAggregation Object ==================
Time Aggregation
------------------ Overall Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
1.515474 0.119343 12.698508 0.0 1.281567 1.749382
------------------ Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
2025-04 0.973259 0.117646 8.272778 2.220446e-16 0.742677 1.203841
2025-05 1.451808 0.138357 10.493195 0.000000e+00 1.180633 1.722983
2025-06 2.121355 0.155789 13.616811 0.000000e+00 1.816014 2.426697
------------------ Additional Information ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
/home/runner/work/doubleml-docs/doubleml-docs/doubleml-for-py/doubleml/did/did_aggregation.py:368: UserWarning: Joint confidence intervals require bootstrapping which hasn't been performed yet. Automatically applying '.aggregated_frameworks.bootstrap(method="normal", n_rep_boot=500)' with default values. For different bootstrap settings, call bootstrap() explicitly before plotting.
warnings.warn(

Event Study Aggregation#
To obtain event-study-type effects one can would like to aggregate \(ATT(\mathrm{g}, t_\text{eval})\) over \(e = t_\text{eval} - \mathrm{g}\) (respecting group size). As a sample oracle we will combine all ite
’s based on group \(\mathrm{g}\). As oracle values, we obtain
[22]:
df["e"] = pd.to_datetime(df["t"]).values.astype("datetime64[M]") - \
pd.to_datetime(df["d"]).values.astype("datetime64[M]")
df.groupby("e")["ite"].mean()[1:]
[22]:
e
-122 days 0.019071
-92 days -0.017818
-61 days -0.024566
-31 days 0.022331
0 days 1.014541
31 days 1.957218
59 days 2.958891
Name: ite, dtype: float64
Analogously, aggregation="eventstudy"
aggregates \(\widehat{ATT}(\mathrm{g},t_\text{pre},t_\text{eval})\) based on exposure time \(e = t_\text{eval} - \mathrm{g}\) (respecting group size).
[23]:
aggregated_eventstudy = dml_obj.aggregate("eventstudy")
print(aggregated_eventstudy)
aggregated_eventstudy.plot_effects()
================== DoubleMLDIDAggregation Object ==================
Event Study Aggregation
------------------ Overall Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
2.009951 0.159526 12.599537 0.0 1.697286 2.322615
------------------ Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
-4 months 0.121206 0.109693 1.104956 0.269179 -0.093788 0.336200
-3 months 0.017057 0.077841 0.219124 0.826554 -0.135509 0.169623
-2 months -0.057022 0.076748 -0.742976 0.457496 -0.207445 0.093401
-1 months -0.027418 0.071972 -0.380952 0.703239 -0.168480 0.113644
0 months 0.993011 0.073888 13.439366 0.000000 0.848193 1.137829
1 months 2.080726 0.165203 12.594979 0.000000 1.756934 2.404517
2 months 2.956115 0.279151 10.589672 0.000000 2.408990 3.503241
------------------ Additional Information ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
/home/runner/work/doubleml-docs/doubleml-docs/doubleml-for-py/doubleml/did/did_aggregation.py:368: UserWarning: Joint confidence intervals require bootstrapping which hasn't been performed yet. Automatically applying '.aggregated_frameworks.bootstrap(method="normal", n_rep_boot=500)' with default values. For different bootstrap settings, call bootstrap() explicitly before plotting.
warnings.warn(
[23]:
(<Figure size 1200x600 with 1 Axes>,
<Axes: title={'center': 'Aggregated Treatment Effects'}, ylabel='Effect'>)

Aggregation Details#
The DoubleMLDIDAggregation
objects include several DoubleMLFrameworks
which support methods like bootstrap()
or confint()
. Further, the weights can be accessed via the properties
overall_aggregation_weights
: weights for the overall aggregationaggregation_weights
: weights for the aggregation
To clarify, e.g. for the eventstudy aggregation
[24]:
print(aggregated_eventstudy)
================== DoubleMLDIDAggregation Object ==================
Event Study Aggregation
------------------ Overall Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
2.009951 0.159526 12.599537 0.0 1.697286 2.322615
------------------ Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
-4 months 0.121206 0.109693 1.104956 0.269179 -0.093788 0.336200
-3 months 0.017057 0.077841 0.219124 0.826554 -0.135509 0.169623
-2 months -0.057022 0.076748 -0.742976 0.457496 -0.207445 0.093401
-1 months -0.027418 0.071972 -0.380952 0.703239 -0.168480 0.113644
0 months 0.993011 0.073888 13.439366 0.000000 0.848193 1.137829
1 months 2.080726 0.165203 12.594979 0.000000 1.756934 2.404517
2 months 2.956115 0.279151 10.589672 0.000000 2.408990 3.503241
------------------ Additional Information ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
Here, the overall effect aggregation aggregates each effect with positive exposure
[25]:
print(aggregated_eventstudy.overall_aggregation_weights)
[0. 0. 0. 0. 0.33333333 0.33333333
0.33333333]
If one would like to consider how the aggregated effect with \(e=0\) is computed, one would have to look at the corresponding set of weights within the aggregation_weights
property
[26]:
# the weights for e=0 correspond to the fifth element of the aggregation weights
aggregated_eventstudy.aggregation_weights[4]
[26]:
array([0. , 0. , 0.35287789, 0. , 0. ,
0. , 0. , 0. , 0.32867133, 0. ,
0. , 0. , 0. , 0. , 0.31845078])
Taking a look at the original dml_obj
, one can see that this combines the following estimates (only show month):
\(\widehat{ATT}(04,03,04)\)
\(\widehat{ATT}(05,04,05)\)
\(\widehat{ATT}(06,05,06)\)
[27]:
print(dml_obj.summary["coef"])
ATT(2025-04,2025-01,2025-02) 0.062371
ATT(2025-04,2025-02,2025-03) -0.057230
ATT(2025-04,2025-03,2025-04) 0.973259
ATT(2025-04,2025-03,2025-05) 1.998808
ATT(2025-04,2025-03,2025-06) 2.956115
ATT(2025-05,2025-01,2025-02) 0.076977
ATT(2025-05,2025-02,2025-03) -0.220500
ATT(2025-05,2025-03,2025-04) -0.011274
ATT(2025-05,2025-04,2025-05) 0.864523
ATT(2025-05,2025-04,2025-06) 2.168677
ATT(2025-06,2025-01,2025-02) 0.121206
ATT(2025-06,2025-02,2025-03) -0.044786
ATT(2025-06,2025-03,2025-04) -0.020597
ATT(2025-06,2025-04,2025-05) -0.011044
ATT(2025-06,2025-05,2025-06) 1.147511
Name: coef, dtype: float64
Anticipation#
As described in the Model Guide, one can include anticipation periods \(\delta>0\) by setting the anticipation_periods
parameter.
Data with Anticipation#
The DGP allows to include anticipation periods via the anticipation_periods
parameter. In this case the observations will be “shifted” such that units anticipate the effect earlier and the exposure effect is increased by the number of periods where the effect is anticipated.
[28]:
n_obs = 4000
n_periods = 6
df_anticipation = make_did_CS2021(n_obs, dgp_type=4, n_periods=n_periods, n_pre_treat_periods=3, time_type="datetime", anticipation_periods=1)
print(df_anticipation.shape)
df_anticipation.head()
(19242, 10)
[28]:
id | y | y0 | y1 | d | t | Z1 | Z2 | Z3 | Z4 | |
---|---|---|---|---|---|---|---|---|---|---|
1 | 0 | 195.676838 | 195.676838 | 196.698913 | 2025-06-01 | 2025-01-01 | -0.166388 | -2.302376 | -0.108507 | -2.418089 |
2 | 0 | 190.064289 | 190.064289 | 189.324692 | 2025-06-01 | 2025-02-01 | -0.166388 | -2.302376 | -0.108507 | -2.418089 |
3 | 0 | 181.608108 | 181.608108 | 182.317326 | 2025-06-01 | 2025-03-01 | -0.166388 | -2.302376 | -0.108507 | -2.418089 |
4 | 0 | 174.528377 | 174.528377 | 173.568841 | 2025-06-01 | 2025-04-01 | -0.166388 | -2.302376 | -0.108507 | -2.418089 |
5 | 0 | 168.378835 | 164.839235 | 168.378835 | 2025-06-01 | 2025-05-01 | -0.166388 | -2.302376 | -0.108507 | -2.418089 |
To visualize the anticipation, we will again plot the “oracle” values
[29]:
df_anticipation["ite"] = df_anticipation["y1"] - df_anticipation["y0"]
df_anticipation["First Treated"] = df_anticipation["d"].dt.strftime("%Y-%m").fillna("Never Treated")
agg_df_anticipation = df_anticipation.groupby(["t", "First Treated"]).agg(**agg_dictionary).reset_index()
agg_df_anticipation.head()
[29]:
t | First Treated | y_mean | y_lower_quantile | y_upper_quantile | ite_mean | ite_lower_quantile | ite_upper_quantile | |
---|---|---|---|---|---|---|---|---|
0 | 2025-01-01 | 2025-04 | 208.354186 | 191.078927 | 226.008939 | -0.012378 | -2.332271 | 2.236961 |
1 | 2025-01-01 | 2025-05 | 210.641783 | 193.767119 | 227.921613 | 0.024665 | -2.300181 | 2.274535 |
2 | 2025-01-01 | 2025-06 | 213.010381 | 195.788023 | 229.380071 | -0.044443 | -2.385963 | 2.329258 |
3 | 2025-01-01 | Never Treated | 216.717831 | 199.863955 | 233.329446 | -0.000532 | -2.390801 | 2.404978 |
4 | 2025-02-01 | 2025-04 | 208.035874 | 181.686641 | 233.992890 | -0.002443 | -2.462117 | 2.376376 |
One can see that the effect is already anticipated one period before the actual treatment assignment.
[30]:
plot_data(agg_df_anticipation, col_name='ite')

Initialize a corresponding DoubleMLPanelData
object.
[31]:
dml_data_anticipation = DoubleMLPanelData(
data=df_anticipation,
y_col="y",
d_cols="d",
id_col="id",
t_col="t",
x_cols=["Z1", "Z2", "Z3", "Z4"],
datetime_unit="M"
)
ATT Estimation#
Let us take a look at the estimation without anticipation.
[32]:
dml_obj_anticipation = DoubleMLDIDMulti(dml_data_anticipation, **default_args)
dml_obj_anticipation.fit()
dml_obj_anticipation.bootstrap(n_rep_boot=5000)
dml_obj_anticipation.plot_effects()
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
return math.isfinite(val)
[32]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])

The effects are obviously biased. To include anticipation periods, one can adjust the anticipation_periods
parameter. Correspondingly, the outcome regression (and not yet treated units) are adjusted.
[33]:
dml_obj_anticipation = DoubleMLDIDMulti(dml_data_anticipation, **(default_args| {"anticipation_periods": 1}))
dml_obj_anticipation.fit()
dml_obj_anticipation.bootstrap(n_rep_boot=5000)
dml_obj_anticipation.plot_effects()
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
return math.isfinite(val)
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
return math.isfinite(val)
[33]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])

Group-Time Combinations#
The default option gt_combinations="standard"
includes all group time values with the specific choice of \(t_\text{pre} = \min(\mathrm{g}, t_\text{eval}) - 1\) (without anticipation) which is the weakest possible parallel trend assumption.
Other options are possible or only specific combinations of \((\mathrm{g},t_\text{pre},t_\text{eval})\).
All combinations#
The option gt_combinations="all"
includes all relevant group time values with \(t_\text{pre} < \min(\mathrm{g}, t_\text{eval})\), including longer parallel trend assumptions. This can result in multiple estimates for the same \(ATT(\mathrm{g},t)\), which have slightly different assumptions (length of parallel trends).
[34]:
dml_obj_all = DoubleMLDIDMulti(dml_data, **(default_args| {"gt_combinations": "all"}))
dml_obj_all.fit()
dml_obj_all.bootstrap(n_rep_boot=5000)
dml_obj_all.plot_effects()
/home/runner/work/doubleml-docs/doubleml-docs/doubleml-for-py/doubleml/double_ml.py:1470: UserWarning: The estimated nu2 for d is not positive. Re-estimation based on riesz representer (non-orthogonal).
warnings.warn(msg, UserWarning)
[34]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])

Selected Combinations#
Instead it is also possible to just submit a list of tuples containing \((\mathrm{g}, t_\text{pre}, t_\text{eval})\) combinations. E.g. only two combinations
[35]:
gt_dict = {
"gt_combinations": [
(np.datetime64('2025-04'),
np.datetime64('2025-01'),
np.datetime64('2025-02')),
(np.datetime64('2025-04'),
np.datetime64('2025-02'),
np.datetime64('2025-03')),
]
}
dml_obj_all = DoubleMLDIDMulti(dml_data, **(default_args| gt_dict))
dml_obj_all.fit()
dml_obj_all.bootstrap(n_rep_boot=5000)
dml_obj_all.plot_effects()
[35]:
(<Figure size 1200x800 with 2 Axes>,
[<Axes: title={'center': 'First Treated: 2025-04'}, xlabel='Evaluation Period', ylabel='Effect'>])
