Python: Panel Data with Multiple Time Periods#

In this example, a detailed guide on Difference-in-Differences with multiple time periods using the DoubleML-package. The implementation is based on Callaway and Sant’Anna(2021).

The notebook requires the following packages:

[1]:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

from lightgbm import LGBMRegressor, LGBMClassifier
from sklearn.linear_model import LinearRegression, LogisticRegression

from doubleml.did import DoubleMLDIDMulti
from doubleml.data import DoubleMLPanelData

from doubleml.did.datasets import make_did_CS2021

Data#

We will rely on the make_did_CS2021 DGP, which is inspired by Callaway and Sant’Anna(2021) (Appendix SC) and Sant’Anna and Zhao (2020).

We will observe n_obs units over n_periods. Remark that the dataframe includes observations of the potential outcomes y0 and y1, such that we can use oracle estimates as comparisons.

[2]:
n_obs = 5000
n_periods = 6

df = make_did_CS2021(n_obs, dgp_type=4, n_periods=n_periods, n_pre_treat_periods=3, time_type="datetime")
df["ite"] = df["y1"] - df["y0"]

print(df.shape)
df.head()
(30000, 11)
[2]:
id y y0 y1 d t Z1 Z2 Z3 Z4 ite
0 0 212.224990 212.224990 212.798173 NaT 2025-01-01 -0.471462 0.43136 0.004989 -0.038153 0.573183
1 0 211.317387 211.317387 210.454496 NaT 2025-02-01 -0.471462 0.43136 0.004989 -0.038153 -0.862891
2 0 208.285053 208.285053 210.533617 NaT 2025-03-01 -0.471462 0.43136 0.004989 -0.038153 2.248564
3 0 208.374208 208.374208 209.663793 NaT 2025-04-01 -0.471462 0.43136 0.004989 -0.038153 1.289585
4 0 207.813743 207.813743 208.794432 NaT 2025-05-01 -0.471462 0.43136 0.004989 -0.038153 0.980689

Data Details#

Here, we slightly abuse the definition of the potential outcomes. :math:`Y_{i,t}(1)` corresponds to the (potential) outcome if unit :math:`i` would have received treatment at time period :math:`mathrm{g}` (where the group :math:`mathrm{g}` is drawn with probabilities based on :math:`Z`).

More specifically

