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 = 10000
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()
(59970, 11)
[2]:
id y y0 y1 d t Z1 Z2 Z3 Z4 ite
0 0 212.625950 212.625950 211.381228 4.0 0 0.239446 -0.738630 -0.247806 -0.056120 -1.244722
1 0 214.132519 214.132519 214.126916 4.0 1 0.239446 -0.738630 -0.247806 -0.056120 -0.005603
3 0 218.472192 218.472192 217.531586 4.0 3 0.239446 -0.738630 -0.247806 -0.056120 -0.940606
5 0 224.610703 221.924248 224.610703 4.0 5 0.239446 -0.738630 -0.247806 -0.056120 2.686455
6 1 205.040139 205.040139 204.747278 5.0 0 -0.674319 -1.715196 -0.518845 -1.798885 -0.292862

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

\[\begin{split}\begin{align*} Y_{i,t}(0)&:= f_t(Z) + \delta_t + \eta_i + \varepsilon_{i,t,0}\\ Y_{i,t}(1)&:= Y_{i,t}(0) + \theta_{i,t,\mathrm{g}} + \epsilon_{i,t,1} - \epsilon_{i,t,0} \end{align*}\end{split}\]

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

\[\theta_{i,t,\mathrm{g}}:= 0 \text{ for } t<\mathrm{g}\]

such that

\[\mathbb{E}[Y_{i,t}(1) - Y_{i,t}(0)] = \mathbb{E}[\epsilon_{i,t,1} - \epsilon_{i,t,0}]=0 \text{ for } t<\mathrm{g}\]

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     9912
1     9966
2    10098
3    10019
4    10001
5     9974
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    15544
4.0    14440
5.0    14468
inf    15518
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    15544
4.0    14440
5.0    14468
inf    15518
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.632995 198.604011 218.888239 -0.028220 -2.326351 2.296389
1 0 4.0 210.635043 200.638194 220.654401 -0.021842 -2.312869 2.379051
2 0 5.0 212.494930 202.436845 222.726232 -0.015440 -2.421521 2.265363
3 0 inf 214.570692 204.411215 225.055322 0.027537 -2.340189 2.366986
4 1 3.0 208.483092 188.615209 228.438537 -0.018223 -2.375088 2.365177
[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)
../../_images/examples_did_py_rep_cs_16_1.png

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):

\[ATT(\mathrm{g}, t) = \min(\mathrm{t} - \mathrm{g} + 1, 0) =: e\]
[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)
../../_images/examples_did_py_rep_cs_18_1.png

DoubleMLPanelData#

Finally, we can construct our DoubleMLPanelData, specifying

  • y_col : the outcome

  • d_cols: the group variable indicating the first treated period for each unit

  • id_col: the unique identification column for each unit

  • t_col : the time column

  • x_cols: the additional pre-treatment controls

  • datetime_unit: unit required for datetime 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: 19704
No. Observations: 59970

------------------ DataFrame info    ------------------
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 59970 entries, 0 to 59969
Columns: 11 entries, id to ite
dtypes: float64(9), int64(2)
memory usage: 5.0 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 learner

  • ml_m propensity Score learner

  • control_group the control group for the parallel trend assumption

  • gt_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: 19704
No. Observations: 59970

------------------ 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.7865872  2.5499725  3.45828123 3.44127812 3.42654824 1.78299613
  2.54139818 3.39996997 4.56327232 4.60750488 1.78032571 2.51846698
  3.43543688 4.50536577 5.18335797]]
Learner ml_g_d0_t1 RMSE: [[2.52732041 3.43993449 4.58185345 5.19929475 6.12690934 2.55321626
  3.41495635 4.53511151 5.2205336  6.33153576 2.52749098 3.41775942
  4.61988459 5.18551018 6.3589551 ]]
Learner ml_g_d1_t0 RMSE: [[1.78653422 2.48918051 3.38064094 3.44097737 3.35283906 1.80665762
  2.51089359 3.42622683 4.24390561 4.19877413 1.81002084 2.5998908
  3.47615288 4.50353441 5.54621856]]
