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 201.564372 201.564372 199.699800 2025-05-01 2025-01-01 -0.288006 -1.035991 -0.006924 -1.537002 -1.864572
1 0 195.472963 195.472963 193.774804 2025-05-01 2025-02-01 -0.288006 -1.035991 -0.006924 -1.537002 -1.698159
2 0 189.490055 189.490055 189.683125 2025-05-01 2025-03-01 -0.288006 -1.035991 -0.006924 -1.537002 0.193070
3 0 182.972702 182.972702 181.818057 2025-05-01 2025-04-01 -0.288006 -1.035991 -0.006924 -1.537002 -1.154646
4 0 179.047922 177.826613 179.047922 2025-05-01 2025-05-01 -0.288006 -1.035991 -0.006924 -1.537002 1.221309

Data Details#

Here, we slightly abuse the definition of the potential outcomes. \(Y_{i,t}(1)\) corresponds to the (potential) outcome if unit \(i\) would have received treatment at time period \(\mathrm{g}\) (where the group \(\mathrm{g}\) is drawn with probabilities based on \(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    7824
2025-05-01    7206
2025-06-01    7518
NaT           7452
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    7824
2025-05-01    7206
2025-06-01    7518
NaT           7452
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.689885 198.830903 218.755066 0.000767 -2.360011 2.272565
1 2025-01-01 2025-05 210.539429 200.920855 220.957644 -0.032989 -2.325725 2.293092
2 2025-01-01 2025-06 212.419433 202.701835 221.894715 -0.003835 -2.296383 2.193627
3 2025-01-01 Never Treated 214.488667 204.174823 224.394286 0.011676 -2.408228 2.268041
4 2025-02-01 2025-04 208.343290 189.072823 228.380297 0.044929 -2.350692 2.367703
[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. Unique Ids: 5000
No. Observations: 30000

------------------ 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. Unique Ids: 5000
No. Observations: 30000

------------------ 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.93834987 2.00137766 2.00313902 2.96936123 4.03847566 1.9365376
  2.00618649 1.97756466 1.93325324 2.96648818 1.93103038 1.97338586
  1.96697984 1.94281321 1.91077964]]
Learner ml_g1 RMSE: [[1.9843391  1.95886712 1.98095976 3.00575479 4.00387225 1.86485892
  1.93099284 1.94539411 1.91282911 2.89639109 1.96426864 2.00205786
  1.99337148 1.94762897 1.92331881]]
Classification:
Learner ml_m Log Loss: [[0.65940159 0.66526036 0.65948207 0.65687858 0.6624634  0.69851884
  0.69572803 0.69719704 0.69825358 0.70136591 0.72864887 0.73278871
  0.72520768 0.73351584 0.72099328]]

------------------ 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.009590  0.149569 -0.064118  9.488762e-01
ATT(2025-04,2025-02,2025-03)  0.163969  0.158136  1.036891  2.997866e-01
ATT(2025-04,2025-03,2025-04)  0.957512  0.138976  6.889770  5.588197e-12
ATT(2025-04,2025-03,2025-05)  2.342959  0.371372  6.308924  2.809830e-10
ATT(2025-04,2025-03,2025-06)  3.084149  0.436515  7.065385  1.601608e-12
ATT(2025-05,2025-01,2025-02) -0.046251  0.136212 -0.339550  7.341955e-01
ATT(2025-05,2025-02,2025-03)  0.035669  0.120403  0.296248  7.670410e-01
ATT(2025-05,2025-03,2025-04) -0.091039  0.102939 -0.884392  3.764845e-01
ATT(2025-05,2025-04,2025-05)  0.934686  0.109817  8.511318  0.000000e+00
ATT(2025-05,2025-04,2025-06)  2.047175  0.218957  9.349686  0.000000e+00
ATT(2025-06,2025-01,2025-02) -0.061289  0.096930 -0.632309  5.271849e-01
ATT(2025-06,2025-02,2025-03)  0.122011  0.096841  1.259914  2.077002e-01
ATT(2025-06,2025-03,2025-04) -0.055071  0.097479 -0.564954  5.721049e-01
ATT(2025-06,2025-04,2025-05) -0.006950  0.095776 -0.072569  9.421492e-01
ATT(2025-06,2025-05,2025-06)  1.047049  0.107962  9.698292  0.000000e+00

                                 2.5 %    97.5 %
ATT(2025-04,2025-01,2025-02) -0.302740  0.283560
ATT(2025-04,2025-02,2025-03) -0.145971  0.473910
ATT(2025-04,2025-03,2025-04)  0.685124  1.229900
ATT(2025-04,2025-03,2025-05)  1.615083  3.070835
ATT(2025-04,2025-03,2025-06)  2.228595  3.939704
ATT(2025-05,2025-01,2025-02) -0.313222  0.220720
ATT(2025-05,2025-02,2025-03) -0.200316  0.271654
ATT(2025-05,2025-03,2025-04) -0.292795  0.110718
ATT(2025-05,2025-04,2025-05)  0.719449  1.149923
ATT(2025-05,2025-04,2025-06)  1.618028  2.476321
ATT(2025-06,2025-01,2025-02) -0.251268  0.128689
ATT(2025-06,2025-02,2025-03) -0.067793  0.311815
ATT(2025-06,2025-03,2025-04) -0.246128  0.135985
ATT(2025-06,2025-04,2025-05) -0.194668  0.180767
ATT(2025-06,2025-05,2025-06)  0.835447  1.258651

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.432485 0.413305
ATT(2025-04,2025-02,2025-03) -0.283148 0.611086
ATT(2025-04,2025-03,2025-04) 0.564568 1.350457
ATT(2025-04,2025-03,2025-05) 1.292931 3.392987
ATT(2025-04,2025-03,2025-06) 1.849934 4.318365
ATT(2025-05,2025-01,2025-02) -0.431380 0.338879
ATT(2025-05,2025-02,2025-03) -0.304761 0.376099
ATT(2025-05,2025-03,2025-04) -0.382091 0.200014
ATT(2025-05,2025-04,2025-05) 0.624187 1.245185
ATT(2025-05,2025-04,2025-06) 1.428091 2.666258
ATT(2025-06,2025-01,2025-02) -0.335351 0.212772
ATT(2025-06,2025-02,2025-03) -0.151799 0.395820
ATT(2025-06,2025-03,2025-04) -0.330687 0.220544
ATT(2025-06,2025-04,2025-05) -0.277750 0.263849
ATT(2025-06,2025-05,2025-06) 0.741794 1.352305

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: 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.377991    -0.136637 -0.009590     0.117457
ATT(2025-04,2025-02,2025-03) -0.194964     0.051884  0.163969     0.276055
ATT(2025-04,2025-03,2025-04)  0.607336     0.831075  0.957512     1.083950
ATT(2025-04,2025-03,2025-05)  1.641464     2.203080  2.342959     2.482838
ATT(2025-04,2025-03,2025-06)  2.200675     2.871987  3.084149     3.296312
ATT(2025-05,2025-01,2025-02) -0.368484    -0.134586 -0.046251     0.042085
ATT(2025-05,2025-02,2025-03) -0.271860    -0.076048  0.035669     0.147386
ATT(2025-05,2025-03,2025-04) -0.375097    -0.205929 -0.091039     0.023852
ATT(2025-05,2025-04,2025-05)  0.643027     0.832289  0.934686     1.037082
ATT(2025-05,2025-04,2025-06)  1.539456     1.896194  2.047175     2.198155
ATT(2025-06,2025-01,2025-02) -0.325341    -0.166296 -0.061289     0.043717
ATT(2025-06,2025-02,2025-03) -0.138259     0.019808  0.122011     0.224214
ATT(2025-06,2025-03,2025-04) -0.321187    -0.161333 -0.055071     0.051190
ATT(2025-06,2025-04,2025-05) -0.266499    -0.109606 -0.006950     0.095706
ATT(2025-06,2025-05,2025-06)  0.769916     0.944282  1.047049     1.149817

                              CI upper
ATT(2025-04,2025-01,2025-02)  0.369391
ATT(2025-04,2025-02,2025-03)  0.552594
ATT(2025-04,2025-03,2025-04)  1.318735
ATT(2025-04,2025-03,2025-05)  3.147328
ATT(2025-04,2025-03,2025-06)  4.064307
ATT(2025-05,2025-01,2025-02)  0.260399
ATT(2025-05,2025-02,2025-03)  0.348656
ATT(2025-05,2025-03,2025-04)  0.194287
ATT(2025-05,2025-04,2025-05)  1.212484
ATT(2025-05,2025-04,2025-06)  2.563890
ATT(2025-06,2025-01,2025-02)  0.203899
ATT(2025-06,2025-02,2025-03)  0.385399
ATT(2025-06,2025-03,2025-04)  0.212493
ATT(2025-06,2025-04,2025-05)  0.254378
ATT(2025-06,2025-05,2025-06)  1.331016

------------------ Robustness Values ------------------
                              H_0     RV (%)    RVa (%)
ATT(2025-04,2025-01,2025-02)  0.0   0.229512   0.000469
ATT(2025-04,2025-02,2025-03)  0.0   4.357892   0.000610
ATT(2025-04,2025-03,2025-04)  0.0  20.560005  16.236359
ATT(2025-04,2025-03,2025-05)  0.0  39.639263  30.949115
ATT(2025-04,2025-03,2025-06)  0.0  35.548378  29.965817
ATT(2025-05,2025-01,2025-02)  0.0   1.582292   0.000364
ATT(2025-05,2025-02,2025-03)  0.0   0.967960   0.000341
ATT(2025-05,2025-03,2025-04)  0.0   2.384803   0.000554
ATT(2025-05,2025-04,2025-05)  0.0  24.206497  17.760031
ATT(2025-05,2025-04,2025-06)  0.0  33.644202  27.704332
ATT(2025-06,2025-01,2025-02)  0.0   1.762264   0.000562
ATT(2025-06,2025-02,2025-03)  0.0   3.570934   0.000543
ATT(2025-06,2025-03,2025-04)  0.0   1.566352   0.000475
ATT(2025-06,2025-04,2025-05)  0.0   0.205869   0.000542
ATT(2025-06,2025-05,2025-06)  0.0  26.590299  22.949681

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: 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.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: 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.974812
2025-05-01    1.517005
2025-06-01    0.950884
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.564061 0.160306 9.756697    0.0 1.249866 1.878256
------------------ Aggregated Effects         ------------------
             coef   std err         t         P>|t|     2.5 %    97.5 %
2025-04  2.128207  0.290073  7.336793  2.187139e-13  1.559674  2.696740
2025-05  1.490930  0.150368  9.915197  0.000000e+00  1.196214  1.785646
2025-06  1.047049  0.107962  9.698292  0.000000e+00  0.835447  1.258651
------------------ 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_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    0.978669
2025-05-01    1.526374
2025-06-01    1.985369
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.566274 0.175913 8.903709    0.0 1.221492 1.911056
------------------ Aggregated Effects         ------------------
             coef   std err         t         P>|t|     2.5 %    97.5 %
2025-04  0.957512  0.138976  6.889770  5.588197e-12  0.685124  1.229900
2025-05  1.667775  0.220885  7.550421  4.329870e-14  1.234848  2.100702
2025-06  2.073534  0.227744  9.104653  0.000000e+00  1.627163  2.519905
------------------ 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_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.008097
-92 days     0.003965
-61 days     0.004698
-31 days    -0.028837
0 days       0.980328
31 days      2.009801
59 days      2.946429
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.088456 0.250586 8.334302    0.0 1.597317 2.579595
------------------ Aggregated Effects         ------------------
               coef   std err          t         P>|t|     2.5 %    97.5 %
-4 months -0.061289  0.096930  -0.632309  5.271849e-01 -0.251268  0.128689
-3 months  0.039663  0.091374   0.434072  6.642360e-01 -0.139426  0.218752
-2 months -0.010290  0.089840  -0.114542  9.088080e-01 -0.186373  0.165792
-1 months  0.025484  0.085530   0.297959  7.657347e-01 -0.142151  0.193120
0 months   0.980071  0.084212  11.638097  0.000000e+00  0.815018  1.145124
1 months   2.201148  0.275855   7.979358  1.554312e-15  1.660481  2.741814
2 months   3.084149  0.436515   7.065385  1.601608e-12  2.228595  3.939704
------------------ 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_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 %
2.088456 0.250586 8.334302    0.0 1.597317 2.579595
------------------ Aggregated Effects         ------------------
               coef   std err          t         P>|t|     2.5 %    97.5 %
-4 months -0.061289  0.096930  -0.632309  5.271849e-01 -0.251268  0.128689
-3 months  0.039663  0.091374   0.434072  6.642360e-01 -0.139426  0.218752
-2 months -0.010290  0.089840  -0.114542  9.088080e-01 -0.186373  0.165792
-1 months  0.025484  0.085530   0.297959  7.657347e-01 -0.142151  0.193120
0 months   0.980071  0.084212  11.638097  0.000000e+00  0.815018  1.145124
1 months   2.201148  0.275855   7.979358  1.554312e-15  1.660481  2.741814
2 months   3.084149  0.436515   7.065385  1.601608e-12  2.228595  3.939704
------------------ 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.34699308, 0.        , 0.        ,
       0.        , 0.        , 0.        , 0.31958489, 0.        ,
       0.        , 0.        , 0.        , 0.        , 0.33342203])

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.009590
ATT(2025-04,2025-02,2025-03)    0.163969
ATT(2025-04,2025-03,2025-04)    0.957512
ATT(2025-04,2025-03,2025-05)    2.342959
ATT(2025-04,2025-03,2025-06)    3.084149
ATT(2025-05,2025-01,2025-02)   -0.046251
ATT(2025-05,2025-02,2025-03)    0.035669
ATT(2025-05,2025-03,2025-04)   -0.091039
ATT(2025-05,2025-04,2025-05)    0.934686
ATT(2025-05,2025-04,2025-06)    2.047175
ATT(2025-06,2025-01,2025-02)   -0.061289
ATT(2025-06,2025-02,2025-03)    0.122011
ATT(2025-06,2025-03,2025-04)   -0.055071
ATT(2025-06,2025-04,2025-05)   -0.006950
ATT(2025-06,2025-05,2025-06)    1.047049
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()