\[\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
2025-01-01    5000
2025-02-01    5000
2025-03-01    5000
2025-04-01    5000
2025-05-01    5000
2025-06-01    5000
dtype: int64

The treatment column d indicates first treatment period of the corresponding unit, whereas NaT units are never treated.

Generally, never treated units should take either on the value ``np.inf`` or ``pd.NaT`` depending on the data type (``float`` or ``datetime``).

The individual units are roughly uniformly divided between the groups, where treatment assignment depends on the pre-treatment covariates Z1 to Z4.

[4]:
df.groupby("d", dropna=False).size()
[4]:
d
2025-04-01    7410
2025-05-01    7824
2025-06-01    6924
NaT           7842
dtype: int64

Here, the group indicates the first treated period and NaT units are never treated. To simplify plotting and pands

[5]:
df.groupby("d", dropna=False).size()
[5]:
d
2025-04-01    7410
2025-05-01    7824
2025-06-01    6924
NaT           7842
dtype: int64

To get a better understanding of the underlying data and true effects, we will compare the unconditional averages and the true effects based on the oracle values of individual effects ite.

[6]:
# rename for plotting
df["First Treated"] = df["d"].dt.strftime("%Y-%m").fillna("Never Treated")

# Create aggregation dictionary for means
def agg_dict(col_name):
    return {
        f'{col_name}_mean': (col_name, 'mean'),
        f'{col_name}_lower_quantile': (col_name, lambda x: x.quantile(0.05)),
        f'{col_name}_upper_quantile': (col_name, lambda x: x.quantile(0.95))
    }

# Calculate means and confidence intervals
agg_dictionary = agg_dict("y") | agg_dict("ite")

agg_df = df.groupby(["t", "First Treated"]).agg(**agg_dictionary).reset_index()
agg_df.head()
[6]:
t First Treated y_mean y_lower_quantile y_upper_quantile ite_mean ite_lower_quantile ite_upper_quantile
0 2025-01-01 2025-04 208.797967 198.412617 218.914990 -0.003349 -2.429375 2.243840
1 2025-01-01 2025-05 210.974093 201.133361 221.074290 -0.024895 -2.168300 2.275224
2 2025-01-01 2025-06 212.478447 202.335574 222.417694 0.042273 -2.404098 2.342429
3 2025-01-01 Never Treated 214.330828 204.113681 224.116315 -0.022989 -2.412944 2.202708
4 2025-02-01 2025-04 208.576363 188.346995 228.353390 0.045930 -2.363351 2.362171
[7]:
def plot_data(df, col_name='y'):
    """
    Create an improved plot with colorblind-friendly features

    Parameters:
    -----------
    df : DataFrame
        The dataframe containing the data
    col_name : str, default='y'
        Column name to plot (will use '{col_name}_mean')
    """
    plt.figure(figsize=(12, 7))
    n_colors = df["First Treated"].nunique()
    color_palette = sns.color_palette("colorblind", n_colors=n_colors)

    sns.lineplot(
        data=df,
        x='t',
        y=f'{col_name}_mean',
        hue='First Treated',
        style='First Treated',
        palette=color_palette,
        markers=True,
        dashes=True,
        linewidth=2.5,
        alpha=0.8
    )

    plt.title(f'Average Values {col_name} by Group Over Time', fontsize=16)
    plt.xlabel('Time', fontsize=14)
    plt.ylabel(f'Average Value {col_name}', fontsize=14)


    plt.legend(title='First Treated', title_fontsize=13, fontsize=12,
               frameon=True, framealpha=0.9, loc='best')

    plt.grid(alpha=0.3, linestyle='-')
    plt.tight_layout()

    plt.show()

So let us take a look at the average values over time

[8]:
plot_data(agg_df, col_name='y')
../../_images/examples_did_py_panel_16_0.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')
../../_images/examples_did_py_panel_18_0.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"],
    datetime_unit="M"
)
print(dml_data)
================== DoubleMLPanelData Object ==================

------------------ Data summary      ------------------
Outcome variable: y
Treatment variable(s): ['d']
Covariates: ['Z1', 'Z2', 'Z3', 'Z4']
Instrument variable(s): None
Time variable: t
Id variable: id
No. Observations: 5000

------------------ DataFrame info    ------------------
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 30000 entries, 0 to 29999
Columns: 12 entries, id to First Treated
dtypes: datetime64[s](2), float64(8), int64(1), object(1)
memory usage: 2.7+ MB

ATT Estimation#

The DoubleML-package implements estimation of group-time average treatment effect via the DoubleMLDIDMulti class (see model documentation).

Basics#

The class basically behaves like other DoubleML classes and requires the specification of two learners (for more details on the regression elements, see score documentation).

The basic arguments of a DoubleMLDIDMulti object include

  • ml_g “outcome” regression 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.

[11]:
default_args = {
    "ml_g": LGBMRegressor(n_estimators=500, learning_rate=0.01, verbose=-1, random_state=123),
    "ml_m": LGBMClassifier(n_estimators=500, learning_rate=0.01, verbose=-1, random_state=123),
    "control_group": "never_treated",
    "gt_combinations": "standard",
    "anticipation_periods": 0,
    "n_folds": 5,
    "n_rep": 1,
}

The model will be estimated using the fit() method.

[12]:
dml_obj = DoubleMLDIDMulti(dml_data, **default_args)
dml_obj.fit()
print(dml_obj)
================== DoubleMLDIDMulti Object ==================

------------------ Data summary      ------------------
Outcome variable: y
Treatment variable(s): ['d']
Covariates: ['Z1', 'Z2', 'Z3', 'Z4']
Instrument variable(s): None
Time variable: t
Id variable: id
No. Observations: 5000

------------------ Score & algorithm ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0

------------------ Machine learner   ------------------
Learner ml_g: LGBMRegressor(learning_rate=0.01, n_estimators=500, random_state=123,
              verbose=-1)
Learner ml_m: LGBMClassifier(learning_rate=0.01, n_estimators=500, random_state=123,
               verbose=-1)