Learner ml_g_d1_t1 RMSE: [[2.52987076 3.38700256 4.45397249 5.24516115 6.26410825 2.5687224
  3.4531084  4.14659004 5.49888811 6.08357776 2.63489968 3.49869875
  4.50379354 5.57111297 6.27638964]]
Classification:
Learner ml_m Log Loss: [[0.6171256  0.61336179 0.61518888 0.61545173 0.62083859 0.64578228
  0.64621116 0.64606074 0.64877932 0.65002473 0.66377109 0.66459015
  0.66686516 0.66686444 0.66749887]]

------------------ 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.125405  0.135494  -0.925537  3.546866e-01 -0.390969  0.140159
ATT(3.0,1,2) -0.125875  0.160363  -0.784943  4.324871e-01 -0.440180  0.188429
ATT(3.0,2,3)  0.948522  0.218427   4.342506  1.408669e-05  0.520412  1.376632
ATT(3.0,2,4)  1.873369  0.319014   5.872371  4.296070e-09  1.248113  2.498626
ATT(3.0,2,5)  3.365993  0.271058  12.417981  0.000000e+00  2.834729  3.897257
ATT(4.0,0,1)  0.000448  0.106274   0.004218  9.966342e-01 -0.207845  0.208741
ATT(4.0,1,2) -0.091479  0.153867  -0.594532  5.521563e-01 -0.393053  0.210095
ATT(4.0,2,3)  0.068030  0.177290   0.383725  7.011826e-01 -0.279451  0.415512
ATT(4.0,3,4)  0.710137  0.250092   2.839502  4.518405e-03  0.219965  1.200308
ATT(4.0,3,5)  2.171263  0.275471   7.882003  3.330669e-15  1.631350  2.711176
ATT(5.0,0,1)  0.051074  0.094977   0.537748  5.907512e-01 -0.135078  0.237226
ATT(5.0,1,2) -0.215085  0.129063  -1.666508  9.561232e-02 -0.468045  0.037874
ATT(5.0,2,3) -0.156651  0.170697  -0.917713  3.587690e-01 -0.491210  0.177909
ATT(5.0,3,4) -0.137125  0.213100  -0.643480  5.199130e-01 -0.554793  0.280543
ATT(5.0,4,5)  1.245566  0.270474   4.605130  4.122089e-06  0.715447  1.775684

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.519530 0.268720
ATT(3.0,1,2) -0.592337 0.340586
ATT(3.0,2,3) 0.313162 1.583883
ATT(3.0,2,4) 0.945423 2.801316
ATT(3.0,2,5) 2.577541 4.154445
ATT(4.0,0,1) -0.308680 0.309577
ATT(4.0,1,2) -0.539047 0.356089
ATT(4.0,2,3) -0.447669 0.583730
ATT(4.0,3,4) -0.017330 1.437603
ATT(4.0,3,5) 1.369975 2.972551
ATT(5.0,0,1) -0.225195 0.327343
ATT(5.0,1,2) -0.590504 0.160334
ATT(5.0,2,3) -0.653172 0.339871
ATT(5.0,3,4) -0.756989 0.482738
ATT(5.0,4,5) 0.458814 2.032317

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'>])
../../_images/examples_did_py_rep_cs_30_2.png

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.667156    -0.443901 -0.125405     0.193091  0.416470
ATT(3.0,1,2) -0.853916    -0.588044 -0.125875     0.336293  0.599141
ATT(3.0,2,3) -0.007604     0.352867  0.948522     1.544178  1.903949
ATT(3.0,2,4)  0.719217     1.231964  1.873369     2.514775  3.053681
ATT(3.0,2,5)  2.185480     2.630222  3.365993     4.101764  4.550611
ATT(4.0,0,1) -0.470060    -0.296714  0.000448     0.297611  0.474415
ATT(4.0,1,2) -0.752979    -0.498968 -0.091479     0.316010  0.568874
ATT(4.0,2,3) -0.753505    -0.461129  0.068030     0.597190  0.889027
ATT(4.0,3,4) -0.360580     0.050855  0.710137     1.369419  1.781847
ATT(4.0,3,5)  1.003224     1.454322  2.171263     2.888204  3.344609
ATT(5.0,0,1) -0.392811    -0.236296  0.051074     0.338443  0.494761
ATT(5.0,1,2) -0.817660    -0.605041 -0.215085     0.174871  0.387433
ATT(5.0,2,3) -0.958681    -0.676970 -0.156651     0.363669  0.644368
ATT(5.0,3,4) -1.123779    -0.772698 -0.137125     0.498448  0.849440
ATT(5.0,4,5)  0.049138     0.495106  1.245566     1.996025  2.441068