(19044, 10)
[28]:
id y y0 y1 d t Z1 Z2 Z3 Z4
1 0 209.033269 209.033269 208.644110 2025-05-01 2025-01-01 -0.473131 -0.444505 -0.019488 0.438496
2 0 208.896229 208.896229 209.495441 2025-05-01 2025-02-01 -0.473131 -0.444505 -0.019488 0.438496
3 0 208.273269 208.273269 209.165798 2025-05-01 2025-03-01 -0.473131 -0.444505 -0.019488 0.438496
4 0 211.875838 210.965620 211.875838 2025-05-01 2025-04-01 -0.473131 -0.444505 -0.019488 0.438496
5 0 215.075230 210.505041 215.075230 2025-05-01 2025-05-01 -0.473131 -0.444505 -0.019488 0.438496

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.913396 191.063362 225.692226 -0.016196 -2.321846 2.223053
1 2025-01-01 2025-05 209.617390 193.372706 225.124363 -0.021744 -2.530148 2.174271
2 2025-01-01 2025-06 212.952755 196.091000 229.497035 -0.006507 -2.295000 2.383822
3 2025-01-01 Never Treated 217.359244 199.942959 233.655557 -0.079229 -2.346367 2.236624
4 2025-02-01 2025-04 208.834383 182.015908 234.261647 -0.050220 -2.312384 2.268610

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.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_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()
/home/runner/work/doubleml-docs/doubleml-docs/doubleml-for-py/doubleml/double_ml.py:1479: 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.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_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

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: 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_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": [
        (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()
[36]:
(<Figure size 1200x800 with 2 Axes>,
 [<Axes: title={'center': 'First Treated: 2025-04'}, xlabel='Evaluation Period', ylabel='Effect'>])
../../_images/examples_did_py_panel_79_1.png