Out-of-sample Performance:
Regression:
Learner ml_g0 RMSE: [[1.91409503 1.93546772 1.86909374 2.75968703 3.84044494 1.90125521
  1.90625188 1.90680345 1.9537342  2.83297825 1.88131501 1.89563661
  1.89018583 1.96635777 1.96588916]]
Learner ml_g1 RMSE: [[1.95579341 1.99400917 1.97139663 2.92333873 4.0006495  1.88978711
  1.91081311 1.94479424 1.90639427 2.77944468 1.99798051 1.99368191
  1.88481716 1.94194155 1.99511249]]
Classification:
Learner ml_m Log Loss: [[0.68646713 0.67746014 0.6857181  0.68148534 0.68148089 0.70499157
  0.70865004 0.71083756 0.70613659 0.70861802 0.72169744 0.72210268
  0.72067539 0.72317315 0.7264042 ]]

------------------ Resampling        ------------------
No. folds: 5
No. repeated sample splits: 1

------------------ Fit summary       ------------------
                                  coef   std err          t         P>|t|  \
ATT(2025-04,2025-01,2025-02) -0.096728  0.125215  -0.772491  4.398237e-01
ATT(2025-04,2025-02,2025-03)  0.069577  0.118056   0.589359  5.556208e-01
ATT(2025-04,2025-03,2025-04)  0.994951  0.120115   8.283308  2.220446e-16
ATT(2025-04,2025-03,2025-05)  1.973872  0.219334   8.999404  0.000000e+00
ATT(2025-04,2025-03,2025-06)  2.808329  0.279049  10.063928  0.000000e+00
ATT(2025-05,2025-01,2025-02)  0.002848  0.092529   0.030781  9.754441e-01
ATT(2025-05,2025-02,2025-03) -0.005956  0.098411  -0.060527  9.517361e-01
ATT(2025-05,2025-03,2025-04)  0.011261  0.103439   0.108864  9.133104e-01
ATT(2025-05,2025-04,2025-05)  1.129407  0.096260  11.732834  0.000000e+00
ATT(2025-05,2025-04,2025-06)  2.184273  0.165614  13.188933  0.000000e+00
ATT(2025-06,2025-01,2025-02) -0.017474  0.088269  -0.197958  8.430783e-01
ATT(2025-06,2025-02,2025-03) -0.016254  0.085915  -0.189183  8.499495e-01
ATT(2025-06,2025-03,2025-04) -0.118917  0.091212  -1.303754  1.923175e-01
ATT(2025-06,2025-04,2025-05)  0.029758  0.091143   0.326502  7.440443e-01
ATT(2025-06,2025-05,2025-06)  1.136641  0.090506  12.558761  0.000000e+00

                                 2.5 %    97.5 %
ATT(2025-04,2025-01,2025-02) -0.342146  0.148690
ATT(2025-04,2025-02,2025-03) -0.161808  0.300962
ATT(2025-04,2025-03,2025-04)  0.759529  1.230372
ATT(2025-04,2025-03,2025-05)  1.543986  2.403758
ATT(2025-04,2025-03,2025-06)  2.261403  3.355255
ATT(2025-05,2025-01,2025-02) -0.178506  0.184202
ATT(2025-05,2025-02,2025-03) -0.198838  0.186925
ATT(2025-05,2025-03,2025-04) -0.191476  0.213997
ATT(2025-05,2025-04,2025-05)  0.940740  1.318074
ATT(2025-05,2025-04,2025-06)  1.859676  2.508871
ATT(2025-06,2025-01,2025-02) -0.190478  0.155531
ATT(2025-06,2025-02,2025-03) -0.184644  0.152136
ATT(2025-06,2025-03,2025-04) -0.297689  0.059854
ATT(2025-06,2025-04,2025-05) -0.148879  0.208396
ATT(2025-06,2025-05,2025-06)  0.959253  1.314029

The summary displays estimates of the \(ATT(g,t_\text{eval})\) effects for different combinations of \((g,t_\text{eval})\) via \(\widehat{ATT}(\mathrm{g},t_\text{pre},t_\text{eval})\), where

  • \(\mathrm{g}\) specifies the group

  • \(t_\text{pre}\) specifies the corresponding pre-treatment period

  • \(t_\text{eval}\) specifies the evaluation period

