Note
-
Download Jupyter notebook:
https://docs.doubleml.org/stable/examples/did/py_rep_cs.ipynb.
Python: Repeated Cross-Sectional 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_cs_CS2021
Data#
We will rely on the make_did_cs_CS2021
DGP, which is inspired by Callaway and Sant’Anna(2021) (Appendix SC) and Sant’Anna and Zhao (2020).
We will observe approximately n_obs
units over n_periods
. The parameter lambda_t
determines the probability of observing a unit i
in time period t
. The parameter lambda_t
is set to 0.5 for all time periods, which means that each unit has a 50% chance of being observed in each time period.
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_cs_CS2021(n_obs, dgp_type=4, include_never_treated=True, n_periods=n_periods, n_pre_treat_periods=3,
lambda_t=0.5, time_type="float")
df["ite"] = df["y1"] - df["y0"]
print(df.shape)
df.head()
(29601, 11)
[2]:
id | y | y0 | y1 | d | t | Z1 | Z2 | Z3 | Z4 | ite | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 206.290533 | 206.290533 | 207.964732 | 3.0 | 0 | -0.317116 | -0.832171 | -0.308184 | -1.870001 | 1.674198 |
1 | 0 | 207.450885 | 207.450885 | 208.125002 | 3.0 | 1 | -0.317116 | -0.832171 | -0.308184 | -1.870001 | 0.674117 |
2 | 0 | 205.392812 | 205.392812 | 207.117336 | 3.0 | 2 | -0.317116 | -0.832171 | -0.308184 | -1.870001 | 1.724524 |
3 | 0 | 207.727118 | 205.829388 | 207.727118 | 3.0 | 3 | -0.317116 | -0.832171 | -0.308184 | -1.870001 | 1.897730 |
5 | 0 | 206.798758 | 203.390777 | 206.798758 | 3.0 | 5 | -0.317116 | -0.832171 | -0.308184 | -1.870001 | 3.407981 |
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`).
The data set with repeated cross-sectional data is generated on the basis of a panel data set with the following data generating process (DGP). To obtain repeated cross-sectional data, the number of generated individuals is increased to \(\frac{n_{obs}}{\lambda_t}\), where \(\lambda_t\) denotes the probability to observe a unit at each time period (time constant).
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
0 4914
1 5000
2 4854
3 5062
4 4887
5 4884
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
3.0 7578
4.0 7186
5.0 7196
inf 7641
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
3.0 7578
4.0 7186
5.0 7196
inf 7641
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
# 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", "d"]).agg(**agg_dictionary).reset_index()
agg_df.head()
[6]:
t | d | y_mean | y_lower_quantile | y_upper_quantile | ite_mean | ite_lower_quantile | ite_upper_quantile | |
---|---|---|---|---|---|---|---|---|
0 | 0 | 3.0 | 208.711855 | 199.091900 | 218.864724 | -0.008117 | -2.359493 | 2.310664 |
1 | 0 | 4.0 | 210.269650 | 199.849703 | 220.428055 | -0.042078 | -2.386611 | 2.367674 |
2 | 0 | 5.0 | 212.460444 | 203.261968 | 222.618621 | -0.017448 | -2.285882 | 2.319843 |
3 | 0 | inf | 214.203281 | 204.147365 | 224.192737 | -0.005641 | -2.298443 | 2.271431 |
4 | 1 | 3.0 | 208.757128 | 188.251340 | 228.885705 | -0.019994 | -2.276624 | 2.293457 |
[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["d"].nunique()
color_palette = sns.color_palette("colorblind", n_colors=n_colors)
sns.lineplot(
data=df,
x='t',
y=f'{col_name}_mean',
hue='d',
style='d',
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='d', 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')
/opt/hostedtoolcache/Python/3.12.11/x64/lib/python3.12/site-packages/matplotlib/colors.py:2295: RuntimeWarning: invalid value encountered in divide
resdat /= (vmax - vmin)

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')
/opt/hostedtoolcache/Python/3.12.11/x64/lib/python3.12/site-packages/matplotlib/colors.py:2295: RuntimeWarning: invalid value encountered in divide
resdat /= (vmax - vmin)

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"],
)
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. Unique Ids: 9847
No. Observations: 29601
------------------ DataFrame info ------------------
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29601 entries, 0 to 29600
Columns: 11 entries, id to ite
dtypes: float64(9), int64(2)
memory usage: 2.5 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.
For repeated cross-sectional data, we additionally specify the argument
panel=False
[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",
"anticipation_periods": 0,
"n_folds": 5,
"n_rep": 1,
"panel": False,
}
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. Unique Ids: 9847
No. Observations: 29601
------------------ 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_g_d0_t0 RMSE: [[1.98430085 2.92185958 3.96072074 4.01615173 3.99746842 1.94860197
2.91220897 3.95326435 5.33890777 5.36415913 1.96261388 2.85975739
3.97859413 5.41113127 6.50649578]]
Learner ml_g_d0_t1 RMSE: [[2.90041844 4.01562045 5.374187 6.47364698 7.88686151 2.97781186
3.85026247 5.40043967 6.52873332 8.11570692 2.95037883 3.87334694
5.32207333 6.6825634 7.82987933]]
Learner ml_g_d1_t0 RMSE: [[1.93811241 3.01601231 4.12397944 4.14368631 4.1068965 1.88728285
2.81496258 3.9901015 4.88683838 4.81874341 1.94094027 3.03267071
4.01844598 5.25465859 6.30140735]]
Learner ml_g_d1_t1 RMSE: [[3.07358689 4.13338882 5.32536645 6.16452829 7.81141183 2.81327761
4.04464987 4.68690706 6.34072587 7.41243276 3.03757199 3.99817614
5.26103716 6.56316397 7.6340788 ]]
Classification:
Learner ml_m Log Loss: [[0.61228405 0.60639433 0.61638235 0.60691978 0.61086846 0.63377629
0.63142806 0.64685572 0.64520933 0.64537167 0.65369941 0.65833534
0.6622962 0.66227142 0.65609841]]
------------------ Resampling ------------------
No. folds: 5
No. repeated sample splits: 1
------------------ Fit summary ------------------
coef std err t P>|t| 2.5 % 97.5 %
ATT(3.0,0,1) -0.111021 0.217438 -0.510588 6.096396e-01 -0.537192 0.315149
ATT(3.0,1,2) 0.195264 0.324272 0.602161 5.470670e-01 -0.440298 0.830826
ATT(3.0,2,3) 1.194680 0.396379 3.013984 2.578410e-03 0.417791 1.971568
ATT(3.0,2,4) 2.078489 0.417198 4.982024 6.292265e-07 1.260797 2.896182
ATT(3.0,2,5) 2.755739 0.541919 5.085153 3.673299e-07 1.693598 3.817880
ATT(4.0,0,1) 0.100516 0.186125 0.540049 5.891635e-01 -0.264281 0.465314
ATT(4.0,1,2) 0.007868 0.243581 0.032303 9.742307e-01 -0.469542 0.485278
ATT(4.0,2,3) -0.260447 0.310786 -0.838028 4.020150e-01 -0.869576 0.348682
ATT(4.0,3,4) 1.466160 0.380038 3.857926 1.143531e-04 0.721298 2.211022
ATT(4.0,3,5) 1.978502 0.477238 4.145737 3.387217e-05 1.043133 2.913870
ATT(5.0,0,1) 0.135144 0.159067 0.849605 3.955447e-01 -0.176622 0.446910
ATT(5.0,1,2) 0.004293 0.217748 0.019716 9.842697e-01 -0.422485 0.431072
ATT(5.0,2,3) -0.470757 0.285231 -1.650440 9.885290e-02 -1.029800 0.088286
ATT(5.0,3,4) 0.117080 0.387465 0.302168 7.625237e-01 -0.642338 0.876498
ATT(5.0,4,5) 0.898292 0.429518 2.091396 3.649257e-02 0.056452 1.740131
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=3, t_{\text{pre}}=0, t_{\text{eval}}=1)\) which estimates the pre-trend from time period \(0\) to \(1\) even if the actual treatment occured in time period \(3\).
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(3.0,0,1) | -0.742576 | 0.520533 |
ATT(3.0,1,2) | -0.746594 | 1.137122 |
ATT(3.0,2,3) | 0.043387 | 2.345972 |
ATT(3.0,2,4) | 0.866728 | 3.290251 |
ATT(3.0,2,5) | 1.181722 | 4.329756 |
ATT(4.0,0,1) | -0.440088 | 0.641121 |
ATT(4.0,1,2) | -0.699619 | 0.715356 |
ATT(4.0,2,3) | -1.163133 | 0.642238 |
ATT(4.0,3,4) | 0.362329 | 2.569991 |
ATT(4.0,3,5) | 0.592353 | 3.364651 |
ATT(5.0,0,1) | -0.326870 | 0.597159 |
ATT(5.0,1,2) | -0.628162 | 0.636748 |
ATT(5.0,2,3) | -1.299219 | 0.357704 |
ATT(5.0,3,4) | -1.008324 | 1.242483 |
ATT(5.0,4,5) | -0.349254 | 2.145838 |
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.11/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: 3.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 4.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 5.0'}, 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 CI upper
ATT(3.0,0,1) -0.818764 -0.458395 -0.111021 0.236352 0.593280
ATT(3.0,1,2) -0.858645 -0.325634 0.195264 0.716162 1.252033
ATT(3.0,2,3) -0.128834 0.515808 1.194680 1.873552 2.535848
ATT(3.0,2,4) 0.632813 1.320627 2.078489 2.836352 3.525724
ATT(3.0,2,5) 0.964192 1.851576 2.755739 3.659903 4.558834
ATT(4.0,0,1) -0.539144 -0.234324 0.100516 0.435357 0.743780
ATT(4.0,1,2) -0.880782 -0.477338 0.007868 0.493075 0.892826
ATT(4.0,2,3) -1.390373 -0.878496 -0.260447 0.357601 0.869695
ATT(4.0,3,4) 0.070589 0.692491 1.466160 2.239829 2.870595
ATT(4.0,3,5) 0.296190 1.078591 1.978502 2.878412 3.668259
ATT(5.0,0,1) -0.459971 -0.197916 0.135144 0.468204 0.730141
ATT(5.0,1,2) -0.801110 -0.442732 0.004293 0.451318 0.810448
ATT(5.0,2,3) -1.548992 -1.080603 -0.470757 0.139088 0.610499
ATT(5.0,3,4) -1.291787 -0.656763 0.117080 0.890922 1.532429
ATT(5.0,4,5) -0.746335 -0.037688 0.898292 1.834272 2.540801
------------------ Robustness Values ------------------
H_0 RV (%) RVa (%)
ATT(3.0,0,1) 0.0 0.968935 0.000389
ATT(3.0,1,2) 0.0 1.135473 0.000393
ATT(3.0,2,3) 0.0 5.218702 2.432460
ATT(3.0,2,4) 0.0 8.012316 5.416995
ATT(3.0,2,5) 0.0 8.862832 6.100256
ATT(4.0,0,1) 0.0 0.910369 0.000381
ATT(4.0,1,2) 0.0 0.049243 0.000664
ATT(4.0,2,3) 0.0 1.275524 0.000636
ATT(4.0,3,4) 0.0 5.608286 3.269934
ATT(4.0,3,5) 0.0 6.476406 3.968677
ATT(5.0,0,1) 0.0 1.228492 0.000646
ATT(5.0,1,2) 0.0 0.029110 0.000619
ATT(5.0,2,3) 0.0 2.323931 0.007919
ATT(5.0,3,4) 0.0 0.459629 0.000583
ATT(5.0,4,5) 0.0 2.881040 0.621311
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.11/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: 3.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 4.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 5.0'}, 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.11/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: 3.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 4.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 5.0'}, 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
3.0 1.935077
4.0 1.511858
5.0 0.958206
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.551448 0.23123 6.709534 1.952460e-11 1.098245 2.004651
------------------ Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
3.0 2.009636 0.305576 6.576548 4.814948e-11 1.410718 2.608554
4.0 1.722331 0.341061 5.049922 4.419900e-07 1.053864 2.390798
5.0 0.898292 0.429518 2.091396 3.649257e-02 0.056452 1.740131
------------------ Additional Information ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
/opt/hostedtoolcache/Python/3.12.11/x64/lib/python3.12/site-packages/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
3 0.932968
4 1.478475
5 2.005921
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.622625 0.208521 7.781601 7.105427e-15 1.213932 2.031318
------------------ Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
3 1.194680 0.396379 3.013984 2.578410e-03 0.417791 1.971568
4 1.780454 0.321475 5.538381 3.052803e-08 1.150373 2.410534
5 1.892742 0.375189 5.044763 4.540839e-07 1.157384 2.628100
------------------ Additional Information ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
/opt/hostedtoolcache/Python/3.12.11/x64/lib/python3.12/site-packages/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_treated = df[df["d"] != np.inf].copy()
df_treated["e"] = df_treated["t"] - df_treated["d"]
df_treated.groupby("e")["ite"].mean().iloc[1:]
[22]:
e
-4.0 -0.031310
-3.0 -0.011711
-2.0 -0.018675
-1.0 0.011166
0.0 0.949051
1.0 2.007699
2.0 2.929263
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 %
1.990652 0.27966 7.118121 1.094014e-12 1.442529 2.538775
------------------ Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
-4.0 0.135144 0.159067 0.849605 3.955447e-01 -0.176622 0.446910
-3.0 0.052371 0.128468 0.407662 6.835221e-01 -0.199421 0.304163
-2.0 -0.189998 0.121834 -1.559477 1.188835e-01 -0.428788 0.048793
-1.0 0.020521 0.166128 0.123526 9.016905e-01 -0.305084 0.346126
0.0 1.186394 0.190961 6.212758 5.206264e-10 0.812118 1.560671
1.0 2.029823 0.315928 6.424960 1.319043e-10 1.410616 2.649030
2.0 2.755739 0.541919 5.085153 3.673299e-07 1.693598 3.817880
------------------ Additional Information ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
/opt/hostedtoolcache/Python/3.12.11/x64/lib/python3.12/site-packages/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 %
1.990652 0.27966 7.118121 1.094014e-12 1.442529 2.538775
------------------ Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
-4.0 0.135144 0.159067 0.849605 3.955447e-01 -0.176622 0.446910
-3.0 0.052371 0.128468 0.407662 6.835221e-01 -0.199421 0.304163
-2.0 -0.189998 0.121834 -1.559477 1.188835e-01 -0.428788 0.048793
-1.0 0.020521 0.166128 0.123526 9.016905e-01 -0.305084 0.346126
0.0 1.186394 0.190961 6.212758 5.206264e-10 0.812118 1.560671
1.0 2.029823 0.315928 6.424960 1.319043e-10 1.410616 2.649030
2.0 2.755739 0.541919 5.085153 3.673299e-07 1.693598 3.817880
------------------ 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.34508197, 0. , 0. ,
0. , 0. , 0. , 0.32723133, 0. ,
0. , 0. , 0. , 0. , 0.3276867 ])
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(3.0,0,1) -0.111021
ATT(3.0,1,2) 0.195264
ATT(3.0,2,3) 1.194680
ATT(3.0,2,4) 2.078489
ATT(3.0,2,5) 2.755739
ATT(4.0,0,1) 0.100516
ATT(4.0,1,2) 0.007868
ATT(4.0,2,3) -0.260447
ATT(4.0,3,4) 1.466160
ATT(4.0,3,5) 1.978502
ATT(5.0,0,1) 0.135144
ATT(5.0,1,2) 0.004293
ATT(5.0,2,3) -0.470757
ATT(5.0,3,4) 0.117080
ATT(5.0,4,5) 0.898292
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_cs_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()
(19046, 10)
[28]:
id | y | y0 | y1 | d | t | Z1 | Z2 | Z3 | Z4 | |
---|---|---|---|---|---|---|---|---|---|---|
1 | 0 | 209.943892 | 209.943892 | 206.488123 | 2025-05-01 | 2025-01-01 | 0.295609 | -0.260085 | -0.736988 | -0.638664 |
6 | 0 | 205.309536 | 201.959006 | 205.309536 | 2025-05-01 | 2025-06-01 | 0.295609 | -0.260085 | -0.736988 | -0.638664 |
8 | 1 | 222.862644 | 222.862644 | 221.543711 | 2025-06-01 | 2025-01-01 | 0.674337 | -0.172129 | 0.316567 | 0.243262 |
10 | 1 | 234.222429 | 234.222429 | 234.788618 | 2025-06-01 | 2025-03-01 | 0.674337 | -0.172129 | 0.316567 | 0.243262 |
12 | 1 | 247.298166 | 246.590073 | 247.298166 | 2025-06-01 | 2025-05-01 | 0.674337 | -0.172129 | 0.316567 | 0.243262 |
To visualize the anticipation, we will again plot the “oracle” values
[29]:
df_anticipation["ite"] = df_anticipation["y1"] - df_anticipation["y0"]
agg_df_anticipation = df_anticipation.groupby(["t", "d"]).agg(**agg_dictionary).reset_index()
agg_df_anticipation.head()
[29]:
t | d | y_mean | y_lower_quantile | y_upper_quantile | ite_mean | ite_lower_quantile | ite_upper_quantile | |
---|---|---|---|---|---|---|---|---|
0 | 2025-01-01 | 2025-04-01 | 208.157834 | 191.445418 | 225.238046 | 0.053598 | -2.240579 | 2.526612 |
1 | 2025-01-01 | 2025-05-01 | 210.667238 | 193.058954 | 227.275186 | 0.059441 | -2.387472 | 2.331671 |
2 | 2025-01-01 | 2025-06-01 | 212.951414 | 196.611318 | 229.209814 | -0.022312 | -2.427173 | 2.313213 |
3 | 2025-02-01 | 2025-04-01 | 208.204619 | 184.353255 | 232.589209 | 0.021270 | -2.227462 | 2.383587 |
4 | 2025-02-01 | 2025-05-01 | 210.865913 | 187.348219 | 236.274644 | -0.063757 | -2.505044 | 2.174914 |
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.11/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.11/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.11/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.11/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.11/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.11/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()
[34]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 3.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 4.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 5.0'}, xlabel='Evaluation Period', ylabel='Effect'>])

Universal Base Period#
The option gt_combinations="universal"
set \(t_\text{pre} = \mathrm{g} - \delta - 1\), corresponding to a universal/constant comparison or base period.
Remark that this implies \(t_\text{pre} > t_\text{eval}\) for all pre-treatment periods (accounting for anticipation). Therefore these effects do not have the same straightforward interpretation as ATT’s.
[35]:
dml_obj_universal = DoubleMLDIDMulti(dml_data, **(default_args| {"gt_combinations": "universal"}))
dml_obj_universal.fit()
dml_obj_universal.bootstrap(n_rep_boot=5000)
dml_obj_universal.plot_effects()
/opt/hostedtoolcache/Python/3.12.11/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)
[35]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 3.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 4.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 5.0'}, 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
[36]:
gt_dict = {
"gt_combinations": [
(4.0, 1, 2),
(4.0, 1, 3),
]
}
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()
[36]:
(<Figure size 1200x800 with 2 Axes>,
[<Axes: title={'center': 'First Treated: 4.0'}, xlabel='Evaluation Period', ylabel='Effect'>])