------------------ Robustness Values ------------------
              H_0     RV (%)    RVa (%)
ATT(3.0,0,1)  0.0   1.192310   0.000411
ATT(3.0,1,2)  0.0   0.826329   0.000413
ATT(3.0,2,3)  0.0   4.734336   2.962521
ATT(3.0,2,4)  0.0   8.509692   6.304195
ATT(3.0,2,5)  0.0  12.997830  11.356077
ATT(4.0,0,1)  0.0   0.004457   0.000351
ATT(4.0,1,2)  0.0   0.681641   0.000612
ATT(4.0,2,3)  0.0   0.390681   0.000584
ATT(4.0,3,4)  0.0   3.227679   1.371244
ATT(4.0,3,5)  0.0   8.809246   7.048694
ATT(5.0,0,1)  0.0   0.540068   0.000626
ATT(5.0,1,2)  0.0   1.666140   0.021764
ATT(5.0,2,3)  0.0   0.913008   0.000441
ATT(5.0,3,4)  0.0   0.655187   0.000336
ATT(5.0,4,5)  0.0   4.929475   3.192888

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'>])
../../_images/examples_did_py_rep_cs_35_2.png

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'>])
../../_images/examples_did_py_rep_cs_37_2.png

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.951363
4.0    1.475177
5.0    1.039086
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.594665 0.139119 11.462604    0.0 1.321997 1.867333
------------------ Aggregated Effects         ------------------
         coef   std err          t         P>|t|     2.5 %    97.5 %