The choice gt_combinations="standard", used estimates all possible combinations of \(ATT(g,t_\text{eval})\) via \(\widehat{ATT}(\mathrm{g},t_\text{pre},t_\text{eval})\), where the standard choice is \(t_\text{pre} = \min(\mathrm{g}, t_\text{eval}) - 1\) (without anticipation).

Remark that this includes pre-tests effects if \(\mathrm{g} > t_{eval}\), e.g. \(\widehat{ATT}(g=\text{2025-04}, t_{\text{pre}}=\text{2025-01}, t_{\text{eval}}=\text{2025-02})\) which estimates the pre-trend from January to February even if the actual treatment occured in April.

As usual for the DoubleML-package, you can obtain joint confidence intervals via bootstrap.

[13]:
level = 0.95

ci = dml_obj.confint(level=level)
dml_obj.bootstrap(n_rep_boot=5000)
ci_joint = dml_obj.confint(level=level, joint=True)
ci_joint
[13]:
2.5 % 97.5 %
ATT(2025-04,2025-01,2025-02) -0.457339 0.263884
ATT(2025-04,2025-02,2025-03) -0.270414 0.409569
ATT(2025-04,2025-03,2025-04) 0.649028 1.340874
ATT(2025-04,2025-03,2025-05) 1.342207 2.605537
ATT(2025-04,2025-03,2025-06) 2.004688 3.611970
ATT(2025-05,2025-01,2025-02) -0.263630 0.269326
ATT(2025-05,2025-02,2025-03) -0.289372 0.277459
ATT(2025-05,2025-03,2025-04) -0.286636 0.309157
ATT(2025-05,2025-04,2025-05) 0.852184 1.406630
ATT(2025-05,2025-04,2025-06) 1.707317 2.661230
ATT(2025-06,2025-01,2025-02) -0.271683 0.236736
ATT(2025-06,2025-02,2025-03) -0.263682 0.231175
ATT(2025-06,2025-03,2025-04) -0.381600 0.143765
ATT(2025-06,2025-04,2025-05) -0.232727 0.292244
ATT(2025-06,2025-05,2025-06) 0.875991 1.397291

A visualization of the effects can be obtained via the plot_effects() method.

Remark that the plot used joint confidence intervals per default.

[14]:
dml_obj.plot_effects()
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
  return math.isfinite(val)
[14]:
(<Figure size 1200x800 with 4 Axes>,
 [<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])
../../_images/examples_did_py_panel_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  \
ATT(2025-04,2025-01,2025-02) -0.413352    -0.196356 -0.096728     0.002900
ATT(2025-04,2025-02,2025-03) -0.229018    -0.039358  0.069577     0.178512
ATT(2025-04,2025-03,2025-04)  0.692586     0.892030  0.994951     1.097872
ATT(2025-04,2025-03,2025-05)  1.459346     1.834944  1.973872     2.112800
ATT(2025-04,2025-03,2025-06)  2.100907     2.559835  2.808329     3.056823
ATT(2025-05,2025-01,2025-02) -0.257036    -0.104526  0.002848     0.110223
ATT(2025-05,2025-02,2025-03) -0.275219    -0.112488 -0.005956     0.100576
ATT(2025-05,2025-03,2025-04) -0.261572    -0.091100  0.011261     0.113621
ATT(2025-05,2025-04,2025-05)  0.860733     1.019042  1.129407     1.239773
ATT(2025-05,2025-04,2025-06)  1.766494     2.033765  2.184273     2.334782
ATT(2025-06,2025-01,2025-02) -0.268831    -0.123538 -0.017474     0.088591
ATT(2025-06,2025-02,2025-03) -0.261550    -0.119841 -0.016254     0.087334
ATT(2025-06,2025-03,2025-04) -0.372029    -0.221770 -0.118917    -0.016065
ATT(2025-06,2025-04,2025-05) -0.226637    -0.076744  0.029758     0.136260
ATT(2025-06,2025-05,2025-06)  0.878887     1.027452  1.136641     1.245830

                              CI upper
