Estimators¶
Eight functions, one per estimator. They share the data arguments, the standard-error options, and the memory, thread and profiling options.
- diff_stream.did_callaway_santanna(fml, data, *, panel=None, time=None, cohort=None, treatment=None, control_group='never_treated', base_period='varying', adjustment='doubly_robust', propensity_trim=0.995, anticipation=0, weights=None, allow_time_varying_weights=False, incomplete_units='error', last_treated_controls='if_needed', vcov='CRV0', multiplier_bootstrap_reps=0, multiplier_bootstrap_seed=None, multiplier_bootstrap_weights='rademacher', effective_sample_warning=30, min_effective_sample=None, covariate_balance=False, balance_distributions=False, n_threads=None, max_memory_gb=None, memory_reserve=None, workdir=None, profile=False, batch_units=None, preprocess_mb=None)[source]¶
Callaway and Sant’Anna’s group-time average treatment effects.
Estimates the average effect for each cohort (units first treated in the same period) in each period, by comparing its outcome changes with those of a control group, then aggregates them with
aggregate(). Covariates enter by outcome regression, inverse probability weighting or the doubly robust combination of Sant’Anna and Zhao (2020), as in R’s did.Callaway, B. and Sant’Anna, P. H. C. (2021). Difference-in-differences with multiple time periods. Journal of Econometrics 225(2), 200-230.
Sant’Anna, P. H. C. and Zhao, J. (2020). Doubly robust difference-in-differences estimators. Journal of Econometrics 219(1), 101-122.
- Parameters:
fml (str) –
"y ~ 1", or"y ~ x + C(region)"with covariates (up to 256 design columns), measured in the comparison’s base period.{DATA}
control_group ({"never_treated", "not_yet_treated"}, default "never_treated") – The comparison units: never-treated units only, or also units not yet treated by the period compared.
base_period ({"varying", "universal"}, default "varying") – The pre-treatment comparison period: the period just before each pre-treatment cell (“varying”), or the last clean period before treatment for every cell (“universal”). Post-treatment cells use the latter either way.
adjustment ({"doubly_robust", "regression", "ipw"}, default "doubly_robust") – How covariates enter: outcome regression on the controls, inverse probability weighting with a logit propensity score, or both.
propensity_trim (float, default 0.995) – Controls with a propensity score above this are dropped from IPW and doubly robust comparisons (treated units are kept). 1 disables it.
{ANTICIPATION}
{WEIGHTS}
{INCOMPLETE_UNITS} – With “keep”, comparisons use each period’s observed rows, as R’s did does for unbalanced panels.
{LAST_TREATED}
{VCOV}
multiplier_bootstrap_reps (int, default 0) – Draws of the multiplier bootstrap, which perturbs each unit’s influence function instead of refitting (R did’s default inference). It gives simultaneous confidence bands through
multiplier_confint(); the analytic standard errors are unchanged. 0 skips it. For a bootstrap that refits the model, seerefit_bootstrap.multiplier_bootstrap_seed (int, optional) – Seed for the multiplier draws.
multiplier_bootstrap_weights ({"rademacher", "mammen", "webb", "norm"}, default "rademacher") – The distribution of the multiplier draws.
effective_sample_warning (float or None, default 30) – Warn (
LowEffectiveSampleWarning) when a comparison’s treated or control group has an effective sample size (Kish) below this. None turns the warning off.min_effective_sample (float, optional) – Report coefficients whose effective sample is below this as NaN.
suppress()does the same after fitting.covariate_balance (bool, default False) – Save covariate balance tables for each comparison, before and after propensity weighting, for
covariate_balance().balance_distributions (bool, default False) – With
covariate_balance, also compare the covariates’ empirical distributions.{RESOURCES}
- Returns:
DIDResult or Profile –
cohort_time()lists the group-time effects;aggregate()gives an event study,aggregate("overall")the overall ATT.
- diff_stream.did_sun_abraham(fml, data, *, panel, cohort=None, treatment=None, anticipation=0, weights=None, allow_time_varying_weights=False, incomplete_units='error', last_treated_controls='if_needed', fixed_effect_solver='auto', vcov='CRV0', n_threads=None, max_memory_gb=None, memory_reserve=None, workdir=None, profile=False, batch_units=None, preprocess_mb=None)[source]¶
Sun and Abraham’s interaction-weighted event study.
Regresses the outcome on a full set of cohort-by-period treatment indicators, with unit and time fixed effects, so that each cohort’s effects are estimated separately;
aggregate()then averages them by event time with cohort-share weights. The period before treatment (beforecohort - anticipation) is the omitted reference.Sun, L. and Abraham, S. (2021). Estimating dynamic treatment effects in event studies with heterogeneous treatment effects. Journal of Econometrics 225(2), 175-199.
- Parameters:
fml (str) –
"y ~ 1"; covariates"y ~ x"; additional fixed effects after a bar,"y ~ x | region^time". Unit and time fixed effects are always included.{DATA}
{ANTICIPATION}
{WEIGHTS}
{INCOMPLETE_UNITS}
{LAST_TREATED}
{FIXED_EFFECT_SOLVER}
{VCOV}
{RESOURCES}
- Returns:
DIDResult or Profile –
cohort_time()lists the cohort-period coefficients;aggregate()gives the event study.
- diff_stream.did_bjs(fml, data, *, panel, cohort=None, treatment=None, residual_averaging='cohort_time', leave_out=False, pretrend_leads=0, anticipation=0, weights=None, allow_time_varying_weights=False, incomplete_units='error', last_treated_controls='if_needed', fixed_effect_solver='auto', vcov='CRV0', n_threads=None, max_memory_gb=None, memory_reserve=None, workdir=None, profile=False, batch_units=None, preprocess_mb=None)[source]¶
Borusyak, Jaravel and Spiess’s imputation estimator.
Fits unit and time fixed effects (and any covariates) on the untreated observations only, imputes each treated observation’s untreated outcome, and averages the differences. The standard errors are the authors’ conservative ones, as in their Stata command
did_imputation.Borusyak, K., Jaravel, X. and Spiess, J. (2024). Revisiting event-study designs: robust and efficient estimation. Review of Economic Studies 91(6), 3253-3285.
- Parameters:
fml (str) –
"y ~ 1"; covariates"y ~ x"; additional fixed effects after a bar,"y ~ x | region^time". Unit and time fixed effects are always included. Treated observations whose fixed-effect level has no untreated observations cannot be imputed: they are dropped, with anUnimputedObservationsWarning, andfit.diagnosticsreports them (unimputed_observations,unimputed_cells).{DATA}
residual_averaging ({"cohort_time", "event_time", "cohort", "all"}, default "cohort_time") – The groups within which the standard errors average treated residuals (the authors’
avgeffectsby). Coarser groups give more conservative standard errors and need fewer observations per group.leave_out (bool, default False) – Leave each unit out of its own group’s average residual (the authors’
leaveout), which reduces the downward bias in small groups.pretrend_leads (int, default 0) – For a pre-trend test: fit a separate regression on the untreated observations with indicators for the last
pretrend_leadsperiods before treatment.placebos()returns those coefficients andpretrend_test()tests that they are jointly zero. The treatment effects are unchanged. 0 skips it.{ANTICIPATION}
{WEIGHTS}
{INCOMPLETE_UNITS}
{LAST_TREATED}
{FIXED_EFFECT_SOLVER}
{VCOV}
{RESOURCES}
- Returns:
DIDResult or Profile –
cohort_time()lists the imputed effects by cohort and period;aggregate()gives the event study,aggregate("overall")the overall ATT. Weighted, unbalanced or covariate fits, and fits with additional fixed effects, keep temporary files for aggregation untilcleanup().
- diff_stream.did_two_stage(fml, data, *, panel, cohort=None, treatment=None, event_study=True, reference_period=None, anticipation=0, weights=None, allow_time_varying_weights=False, incomplete_units='error', last_treated_controls='if_needed', vcov='CRV0', fixed_effect_solver='auto', n_threads=None, max_memory_gb=None, memory_reserve=None, workdir=None, profile=False, batch_units=4096, preprocess_mb=None)[source]¶
Gardner’s two-stage difference-in-differences.
The first stage fits unit and time fixed effects (and any covariates) on the untreated observations only; the second stage regresses the first-stage residuals of all observations on treatment indicators. The standard errors account for the estimated first stage. The point estimates match BJS imputation in many designs; the inference differs.
Gardner, J. (2022). Two-stage differences in differences. arXiv:2207.05943.
Butts, K. and Gardner, J. (2022). did2s: two-stage difference-in-differences. The R Journal 14(3), 162-173.
- Parameters:
fml (str) –
"y ~ 1"; first-stage covariates"y ~ x"; additional fixed effects after a bar,"y ~ x | region^time". Unit and time fixed effects are always included. Fixed effects with many levels (county-by-year) are absorbed iteratively; seefixed_effect_solver.{DATA}
event_study (bool, default True) – Estimate one coefficient per event time (an event study). False estimates a single overall effect of treatment.
reference_period (int, optional) – With
event_study, the omitted pre-treatment event time. Default: the last clean period,-anticipation - 1.{ANTICIPATION}
{WEIGHTS}
{INCOMPLETE_UNITS}
{LAST_TREATED}
{VCOV}
{FIXED_EFFECT_SOLVER}
{RESOURCES}
- Returns:
TwoStageResult or Profile – The second-stage coefficients (
event::horATT) and their joint covariance.select(horizons)reports a subset of event times without refitting.
- diff_stream.did_extended_twfe(fml, data, *, panel, cohort=None, treatment=None, control_group='never_treated', fixed_effects='cohort', treat_sample_as_fixed=False, anticipation=0, weights=None, allow_time_varying_weights=False, incomplete_units='error', last_treated_controls='if_needed', vcov='CRV0', max_design_columns=2048, n_threads=None, max_memory_gb=None, memory_reserve=None, workdir=None, profile=False, batch_units=None, preprocess_mb=None)[source]¶
Wooldridge’s extended two-way fixed effects (linear).
A single regression with a separate treatment effect for every cohort and period, and covariates interacted with cohort, time and treatment, so that the effects can differ with the covariates. The cohort-time effects are averaged over the sample’s covariates and aggregated with
aggregate(), as in R’s etwfe and emfx. Only the linear model is implemented; for logit or Poisson ETWFE use R’s etwfe or Stata’s jwdid.Wooldridge, J. M. (2021). Two-way fixed effects, the two-way Mundlak regression, and difference-in-differences estimators. Working paper, SSRN 3906345.
- Parameters:
fml (str) –
"y ~ 1"or"y ~ x + z". Additional fixed effects are not supported.{DATA}
control_group ({"never_treated", "not_yet_treated"}, default "never_treated") – The comparison units. With never-treated controls, pre-treatment effects are estimated too (for a pre-trend test). R’s etwfe defaults to not-yet-treated.
fixed_effects ({"cohort", "unit"}, default "cohort") – Cohort intercepts (R etwfe’s default) or unit fixed effects.
treat_sample_as_fixed (bool, default False) – Standard errors for the effect in these units, holding the observed covariates and cohort shares fixed (smaller), instead of in the population they were drawn from (R emfx’s conditional option).
{ANTICIPATION}
{WEIGHTS}
{INCOMPLETE_UNITS}
{LAST_TREATED}
{VCOV}
max_design_columns (int, default 2048) – The limit on the expanded design, after interacting the covariates.
{RESOURCES}
- Returns:
DIDResult or Profile –
cohort_time()lists the cohort-time effects;aggregate()gives an event study,aggregate("overall")the overall ATT.
- diff_stream.did_stacked(fml, data, *, panel, event_window, cohort=None, treatment=None, anticipation=0, weights=None, allow_time_varying_weights=False, incomplete_units='error', vcov='CRV0', n_threads=None, max_memory_gb=None, memory_reserve=None, workdir=None, profile=False, batch_units=4096, preprocess_mb=None)[source]¶
Stacked difference-in-differences with corrective weights.
One sub-experiment per adoption cohort: the cohort’s units and the units not yet treated by the end of its event window (never-treated units and later cohorts), over that window. The sub-experiments are stacked and an event study is fitted on the stack, with the corrective weights of Wing, Freedman and Hollingsworth (2024), so that each event-time effect is the average of the sub-experiments’ effects weighted by their treated units (their “trimmed aggregate ATT”). Only cohorts whose whole window lies in the sample are included. The stacked data, which repeat a control unit once for each sub-experiment it enters, are never built.
Cengiz, D., Dube, A., Lindner, A. and Zipperer, B. (2019). The effect of minimum wages on low-wage jobs. Quarterly Journal of Economics 134(3), 1405-1454.
Wing, C., Freedman, S. M. and Hollingsworth, A. (2024). Stacked difference-in-differences. NBER Working Paper 32054.
- Parameters:
fml (str) –
"y ~ 1". Covariates are not supported.{DATA}
event_window (tuple of int) – The first and last event times of each sub-experiment, e.g.
(-4, 4); it must include the reference period (-anticipation - 1) and 0.{ANTICIPATION}
{WEIGHTS}
{INCOMPLETE_UNITS}
{VCOV} – A unit in several sub-experiments is one cluster.
{RESOURCES}
- Returns:
StackedResult or Profile – Event-time coefficients
event::h(all but the reference period), withselect(),overall(),pretrend_test()andsub_experiments().
- diff_stream.did_continuous(fml, data, *, panel, dose, cohort=None, treatment=None, control_group='not_yet_treated', reference_dose=None, base_period='varying', anticipation=0, dose_type='continuous', degree=None, interior_knots=0, dose_grid=None, weights=None, allow_time_varying_weights=False, incomplete_units='error', vcov='CRV0', cluster=None, multiplier_bootstrap_reps=0, multiplier_bootstrap_seed=None, multiplier_bootstrap_weights='rademacher', n_threads=None, max_memory_gb=None, memory_reserve=None, workdir=None, profile=False, batch_units=None, preprocess_mb=None)[source]¶
Callaway, Goodman-Bacon and Sant’Anna’s difference-in-differences with a continuous treatment.
Each treated unit receives a dose, constant over time, when it is first treated; untreated units have no dose. For each cohort and period, the outcome change of the cohort’s units since the base period is regressed on a B-spline in the dose, and the control group’s mean change is subtracted. That gives the average effect of each dose, ATT(d), and its derivative, the average causal response ACRT(d). The coefficients are their overall averages, as R’s contdid reports them.
With
dose_type="discrete"the dose takes a few values, and the spline is replaced by an indicator for each value (the paper’s saturated regression, Eq. 4.1): ATT(d) is the mean outcome change of the units at dose d less the control group’s, and ACRT(d) is the change in ATT from the next lower dose (or from 0), divided by the difference in doses.Callaway, B., Goodman-Bacon, A. and Sant’Anna, P. H. C. (2024). Difference-in-differences with a continuous treatment. NBER Working Paper 32117.
- Parameters:
fml (str) –
"y ~ 1"; experimental: covariates and absorbed fixed effects,"y ~ x + C(occupation) | region"or"y ~ x | region + industry". In each cohort and period, the comparison units’ change is regressed on them (at the base period) and the treated units’ changes less their predictions are fitted on the dose; a fixed effect is region-by-period. One term is absorbed exactly; several are absorbed by hdfe-stream, and assume that their effects on the trend add up. The authors have not developed this, and a fit with covariates issues anExperimentalWarning; see the documentation for the assumptions it needs.{DATA}
dose (str) – Each unit’s dose: positive and constant within a treated unit. The doses of never-treated units are not used.
control_group ({"not_yet_treated", "never_treated", "lowest_dose"}, default "not_yet_treated") – The comparison units: also units not yet treated by the period compared, or never-treated units only.
"lowest_dose"is for samples in which every unit is treated, at one date: the units at the lowest dose are the comparison, and the curves are ATT(d) - ATT(d_L) (the paper’s Remark 3.1, which needs strong parallel trends).reference_dose (float, optional) – With
"lowest_dose"and a continuous dose: the units with a dose up to this one are the comparison, instead of those at the lowest dose. The curves are then ATT(d) less the comparison units’ average ATT, for doses above it.base_period ({"varying", "universal"}, default "varying") – The pre-treatment comparison period, as in
did_callaway_santanna.{ANTICIPATION}
dose_type ({"continuous", "discrete"}, default "continuous") – How the outcome change depends on the dose within each cohort and period: a B-spline (
"continuous") or a separate mean for each dose value ("discrete"). A discrete dose takes at most 1,000 values, and every cohort must have units at each of them.degree (int, optional) – The degree of the dose spline (default 3: cubic). Not used with a discrete dose.
interior_knots (int, default 0) – Interior knots of the spline, at quantiles of the treated doses. With 0 the curve is a polynomial of the given degree. Not used with a discrete dose.
dose_grid (array, optional) – The doses at which
dose_response()evaluates the curves. Default: the 10th to 99th percentiles of the treated doses, in steps of 1, as in contdid; with a discrete dose, its values (and only they can be given).weights (str, optional) – A column of sampling weights: positive, finite, and constant within each unit unless
allow_time_varying_weights=True. They weight the units in every regression and average, and in the cohort shares. Weights that change over time are experimental: each cohort-period then uses the units’ weights in the period compared.allow_time_varying_weights (bool, default False) – Accept weights that change over time within a unit.
incomplete_units ({"error", "drop", "keep"}, default "error") – What to do with units missing some periods: refuse the data, drop those units, or keep them (experimental: each comparison then uses the units observed in both of its periods).
vcov ({"CRV0", "CRV1"}, default "CRV0") – Standard errors clustered by unit, or by
cluster. CRV1 multiplies the variance by G/(G-1), with G the units or clusters.cluster (str, optional) – A column to cluster the standard errors by, above the unit (such as the group that shares the dose, or a region): constant within each unit. Default: the unit.
multiplier_bootstrap_reps (int, default 0) – Draws of the multiplier bootstrap, for simultaneous confidence bands over doses (
dose_response(uniform=True)). 0 skips it.multiplier_bootstrap_seed (int, optional) – Seed for the multiplier draws.
multiplier_bootstrap_weights ({"rademacher", "mammen", "webb", "norm"}, default "rademacher") – The distribution of the multiplier draws.
{RESOURCES}
- Returns:
DoseResponseResult or Profile – The overall ATT and ACRT;
dose_response()the curves,aggregate()event studies of the binarized ATT or of the ACRT.
- diff_stream.did_dcdh(fml, data, *, panel, treatment, effects=1, placebos=0, normalized=False, switchers='both', only_never_switchers=False, trends_by=None, linear_trends=False, weights=None, allow_time_varying_weights=False, incomplete_units='error', cluster=None, continuous_baseline=None, n_threads=None, max_memory_gb=None, memory_reserve=None, workdir=None, profile=False, batch_units=None, preprocess_mb=None)[source]¶
de Chaisemartin and D’Haultfoeuille’s event-study estimator for a treatment that may switch on and off and take several values.
Each group’s baseline is its first-period treatment, and its first switch the first period its treatment differs from that. Effect l compares the outcome change of the groups that first switched l - 1 periods earlier, since the period before their switch, with that of groups with the same baseline that have not switched yet. As the authors’ R and Stata
did_multiplegt_dyn. Weights may vary over time (withallow_time_varying_weights=True): a group enters each comparison with its weight in the period the effect is measured at (for a placebo, that of the matching effect).de Chaisemartin, C. and D’Haultfoeuille, X. (2024). Difference-in-differences estimators of intertemporal treatment effects. NBER Working Paper 29873.
- Parameters:
fml (str) –
"y ~ 1", or"y ~ x + z"with covariates: within each first-period treatment, the outcome’s changes among groups not yet switched are regressed on the covariates’ changes with period effects, and the comparisons use the outcome changes net of the covariates’ fitted part.data (polars.DataFrame, polars.LazyFrame, str or Path) – The panel, or a Parquet path or glob, read in streaming batches.
panel (tuple of str) – The group and time columns,
(group, time); periods are evenly spaced positive integers.treatment (str) – The treatment, numeric: binary or with several values, and free to change in any period. Groups are compared only with groups of the same first-period treatment.
effects (int, default 1) – The number of effects, l = 1, …, effects (fewer if the data support fewer).
placebos (int, default 0) – The number of placebos (at most
effects).normalized (bool, default False) – Divide each effect by the average change in treatment the switchers have received up to it, giving effects per unit of treatment.
switchers ({"both", "in", "out"}, default "both") – Use switchers whose treatment rose (“in”), fell (“out”), or both.
only_never_switchers (bool, default False) – Compare switchers only with groups whose treatment never changes.
trends_by (str or list of str, optional) – Group-level columns (constant within each group) within which trends may differ: switchers are compared only with groups that have the same values of these columns as well as the same first-period treatment.
linear_trends (bool, default False) – Allow each group its own linear trend. The comparisons use the first differences of the outcome (and of the covariates), and effect l is the sum of the first l such effects, for the switchers that have all l; placebo l likewise. Groups that first switch in the second period are not used, and the average total effect is not estimated.
{WEIGHTS}
incomplete_units ({"error", "drop", "keep"}, default "error") – What to do with groups missing some periods: refuse the data, drop those groups, or keep their observed periods. With “keep”, a change is used only where both of its periods are observed, and a group not observed just before its switch is used only as a control until its last observed period before it, as in DIDmultiplegtDYN.
cluster (str, optional) – A column to cluster the standard errors by, above the group (each group in one cluster), as
clusterin DIDmultiplegtDYN: the groups’ terms are summed by cluster, and the authors’ cohort demeaning counts clusters rather than groups. Default: the group.continuous_baseline (int, optional) – For a first-period treatment that is continuous, so that no two groups share one (DIDmultiplegtDYN’s
continuous): the degree of a polynomial in it. All groups are then compared together, with untreated trends that may differ by a polynomial of this degree in the first-period treatment, period by period (entered as covariates), and the switching cohorts of the variance are defined by the direction of the switch. The standard errors are not backed by a proven asymptotic result (see the documentation); fits warn.{RESOURCES}
- Returns:
DCDHResult or Profile –
effect::l,placebo::landaverage_total_effect(not withlinear_trends) with their joint covariance;pretrend_test(),effects_equal_test(),switchers().