Note
-
Download Jupyter notebook:
https://docs.doubleml.org/stable/examples/did/py_panel_data_example.ipynb.
Python: Real-Data Example for Multi-Period Difference-in-Differences#
In this example, we replicate a real-data demo notebook from the did-R-package in order to illustrate the use of DoubleML for multi-period difference-in-differences (DiD) models.
The notebook requires the following packages:
[1]:
import pyreadr
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.dummy import DummyRegressor, DummyClassifier
from sklearn.linear_model import LassoCV, LogisticRegressionCV
from doubleml.data import DoubleMLPanelData
from doubleml.did import DoubleMLDIDMulti
Causal Research Question#
Callaway and Sant’Anna (2021) study the causal effect of raising the minimum wage on teen employment in the US using county data over a period from 2001 to 2007. A county is defined as treated if the minimum wage in that county is above the federal minimum wage. We focus on a preprocessed balanced panel data set as provided by the did-R-package. The corresponding documentation for the mpdta
data is available from the did package website. We use this data solely as a demonstration example to help readers understand differences in the DoubleML and did packages. An analogous notebook using the same data is available from the did documentation.
We follow the original notebook and provide results under identification based on unconditional and conditional parallel trends. For the Double Machine Learning (DML) Difference-in-Differences estimator, we demonstrate two different specifications, one based on linear and logistic regression and one based on their \(\ell_1\) penalized variants Lasso and logistic regression with cross-validated penalty choice. The results for the former are expected to be very similar to those in the did data example. Minor differences might arise due to the use of sample-splitting in the DML estimation.
Data#
We will download and read a preprocessed data file as provided by the did-R-package.
[2]:
# download file from did package for R
url = "https://github.com/bcallaway11/did/raw/refs/heads/master/data/mpdta.rda"
pyreadr.download_file(url, "mpdta.rda")
mpdta = pyreadr.read_r("mpdta.rda")["mpdta"]
mpdta.head()
[2]:
| year | countyreal | lpop | lemp | first.treat | treat | |
|---|---|---|---|---|---|---|
| 0 | 2003 | 8001.0 | 5.896761 | 8.461469 | 2007.0 | 1.0 |
| 1 | 2004 | 8001.0 | 5.896761 | 8.336870 | 2007.0 | 1.0 |
| 2 | 2005 | 8001.0 | 5.896761 | 8.340217 | 2007.0 | 1.0 |
| 3 | 2006 | 8001.0 | 5.896761 | 8.378161 | 2007.0 | 1.0 |
| 4 | 2007 | 8001.0 | 5.896761 | 8.487352 | 2007.0 | 1.0 |
To work with DoubleML, we initialize a DoubleMLPanelData object. The input data has to satisfy some requirements, i.e., it should be in a long format with every row containing the information of one unit at one time period. Moreover, the data should contain a column on the unit identifier and a column on the time period. The requirements are virtually identical to those of the
did-R-package, as listed in their data example. In line with the naming conventions of DoubleML, the treatment group indicator is passed to DoubleMLPanelData by the d_cols argument. To flexibly handle different formats for handling time periods, the time variable t_col can handle float,
int and datetime formats. More information are available in the user guide. To indicate never treated units, we set their value for the treatment group variable to np.inf.
Now, we can initialize the DoubleMLPanelData object, 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 controls
[3]:
# Set values for treatment group indicator for never-treated to np.inf
mpdta.loc[mpdta['first.treat'] == 0, 'first.treat'] = np.inf
dml_data = DoubleMLPanelData(
data=mpdta,
y_col="lemp",
d_cols="first.treat",
id_col="countyreal",
t_col="year",
x_cols=['lpop']
)
print(dml_data)
================== DoubleMLPanelData Object ==================
------------------ Data summary ------------------
Outcome variable: lemp
Treatment variable(s): ['first.treat']
Covariates: ['lpop']
Instrument variable(s): None
Time variable: year
Id variable: countyreal
Static panel data: False
No. Unique Ids: 500
No. Observations: 2500
------------------ DataFrame info ------------------
<class 'pandas.DataFrame'>
RangeIndex: 2500 entries, 0 to 2499
Columns: 6 entries, year to treat
dtypes: float64(5), int32(1)
memory usage: 107.6 KB
Note that we specified a pre-treatment confounding variable lpop through the x_cols argument. To consider cases under unconditional parallel trends, we can use dummy learners to ignore the pre-treatment confounding variable. This is illustrated below.
ATT Estimation: Unconditional Parallel Trends#
We start with identification under the unconditional parallel trends assumption. To do so, initialize a DoubleMLDIDMulti object (see model documentation), which takes the previously initialized DoubleMLPanelData object as input. We use scikit-learn’s DummyRegressor (documentation here) and
DummyClassifier (documentation here) to ignore the pre-treatment confounding variable. At this stage, we can also pass further options, for example specifying the number of folds and repetitions used for cross-fitting.
When calling the fit() method, the model estimates standard combinations of \(ATT(g,t)\) parameters, which corresponds to the defaults in the did-R-package. These combinations can also be customized through the gt_combinations argument, see the user guide.
[4]:
dml_obj = DoubleMLDIDMulti(
obj_dml_data=dml_data,
ml_g=DummyRegressor(),
ml_m=DummyClassifier(),
control_group="never_treated",
n_folds=10
)
dml_obj.fit()
print(dml_obj.summary.round(4))
coef std err t P>|t| 2.5 % 97.5 %
ATT(2004.0,2003,2004) -0.0105 0.0229 -0.4586 0.6465 -0.0554 0.0344
ATT(2004.0,2003,2005) -0.0704 0.0312 -2.2586 0.0239 -0.1316 -0.0093
ATT(2004.0,2003,2006) -0.1373 0.0364 -3.7743 0.0002 -0.2086 -0.0660
ATT(2004.0,2003,2007) -0.1008 0.0342 -2.9437 0.0032 -0.1679 -0.0337
ATT(2006.0,2003,2004) 0.0065 0.0233 0.2802 0.7793 -0.0391 0.0522
ATT(2006.0,2004,2005) -0.0028 0.0197 -0.1408 0.8880 -0.0413 0.0358
ATT(2006.0,2005,2006) -0.0046 0.0178 -0.2585 0.7960 -0.0395 0.0303
ATT(2006.0,2005,2007) -0.0412 0.0203 -2.0274 0.0426 -0.0811 -0.0014
ATT(2007.0,2003,2004) 0.0305 0.0151 2.0279 0.0426 0.0010 0.0600
ATT(2007.0,2004,2005) -0.0027 0.0164 -0.1623 0.8711 -0.0348 0.0295
ATT(2007.0,2005,2006) -0.0311 0.0179 -1.7349 0.0828 -0.0661 0.0040
ATT(2007.0,2006,2007) -0.0261 0.0167 -1.5626 0.1181 -0.0589 0.0066
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
This corresponds to the estimates given in att_gt function in the did-R-package, 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. \(ATT(2007,2005)\).
As usual for the DoubleML-package, you can obtain joint confidence intervals via bootstrap.
[5]:
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)
print(ci_joint)
2.5 % 97.5 %
ATT(2004.0,2003,2004) -0.075725 0.054716
ATT(2004.0,2003,2005) -0.159259 0.018359
ATT(2004.0,2003,2006) -0.240823 -0.033722
ATT(2004.0,2003,2007) -0.198277 -0.003306
ATT(2006.0,2003,2004) -0.059766 0.072815
ATT(2006.0,2004,2005) -0.058723 0.053188
ATT(2006.0,2005,2006) -0.055240 0.046043
ATT(2006.0,2005,2007) -0.099139 0.016673
ATT(2007.0,2003,2004) -0.012331 0.073381
ATT(2007.0,2004,2005) -0.049369 0.044045
ATT(2007.0,2005,2006) -0.082025 0.019910
ATT(2007.0,2006,2007) -0.073712 0.021471
A visualization of the effects can be obtained via the plot_effects() method.
Remark that the plot used joint confidence intervals per default.
[6]:
fig, ax = dml_obj.plot_effects()
Effect Aggregation#
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. We follow the structure of the did package notebook and start with an aggregation relative to the treatment timing.
Event Study Aggregation#
We can aggregate the \(ATT\)s relative to the treatment timing. This is done by setting aggregation="eventstudy" in the aggregate() method. 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).
[7]:
# rerun bootstrap for valid simultaneous inference (as values are not saved)
dml_obj.bootstrap(n_rep_boot=5000)
aggregated_eventstudy = dml_obj.aggregate("eventstudy")
# run bootstrap to obtain simultaneous confidence intervals
aggregated_eventstudy.aggregated_frameworks.bootstrap()
print(aggregated_eventstudy)
fig, ax = aggregated_eventstudy.plot_effects()
================== DoubleMLDIDAggregation Object ==================
Event Study Aggregation
------------------ Overall Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
-0.077254 0.019907 -3.880674 0.000104 -0.116271 -0.038236
------------------ Aggregated Effects ------------------
coef std err t P>|t| 2.5 % 97.5 %
-3.0 0.030525 0.015052 2.027916 0.042569 0.001023 0.060027
-2.0 -0.000513 0.013286 -0.038618 0.969195 -0.026553 0.025527
-1.0 -0.024440 0.014231 -1.717444 0.085898 -0.052331 0.003451
0.0 -0.019978 0.011839 -1.687457 0.091516 -0.043182 0.003226
1.0 -0.050972 0.016900 -3.016100 0.002560 -0.084096 -0.017849
2.0 -0.137272 0.036370 -3.774322 0.000160 -0.208556 -0.065988
3.0 -0.100792 0.034240 -2.943699 0.003243 -0.167901 -0.033683
------------------ Additional Information ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
Alternatively, the \(ATT\) could also be aggregated according to (calendar) time periods or treatment groups, see the user guide.
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
If one would like to consider how the aggregated effect with \(e=0\) is computed, one would have to look at the third set of weights within the aggregation_weights property
[8]:
aggregated_eventstudy.aggregation_weights[2]
[8]:
array([0. , 0. , 0. , 0. , 0. ,
0.23391813, 0. , 0. , 0. , 0. ,
0.76608187, 0. ])
ATT Estimation: Conditional Parallel Trends#
We briefly demonstrate how to use the DoubleMLDIDMulti model with conditional parallel trends. As the rationale behind DML is to flexibly model nuisance components as prediction problems, the DML DiD estimator includes pre-treatment covariates by default. In DiD, the nuisance components are the outcome regression and the propensity score estimation for the treatment group variable. This is why we had to enforce dummy learners in the unconditional parallel trends case to ignore the
pre-treatment covariates. Now, we can replicate the classical doubly robust DiD estimator as of Callaway and Sant’Anna(2021) by using linear and logistic regression for the nuisance components. This is done by setting ml_g to LinearRegression() and ml_m to LogisticRegression(). Similarly, we can also choose other learners, for example by setting ml_g and ml_m to LassoCV() and LogisticRegressionCV(). We present
the results for the ATTs and their event-study aggregation in the corresponding effect plots.
Please note that the example is meant to illustrate the usage of the DoubleMLDIDMulti model in combination with ML learners. In real-data applicatoins, careful choice and empirical evaluation of the learners are required. Default measures for the prediction of the nuisance components are printed in the model summary, as briefly illustrated below.
[9]:
dml_obj_linear_logistic = DoubleMLDIDMulti(
obj_dml_data=dml_data,
ml_g=LinearRegression(),
ml_m=LogisticRegression(penalty=None),
control_group="never_treated",
n_folds=10
)
dml_obj_linear_logistic.fit()
dml_obj_linear_logistic.bootstrap(n_rep_boot=5000)
dml_obj_linear_logistic.plot_effects(title="Estimated ATTs by Group, Linear and logistic Regression")
[9]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 2004.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2006.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2007.0'}, xlabel='Evaluation Period', ylabel='Effect'>])
We briefly look at the model summary, which includes some standard diagnostics for the prediction of the nuisance components.
[10]:
print(dml_obj_linear_logistic)
================== DoubleMLDIDMulti Object ==================
------------------ Data summary ------------------
Outcome variable: lemp
Treatment variable(s): ['first.treat']
Covariates: ['lpop']
Instrument variable(s): None
Time variable: year
Id variable: countyreal
Static panel data: False
No. Unique Ids: 500
No. Observations: 2500
------------------ Score & algorithm ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
------------------ Machine learner ------------------
Learner ml_g: LinearRegression()
Learner ml_m: LogisticRegression(penalty=None)
Out-of-sample Performance:
Regression:
Learner ml_g0 RMSE: [[0.17271383 0.18224584 0.25816163 0.25825991 0.17239205 0.1511116
0.20171256 0.20662897 0.17181597 0.15076732 0.20218335 0.1633238 ]]
Learner ml_g1 RMSE: [[0.10415025 0.12540234 0.13737372 0.14206122 0.14100826 0.11313008
0.08721565 0.10682078 0.13423008 0.16484188 0.16268985 0.16292149]]
Classification:
Learner ml_m Log Loss: [[0.23108209 0.23124006 0.23003306 0.23104292 0.34783479 0.34943951
0.34800193 0.34858996 0.60720574 0.60785415 0.60607401 0.60854246]]
------------------ Resampling ------------------
No. folds: 10
No. repeated sample splits: 1
------------------ Fit summary ------------------
coef std err t P>|t| 2.5 % \
ATT(2004.0,2003,2004) -0.016648 0.021861 -0.761531 0.446340 -0.059494
ATT(2004.0,2003,2005) -0.076541 0.028020 -2.731632 0.006302 -0.131460
ATT(2004.0,2003,2006) -0.137307 0.035237 -3.896664 0.000098 -0.206370
ATT(2004.0,2003,2007) -0.105779 0.032757 -3.229216 0.001241 -0.169981
ATT(2006.0,2003,2004) -0.001289 0.022256 -0.057896 0.953832 -0.044909
ATT(2006.0,2004,2005) -0.007843 0.018374 -0.426848 0.669490 -0.043856
ATT(2006.0,2005,2006) 0.000760 0.019849 0.038279 0.969466 -0.038144
ATT(2006.0,2005,2007) -0.041624 0.019778 -2.104575 0.035328 -0.080388
ATT(2007.0,2003,2004) 0.028159 0.014106 1.996296 0.045902 0.000512
ATT(2007.0,2004,2005) -0.004396 0.015723 -0.279590 0.779792 -0.035212
ATT(2007.0,2005,2006) -0.028902 0.018365 -1.573767 0.115541 -0.064897
ATT(2007.0,2006,2007) -0.028873 0.016453 -1.754891 0.079278 -0.061121
97.5 %
ATT(2004.0,2003,2004) 0.026199
ATT(2004.0,2003,2005) -0.021622
ATT(2004.0,2003,2006) -0.068243
ATT(2004.0,2003,2007) -0.041577
ATT(2006.0,2003,2004) 0.042332
ATT(2006.0,2004,2005) 0.028170
ATT(2006.0,2005,2006) 0.039663
ATT(2006.0,2005,2007) -0.002860
ATT(2007.0,2003,2004) 0.055805
ATT(2007.0,2004,2005) 0.026420
ATT(2007.0,2005,2006) 0.007093
ATT(2007.0,2006,2007) 0.003374
[11]:
es_linear_logistic = dml_obj_linear_logistic.aggregate("eventstudy")
es_linear_logistic.aggregated_frameworks.bootstrap()
es_linear_logistic.plot_effects(title="Estimated ATTs by Group, Linear and logistic Regression")
[11]:
(<Figure size 1200x600 with 1 Axes>,
<Axes: title={'center': 'Estimated ATTs by Group, Linear and logistic Regression'}, ylabel='Effect'>)
[12]:
dml_obj_lasso = DoubleMLDIDMulti(
obj_dml_data=dml_data,
ml_g=LassoCV(),
ml_m=LogisticRegressionCV(),
control_group="never_treated",
n_folds=10
)
dml_obj_lasso.fit()
dml_obj_lasso.bootstrap(n_rep_boot=5000)
dml_obj_lasso.plot_effects(title="Estimated ATTs by Group, LassoCV and LogisticRegressionCV()")
[12]:
(<Figure size 1200x800 with 4 Axes>,
[<Axes: title={'center': 'First Treated: 2004.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2006.0'}, ylabel='Effect'>,
<Axes: title={'center': 'First Treated: 2007.0'}, xlabel='Evaluation Period', ylabel='Effect'>])
[13]:
# Model summary
print(dml_obj_lasso)
================== DoubleMLDIDMulti Object ==================
------------------ Data summary ------------------
Outcome variable: lemp
Treatment variable(s): ['first.treat']
Covariates: ['lpop']
Instrument variable(s): None
Time variable: year
Id variable: countyreal
Static panel data: False
No. Unique Ids: 500
No. Observations: 2500
------------------ Score & algorithm ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0
------------------ Machine learner ------------------
Learner ml_g: LassoCV()
Learner ml_m: LogisticRegressionCV()
Out-of-sample Performance:
Regression:
Learner ml_g0 RMSE: [[0.17269217 0.18178547 0.25926093 0.25950004 0.17215641 0.15244844
0.20070333 0.20625204 0.17377565 0.15157103 0.20144611 0.16383329]]
Learner ml_g1 RMSE: [[0.10510552 0.1299445 0.14116618 0.15416316 0.13994142 0.11371529
0.08674632 0.10927721 0.13277137 0.16158981 0.15939375 0.1595057 ]]
Classification:
Learner ml_m Log Loss: [[0.22913875 0.22913576 0.22913671 0.22913872 0.35596065 0.35596229
0.35595924 0.35595795 0.60884079 0.60884784 0.60888834 0.60884994]]
------------------ Resampling ------------------
No. folds: 10
No. repeated sample splits: 1
------------------ Fit summary ------------------
coef std err t P>|t| 2.5 % \
ATT(2004.0,2003,2004) -0.014523 0.022805 -0.636828 0.524237 -0.059219
ATT(2004.0,2003,2005) -0.077672 0.028928 -2.684962 0.007254 -0.134370
ATT(2004.0,2003,2006) -0.137566 0.035757 -3.847204 0.000119 -0.207649
ATT(2004.0,2003,2007) -0.106771 0.032977 -3.237720 0.001205 -0.171405
ATT(2006.0,2003,2004) -0.001614 0.023323 -0.069210 0.944822 -0.047326
ATT(2006.0,2004,2005) -0.005530 0.019369 -0.285505 0.775257 -0.043492
ATT(2006.0,2005,2006) -0.004326 0.017734 -0.243941 0.807277 -0.039084
ATT(2006.0,2005,2007) -0.041232 0.020260 -2.035131 0.041838 -0.080941
ATT(2007.0,2003,2004) 0.027033 0.015204 1.778015 0.075401 -0.002766
ATT(2007.0,2004,2005) -0.003638 0.016401 -0.221817 0.824457 -0.035784
ATT(2007.0,2005,2006) -0.030873 0.017988 -1.716343 0.086099 -0.066128
ATT(2007.0,2006,2007) -0.028852 0.016768 -1.720696 0.085306 -0.061717
97.5 %
ATT(2004.0,2003,2004) 0.030174
ATT(2004.0,2003,2005) -0.020973
ATT(2004.0,2003,2006) -0.067483
ATT(2004.0,2003,2007) -0.042137
ATT(2006.0,2003,2004) 0.044098
ATT(2006.0,2004,2005) 0.032432
ATT(2006.0,2005,2006) 0.030432
ATT(2006.0,2005,2007) -0.001523
ATT(2007.0,2003,2004) 0.056832
ATT(2007.0,2004,2005) 0.028508
ATT(2007.0,2005,2006) 0.004382
ATT(2007.0,2006,2007) 0.004012
[14]:
es_rf = dml_obj_lasso.aggregate("eventstudy")
es_rf.aggregated_frameworks.bootstrap()
es_rf.plot_effects(title="Estimated ATTs by Group, LassoCV and LogisticRegressionCV()")
[14]:
(<Figure size 1200x600 with 1 Axes>,
<Axes: title={'center': 'Estimated ATTs by Group, LassoCV and LogisticRegressionCV()'}, ylabel='Effect'>)