ATT(2025-04,2025-01,2025-02)  0.200872
ATT(2025-04,2025-02,2025-03)  0.379699
ATT(2025-04,2025-03,2025-04)  1.296438
ATT(2025-04,2025-03,2025-05)  2.466542
ATT(2025-04,2025-03,2025-06)  3.517872
ATT(2025-05,2025-01,2025-02)  0.262818
ATT(2025-05,2025-02,2025-03)  0.262180
ATT(2025-05,2025-03,2025-04)  0.284156
ATT(2025-05,2025-04,2025-05)  1.398646
ATT(2025-05,2025-04,2025-06)  2.613937
ATT(2025-06,2025-01,2025-02)  0.234072
ATT(2025-06,2025-02,2025-03)  0.228731
ATT(2025-06,2025-03,2025-04)  0.134118
ATT(2025-06,2025-04,2025-05)  0.286548
ATT(2025-06,2025-05,2025-06)  1.395374

------------------ Robustness Values ------------------
                              H_0     RV (%)    RVa (%)
ATT(2025-04,2025-01,2025-02)  0.0   2.914026   0.000391
ATT(2025-04,2025-02,2025-03)  0.0   1.926781   0.000393
ATT(2025-04,2025-03,2025-04)  0.0  25.428591  19.447949
ATT(2025-04,2025-03,2025-05)  0.0  34.914581  24.650150
ATT(2025-04,2025-03,2025-06)  0.0  29.005515  24.317781
ATT(2025-05,2025-01,2025-02)  0.0   0.080622   0.000602
ATT(2025-05,2025-02,2025-03)  0.0   0.170018   0.000575
ATT(2025-05,2025-03,2025-04)  0.0   0.334379   0.000574
ATT(2025-05,2025-04,2025-05)  0.0  26.689224  23.114234
ATT(2025-05,2025-04,2025-06)  0.0  35.502185  31.196336
ATT(2025-06,2025-01,2025-02)  0.0   0.500726   0.000600
ATT(2025-06,2025-02,2025-03)  0.0   0.476638   0.000618
ATT(2025-06,2025-03,2025-04)  0.0   3.460389   0.000470
ATT(2025-06,2025-04,2025-05)  0.0   0.847647   0.000615
ATT(2025-06,2025-05,2025-06)  0.0  27.077720  23.804469

In this example one can clearly, distinguish the robustness of the non-zero effects vs. the pre-treatment periods.

Control Groups#

The current implementation support the following control groups

  • "never_treated"

  • "not_yet_treated"

Remark that the ``”not_yet_treated” depends on anticipation.

For differences and recommendations, we refer to Callaway and Sant’Anna(2021).

[16]:
dml_obj_nyt = DoubleMLDIDMulti(dml_data, **(default_args | {"control_group": "not_yet_treated"}))
dml_obj_nyt.fit()
dml_obj_nyt.bootstrap(n_rep_boot=5000)
dml_obj_nyt.plot_effects()
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
  return math.isfinite(val)
[16]:
(<Figure size 1200x800 with 4 Axes>,
 [<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])
../../_images/examples_did_py_panel_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.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
  return math.isfinite(val)
[17]:
(<Figure size 1200x800 with 4 Axes>,
 [<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])
../../_images/examples_did_py_panel_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
2025-04-01    1.997602
2025-05-01    1.544618
2025-06-01    0.963225
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.584204 0.104473 15.163801    0.0 1.379441 1.788967
------------------ Aggregated Effects         ------------------
             coef   std err          t  P>|t|     2.5 %    97.5 %
2025-04  1.925717  0.189482  10.163045    0.0  1.554339  2.297096
2025-05  1.656840  0.121669  13.617552    0.0  1.418373  1.895308
2025-06  1.136641  0.090506  12.558761    0.0  0.959253  1.314029
------------------ Additional Information     ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0