3.0  2.062628  0.190094  10.850573  0.000000e+00  1.690051  2.435206
4.0  1.440700  0.208519   6.909187  4.874323e-12  1.032009  1.849391
5.0  1.245566  0.270474   4.605130  4.122089e-06  0.715447  1.775684
------------------ 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(
../../_images/examples_did_py_rep_cs_42_2.png

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.992388
4    1.463337
5    2.012756
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.516479 0.131207 11.557942    0.0 1.259318 1.773639
------------------ Aggregated Effects         ------------------
       coef   std err          t         P>|t|     2.5 %    97.5 %
3  0.948522  0.218427   4.342506  1.408669e-05  0.520412  1.376632
4  1.313168  0.237893   5.519993  3.390126e-08  0.846906  1.779430
5  2.287746  0.207363  11.032565  0.000000e+00  1.881322  2.694170
------------------ 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(
../../_images/examples_did_py_rep_cs_47_2.png

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.014531
-3.0    0.003359
-2.0   -0.023631
-1.0   -0.003398
 0.0    1.002537
 1.0    1.948164
 2.0    2.938621
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.116863 0.159272 13.290852    0.0 1.804695 2.429031
------------------ Aggregated Effects         ------------------
          coef   std err          t     P>|t|     2.5 %    97.5 %
-4.0  0.051074  0.094977   0.537748  0.590751 -0.135078  0.237226
-3.0 -0.107423  0.073320  -1.465117  0.142889 -0.251128  0.036282
-2.0 -0.124554  0.070010  -1.779084  0.075226 -0.261771  0.012663
-1.0 -0.066548  0.087363  -0.761737  0.446217 -0.237776  0.104681
0.0   0.967764  0.115450   8.382521  0.000000  0.741486  1.194042
1.0   2.016832  0.212015   9.512688  0.000000  1.601290  2.432374
2.0   3.365993  0.271058  12.417981  0.000000  2.834729  3.897257
------------------ 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'>)
../../_images/examples_did_py_rep_cs_51_3.png

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 aggregation

  • aggregation_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.116863 0.159272 13.290852    0.0 1.804695 2.429031
------------------ Aggregated Effects         ------------------
          coef   std err          t     P>|t|     2.5 %    97.5 %
-4.0  0.051074  0.094977   0.537748  0.590751 -0.135078  0.237226
-3.0 -0.107423  0.073320  -1.465117  0.142889 -0.251128  0.036282
-2.0 -0.124554  0.070010  -1.779084  0.075226 -0.261771  0.012663
-1.0 -0.066548  0.087363  -0.761737  0.446217 -0.237776  0.104681
0.0   0.967764  0.115450   8.382521  0.000000  0.741486  1.194042
1.0   2.016832  0.212015   9.512688  0.000000  1.601290  2.432374
2.0   3.365993  0.271058  12.417981  0.000000  2.834729  3.897257
------------------ 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.34968055, 0.        , 0.        ,
       0.        , 0.        , 0.        , 0.32484478, 0.        ,
       0.        , 0.        , 0.        , 0.        , 0.32547467])

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.125405
ATT(3.0,1,2)   -0.125875
ATT(3.0,2,3)    0.948522
ATT(3.0,2,4)    1.873369
ATT(3.0,2,5)    3.365993
ATT(4.0,0,1)    0.000448
ATT(4.0,1,2)   -0.091479
ATT(4.0,2,3)    0.068030
ATT(4.0,3,4)    0.710137
ATT(4.0,3,5)    2.171263
ATT(5.0,0,1)    0.051074
ATT(5.0,1,2)   -0.215085
ATT(5.0,2,3)   -0.156651
ATT(5.0,3,4)   -0.137125
ATT(5.0,4,5)    1.245566
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()

(19264, 10)
[28]:
id y y0 y1 d t Z1 Z2 Z3 Z4
1 0 213.826528 213.826528 213.911413 2025-05-01 2025-01-01 -0.009165 -0.145614 -0.257565 0.656840
3 0 217.888343 217.888343 220.911597 2025-05-01 2025-03-01 -0.009165 -0.145614 -0.257565 0.656840
4 0 221.118776 222.336601 221.118776 2025-05-01 2025-04-01 -0.009165 -0.145614 -0.257565 0.656840
9 1 207.761823 207.761823 209.217407 2025-05-01 2025-02-01 -0.438855 0.171554 -0.031337 -0.190678
11 1 205.456974 206.109196 205.456974 2025-05-01 2025-04-01 -0.438855 0.171554 -0.031337 -0.190678

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.623310 191.890460 225.512725 -0.016423 -2.282435 2.458502
1 2025-01-01 2025-05-01 211.219607 194.391454 227.488644 -0.056376 -2.335278 2.306863
2 2025-01-01 2025-06-01 213.407065 195.410926 232.273737 -0.034195 -2.318740 2.174726
3 2025-02-01 2025-04-01 207.571694 180.225595 233.796352 0.034257 -2.363712 2.285748
4 2025-02-01 2025-05-01 211.520605 185.702520 235.823887 0.033413 -2.257888 2.464469

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')
../../_images/examples_did_py_rep_cs_66_0.png

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'>])
../../_images/examples_did_py_rep_cs_70_2.png

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'>])
../../_images/examples_did_py_rep_cs_72_2.png

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'>])
../../_images/examples_did_py_rep_cs_75_1.png

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'>])
../../_images/examples_did_py_rep_cs_77_2.png

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'>])
../../_images/examples_did_py_rep_cs_79_1.png