/opt/hostedtoolcache/Python/3.12.10/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(
../../_images/examples_did_py_panel_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
2025-04-01    1.029053
2025-05-01    1.528934
2025-06-01    2.000594
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.533572 0.118062 12.989516    0.0 1.302174 1.76497
------------------ Aggregated Effects         ------------------
             coef   std err          t         P>|t|     2.5 %    97.5 %
2025-04  0.994951  0.120115   8.283308  2.220446e-16  0.759529  1.230372
2025-05  1.540165  0.135995  11.325198  0.000000e+00  1.273621  1.806710
2025-06  2.065601  0.146351  14.114045  0.000000e+00  1.778758  2.352443
------------------ Additional Information     ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0

/opt/hostedtoolcache/Python/3.12.10/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(
../../_images/examples_did_py_panel_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["e"] = pd.to_datetime(df["t"]).values.astype("datetime64[M]") - \
    pd.to_datetime(df["d"]).values.astype("datetime64[M]")
df.groupby("e")["ite"].mean()[1:]
[22]:
e
-122 days   -0.015153
-92 days    -0.042707
-61 days     0.027309
-31 days     0.008359
0 days       1.020031
31 days      2.024916
59 days      2.941541
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.992321 0.160135 12.441484    0.0 1.678462 2.306181
------------------ Aggregated Effects         ------------------
               coef   std err          t     P>|t|     2.5 %    97.5 %
-4 months -0.017474  0.088269  -0.197958  0.843078 -0.190478  0.155531
-3 months -0.006120  0.065108  -0.093996  0.925112 -0.133729  0.121489
-2 months -0.071610  0.073657  -0.972208  0.330947 -0.215976  0.072756
-1 months  0.036543  0.071212   0.513159  0.607840 -0.103029  0.176115
0 months   1.086703  0.065967  16.473400  0.000000  0.957410  1.215997
1 months   2.081932  0.168332  12.368014  0.000000  1.752007  2.411856
2 months   2.808329  0.279049  10.063928  0.000000  2.261403  3.355255
------------------ Additional Information     ------------------
Score function: observational
Control group: never_treated
Anticipation periods: 0

/opt/hostedtoolcache/Python/3.12.10/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'>)
../../_images/examples_did_py_panel_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 %
1.992321 0.160135 12.441484    0.0 1.678462 2.306181
------------------ Aggregated Effects         ------------------
               coef   std err          t     P>|t|     2.5 %    97.5 %
-4 months -0.017474  0.088269  -0.197958  0.843078 -0.190478  0.155531
-3 months -0.006120  0.065108  -0.093996  0.925112 -0.133729  0.121489
-2 months -0.071610  0.073657  -0.972208  0.330947 -0.215976  0.072756
-1 months  0.036543  0.071212   0.513159  0.607840 -0.103029  0.176115
0 months   1.086703  0.065967  16.473400  0.000000  0.957410  1.215997
1 months   2.081932  0.168332  12.368014  0.000000  1.752007  2.411856
2 months   2.808329  0.279049  10.063928  0.000000  2.261403  3.355255
------------------ 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.33441646, 0.        , 0.        ,
       0.        , 0.        , 0.        , 0.35310046, 0.        ,
       0.        , 0.        , 0.        , 0.        , 0.31248308])

Taking a look at the original dml_obj, one can see that this combines the following estimates (only show month):

  • \(\widehat{ATT}(04,03,04)\)

  • \(\widehat{ATT}(05,04,05)\)

  • \(\widehat{ATT}(06,05,06)\)

[27]:
print(dml_obj.summary["coef"])
ATT(2025-04,2025-01,2025-02)   -0.096728
ATT(2025-04,2025-02,2025-03)    0.069577
ATT(2025-04,2025-03,2025-04)    0.994951
ATT(2025-04,2025-03,2025-05)    1.973872
ATT(2025-04,2025-03,2025-06)    2.808329
ATT(2025-05,2025-01,2025-02)    0.002848
ATT(2025-05,2025-02,2025-03)   -0.005956
ATT(2025-05,2025-03,2025-04)    0.011261
ATT(2025-05,2025-04,2025-05)    1.129407
ATT(2025-05,2025-04,2025-06)    2.184273
ATT(2025-06,2025-01,2025-02)   -0.017474
ATT(2025-06,2025-02,2025-03)   -0.016254
ATT(2025-06,2025-03,2025-04)   -0.118917
ATT(2025-06,2025-04,2025-05)    0.029758
ATT(2025-06,2025-05,2025-06)    1.136641
Name: coef, dtype: float64

Anticipation#

As described in the Model Guide, one can include anticipation periods \(\delta>0\) by setting the anticipation_periods parameter.

Data with Anticipation#

The DGP allows to include anticipation periods via the anticipation_periods parameter. In this case the observations will be “shifted” such that units anticipate the effect earlier and the exposure effect is increased by the number of periods where the effect is anticipated.

[28]:
n_obs = 4000
n_periods = 6

df_anticipation = make_did_CS2021(n_obs, dgp_type=4, n_periods=n_periods, n_pre_treat_periods=3, time_type="datetime", anticipation_periods=1)

print(df_anticipation.shape)
df_anticipation.head()

(19320, 10)
[28]:
id y y0 y1 d t Z1 Z2 Z3 Z4
1 0 203.586861 203.586861 202.671698 NaT 2025-01-01 -0.492813 -2.240663 -0.054559 -1.597145
2 0 198.081004 198.081004 197.552213 NaT 2025-02-01 -0.492813 -2.240663 -0.054559 -1.597145
3 0 193.257528 193.257528 194.295506 NaT 2025-03-01 -0.492813 -2.240663 -0.054559 -1.597145
4 0 187.233382 187.233382 189.340170 NaT 2025-04-01 -0.492813 -2.240663 -0.054559 -1.597145
5 0 183.774867 183.774867 183.179318 NaT 2025-05-01 -0.492813 -2.240663 -0.054559 -1.597145

To visualize the anticipation, we will again plot the “oracle” values

[29]:
df_anticipation["ite"] = df_anticipation["y1"] - df_anticipation["y0"]
df_anticipation["First Treated"] = df_anticipation["d"].dt.strftime("%Y-%m").fillna("Never Treated")
agg_df_anticipation = df_anticipation.groupby(["t", "First Treated"]).agg(**agg_dictionary).reset_index()
agg_df_anticipation.head()
[29]:
t First Treated y_mean y_lower_quantile y_upper_quantile ite_mean ite_lower_quantile ite_upper_quantile
0 2025-01-01 2025-04 208.227430 191.307898 225.256849 0.064640 -2.292842 2.371382
1 2025-01-01 2025-05 210.929580 194.825845 228.289747 -0.026330 -2.202958 2.153980
2 2025-01-01 2025-06 213.346744 196.722139 229.659984 -0.050970 -2.369291 2.381005
3 2025-01-01 Never Treated 217.736418 200.272937 234.269560 0.039152 -2.303172 2.247736
4 2025-02-01 2025-04 207.826850 183.050734 232.652871 0.031373 -2.429591 2.497150

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_panel_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.10/x64/lib/python3.12/site-packages/doubleml/double_ml.py:1470: UserWarning: The estimated nu2 for d is not positive. Re-estimation based on riesz representer (non-orthogonal).
  warnings.warn(msg, UserWarning)
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/doubleml/double_ml.py:1470: UserWarning: The estimated nu2 for d is not positive. Re-estimation based on riesz representer (non-orthogonal).
  warnings.warn(msg, UserWarning)
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
  return math.isfinite(val)
[32]:
(<Figure size 1200x800 with 4 Axes>,
 [<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])
../../_images/examples_did_py_panel_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.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
  return math.isfinite(val)
/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/matplotlib/cbook.py:1719: FutureWarning: Calling float on a single element Series is deprecated and will raise a TypeError in the future. Use float(ser.iloc[0]) instead
  return math.isfinite(val)
[33]:
(<Figure size 1200x800 with 4 Axes>,
 [<Axes: title={'center': 'First Treated: 2025-04'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-05'}, ylabel='Effect'>,
  <Axes: title={'center': 'First Treated: 2025-06'}, xlabel='Evaluation Period', ylabel='Effect'>])
../../_images/examples_did_py_panel_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: 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_panel_75_1.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

[35]:
gt_dict = {
    "gt_combinations": [
        (np.datetime64('2025-04'),
         np.datetime64('2025-01'),
         np.datetime64('2025-02')),
        (np.datetime64('2025-04'),
         np.datetime64('2025-02'),
         np.datetime64('2025-03')),
    ]
}

dml_obj_all = DoubleMLDIDMulti(dml_data, **(default_args| gt_dict))
dml_obj_all.fit()
dml_obj_all.bootstrap(n_rep_boot=5000)
dml_obj_all.plot_effects()
[35]:
(<Figure size 1200x800 with 2 Axes>,
 [<Axes: title={'center': 'First Treated: 2025-04'}, xlabel='Evaluation Period', ylabel='Effect'>])
../../_images/examples_did_py_panel_77_1.png