API Reference
The top-level diddesign namespace exposes all public functions and classes.
Import directly: from diddesign import did, did_check, DidResult.
Core Estimation
- diddesign.did(data, *, formula=None, outcome=None, treatment=None, time, unit_id=None, post=None, design='did', data_type='panel', covariates=None, lead=0, thres=None, n_boot=30, se_boot=None, level=95, id_cluster=None, random_seed=None, parallel=False, n_cores=None, parallel_backend='thread', worker_timeout=None, progress_callback=None, verbose=1, option=None, is_panel=None, kmax=2, jtest=False)[source]
Estimate DID, Double-DID, K-DID, or staggered-adoption variants.
The Double DID estimator (Egami and Yamauchi, 2023) addresses the question of how to exploit multiple pre-treatment periods in a difference-in- differences design. Standard DID identifies the ATT under the parallel trends assumption (A1); sequential DID identifies it under the weaker parallel trends-in-trends assumption (A2), which permits linear divergence in trends but requires an additional pre-treatment period. These two assumptions are logically independent.
The Double DID formulates a GMM problem: given the 2×1 vector of component estimates (τ̂_DID, τ̂_sDID)’ and its bootstrap covariance Σ̂, the optimal combination weights w = Σ̂⁻¹1 / (1’Σ̂⁻¹1) minimize asymptotic variance. When both A1 and A2 hold, the combined estimate is at least as efficient as either component; when only one holds, the GMM estimator remains consistent under that assumption alone.
With kmax ≥ 3, the K-DID extension adds higher-order transformed-outcome estimators whose identifying assumptions permit polynomial time-varying confounding up to degree (K−1). The J-test (
jtest=True) performs an overidentification check and adaptively discards moment conditions that appear violated, providing robustness against misspecified higher-order assumptions.- Parameters:
data (DataFrame or iterable of mappings) – Panel or repeated cross-section data.
formula (str or DidFormulaSpec, optional) – Formula specification (e.g.
"y ~ treat").outcome (str, optional) – Outcome column name (alternative to formula).
treatment (str, optional) – Treatment column name (alternative to formula).
time (str) – Time column name.
unit_id (str, optional) – Unit identifier column. Required for design=’sa’.
post (str, optional) – Post-treatment indicator column.
design (str, default 'did') – Design type: ‘did’ or ‘sa’ (staggered adoption).
data_type (str, default 'panel') – Data structure: ‘panel’ or ‘rcs’.
covariates (sequence of str, optional) – Covariate column names.
lead (int or sequence of int, default 0) – Post-treatment lead period(s) to estimate.
thres (int, optional) – Minimum observations threshold.
n_boot (int, default 30) – Number of bootstrap replications.
se_boot (bool, optional) – Whether to compute bootstrap standard errors.
level (int, default 95) – Confidence level for intervals.
id_cluster (str, optional) – Cluster variable for bootstrap resampling.
random_seed (int, optional) – Random seed for reproducibility.
parallel (bool, default False) – Whether to run bootstrap in parallel.
n_cores (int, optional) – Number of cores for parallel bootstrap.
option (mapping, optional) – Legacy option mapping for backward compatibility.
is_panel (bool, optional) – Deprecated alias for data_type=’panel’.
verbose (int or bool, default 1) – Output verbosity level. Accepts
True(equivalent to 2) orFalse(equivalent to 0). 0 = suppress all DidWarning messages (quiet mode). 1 = default behavior (warnings emitted normally). 2 = progress display during bootstrap and completion summary.kmax (int, default 2) – Maximum K-DID order. Must satisfy 1 <= kmax <= 8. Values greater than 8 raise ValueError to avoid numerical instability in high-order differencing.
jtest (bool, default False) – Whether to run J-test for overidentification (requires kmax >= 3).
parallel_backend (str)
worker_timeout (float | None)
- Returns:
Immutable result object with estimates, bootstrap draws, and metadata.
- Return type:
- diddesign.did_check(*, diagnostic_rows=None, trends_rows=None, pattern_rows=None, metadata=None, data=None, formula=None, outcome=None, treatment=None, time=None, unit_id=None, post=None, design='did', covariates=None, data_type='panel', id_cluster=None, lag=1, thres=None, n_boot=30, random_seed=None, verbose=1, option=None, is_panel=None)[source]
Assess the plausibility of parallel trends assumptions before estimation.
This function implements the pre-treatment diagnostic procedure described in Egami and Yamauchi (2023, Section 3). The idea is straightforward: if the identifying assumptions hold, then applying DID and sDID to pairs of pre-treatment periods should yield estimates near zero. Substantial deviations constitute evidence against the relevant assumption.
The function computes placebo DID and sDID estimates at each requested lag, reports bootstrap standard errors, and constructs 95% standardized equivalence confidence intervals. The equivalence CI reverses the usual null: its rejection provides positive evidence that pre-treatment trends are substantively close to parallel, rather than merely failing to reject a difference.
For staggered-adoption designs (
design="sa"), diagnostics are computed within each treatment-timing cohort and reported per lag.- Parameters:
data (DataFrame or iterable of mappings) – Panel or repeated cross-section data.
formula (str or DidFormulaSpec, optional) – Formula specification (e.g.
"y ~ treat").outcome (str, optional) – Outcome column name.
treatment (str, optional) – Treatment indicator column.
time (str, optional) – Time period column.
unit_id (str, optional) – Unit identifier column.
post (str, optional) – Post-treatment indicator (for RCS data).
design (str, default 'did') –
'did'for standard design,'sa'for staggered adoption.covariates (sequence of str, optional) – Covariate terms for adjustment.
data_type (str, default 'panel') –
'panel'or'rcs'(repeated cross-section).id_cluster (str, optional) – Cluster variable for the bootstrap.
lag (int or sequence of int, default 1) – Pre-treatment lag(s) at which to compute placebo estimates. Lag k tests the assumption using time periods k+1 steps before treatment.
thres (int, optional) – Minimum observation threshold per cell (required for SA designs).
n_boot (int, default 30) – Number of bootstrap replications for standard error estimation.
random_seed (int, optional) – Seed for reproducibility of bootstrap draws.
verbose (int, default 1) – 0 = suppress warnings, 1 = default, 2 = progress display.
diagnostic_rows (list[DidCheckDiagnosticRow] | tuple[DidCheckDiagnosticRow, ...] | None)
trends_rows (list[DidCheckTrendRow] | tuple[DidCheckTrendRow, ...] | None)
pattern_rows (list[DidCheckPatternRow] | tuple[DidCheckPatternRow, ...] | None)
is_panel (bool | None)
- Returns:
Immutable diagnostic result containing placebo estimates, trend comparison rows, and (for SA designs) pattern rows. Access summaries via
to_summary_frame(),to_placebo_frame(),to_trends_frame(), andnamed_plot_rows().- Return type:
Examples
>>> from diddesign import did_check >>> from diddesign.data import data >>> df = data("malesky2014") >>> check = did_check( ... data=df, outcome="pro4", treatment="treatment", ... time="year", post="post_treat", data_type="rcs", ... id_cluster="id_district", lag=[1], n_boot=50, random_seed=1234, ... ) >>> print(check.to_summary_frame())
Result Objects
- class diddesign.DidResult(estimates, metadata, bootstrap_draws)[source]
Bases:
objectImmutable result of DID, Double-DID, K-DID, or SA estimation.
Returned by
did(), this object stores the full estimation output: point estimates for each component estimator, bootstrap draws used to compute standard errors and GMM weights, and metadata recording the design configuration.The object is frozen at construction time; nested metadata dictionaries are recursively converted to immutable mappings so that downstream code cannot accidentally mutate the estimation record.
Frame accessors provide the primary interface for reporting:
to_estimates_frame()— component and combined estimates as a pandas DataFrame with columns: estimator, lead, estimate, std_error, ci_lo, ci_hi, weight.to_bootstrap_frame()— raw bootstrap draws (iterations × components) for custom inference or diagnostic inspection.to_weights_frame()— per-lead GMM weights showing how the data allocate efficiency across DID and sDID.to_gmm_frame()— full GMM calculation rows including the bootstrap covariance matrix and weight matrix entries.to_k_weights_frame()— K-dimensional weight vectors for K-DID.to_latex()— publication-ready LaTeX table string.
- Parameters:
estimates (tuple[DidEstimateRow, ...])
bootstrap_draws (tuple[DidBootstrapDraw | DidBootstrapDrawK, ...])
- to_serialized_result()[source]
Return detached serialized estimate, draw, weight, GMM, and metadata records.
- to_estimates_frame()[source]
Return detached estimator rows as a stable pandas DataFrame.
- Return type:
- to_bootstrap_frame()[source]
Return detached bootstrap draw rows as a stable pandas DataFrame.
- Return type:
- to_weights_frame()[source]
Return detached per-lead GMM weight rows as a stable pandas DataFrame.
- Return type:
- to_gmm_frame()[source]
Return detached per-lead GMM matrix rows as a stable DataFrame.
- Return type:
- to_dataframe()[source]
Convert estimates to a pandas DataFrame.
Returns a DataFrame with columns: estimator, lead, estimate, std_error, ci_lo, ci_hi, weight.
- Return type:
pd.DataFrame
Examples
>>> result = did(data, ...) >>> df = result.to_dataframe() >>> df[df["estimator"] == "Double-DID"]
- to_latex(*, caption=None, label=None, decimal_places=4, include_ci=True, include_weight=False, stars=True)[source]
Export estimates as a LaTeX table string.
Produces a publication-ready LaTeX tabular environment suitable for direct inclusion in academic papers.
- Parameters:
caption (str, optional) – Table caption. If None, no caption is added.
label (str, optional) – LaTeX label for cross-referencing.
decimal_places (int, optional) – Number of decimal places for numerical values. Default 4.
include_ci (bool, optional) – Whether to include confidence interval columns. Default True.
include_weight (bool, optional) – Whether to include GMM weight column. Default False.
stars (bool, optional) – Whether to add significance stars (* p<0.10, ** p<0.05, *** p<0.01). Uses normal approximation: abs(estimate/se) > z_crit. Default True.
- Returns:
Complete LaTeX table string (with begin{table}…end{table}).
- Return type:
Examples
>>> result = did(data, ...) >>> print(result.to_latex(caption="Double DID Estimates")) >>> # Write to file >>> with open("table1.tex", "w") as f: ... f.write(result.to_latex())
- to_polars()[source]
Convert estimates to a polars DataFrame.
Requires polars to be installed.
- Return type:
polars.DataFrame
- Raises:
ImportError – If polars is not installed.
- to_k_weights_frame()[source]
Return K-dimensional GMM weight rows for K-DID/SA-K-DID results.
For results with kmax > 2, the per-lead weight vector has K components. This method extracts weights from the
k_weights_by_leadmetadata and returns a DataFrame with columns: lead, k, weight, plus J-test info.Returns an empty DataFrame if no K-DID weight metadata is present.
- Return type:
- diddesign.DIDResult
Alias of
diddesign.DidResultretained for backward compatibility.
- class diddesign.DidCheckResult(diagnostic_table, trends_table, metadata, pattern_table=())[source]
Bases:
objectImmutable result of pre-treatment parallel trends diagnostics.
Returned by
did_check(), this object holds placebo DID/sDID estimates, trend comparison rows, and (for staggered-adoption designs) pattern rows. Each table is frozen at construction time.The placebo estimates test whether applying the DID and sDID estimators to pre-treatment period pairs yields values near zero—a necessary condition for the identifying assumptions. The standardized equivalence confidence intervals report pre-trend magnitudes in units of the baseline control-group standard deviation, following Egami and Yamauchi (2023, Section 3).
Frame accessors return detached pandas DataFrames suitable for reporting or further analysis:
to_summary_frame()— placebo estimates with equivalence CIsto_placebo_frame()— standardized placebo rows for plottingto_trends_frame()— group-level outcome means over timeto_pattern_frame()— staggered-adoption cohort pattern rowsnamed_plot_rows()— named record dict for visualization functions
- Parameters:
diagnostic_table (tuple[DidCheckDiagnosticRow, ...])
trends_table (tuple[DidCheckTrendRow, ...])
metadata (MappingProxyType)
pattern_table (tuple[DidCheckPatternRow, ...])
- to_diagnostics_frame()[source]
Return detached diagnostic rows as a stable pandas DataFrame.
- Return type:
- to_summary_frame()[source]
Return detached diagnostic summary rows as a stable pandas DataFrame.
- Return type:
- to_placebo_frame()[source]
Return detached standardized placebo plot rows as a stable DataFrame.
- Return type:
Estimate Row Types
- class diddesign.DidEstimateRow(estimator, lead, estimate, std_error, ci_lo, ci_hi, weight=None)[source]
Bases:
objectStable serialized row for a single estimator/lead estimate.
- class diddesign.DidWeightRow(lead, w_did, w_sdid, double_did_available)[source]
Bases:
objectStable serialized row for per-lead Double-DID weights.
- class diddesign.DidGmmRow(lead, w_did, w_sdid, double_did_available, vcov_did, vcov_sdid, vcov_covariance, W_did, W_sdid, W_covariance, gmm_variance)[source]
Bases:
objectStable per-lead GMM weighting matrix row.
Diagnostic Row Types
- class diddesign.DidCheckDiagnosticRow(lag, estimate_std, std_error_std, estimate_raw, std_error_raw, eqci95_lb_std, eqci95_ub_std)[source]
Bases:
objectTruth-carrying diagnostic row with raw and standardized channels.
Summary and Reporting
- diddesign.summary(result, estimator=None, *, as_frame=False)[source]
Project estimator or diagnostic rows into public summary output.
- diddesign.format_summary(result, estimator=None, *, digits=3)[source]
Render public summary rows as a stable, readable text table.
- class diddesign.DiagnosticsReporter(result, verbose=1)[source]
Bases:
objectGenerate structured diagnostic reports for DidResult objects.
- Parameters:
Examples
>>> result = did(data, ...) >>> reporter = DiagnosticsReporter(result, verbose=2) >>> reporter.print_report()
>>> # Or get as dict for programmatic use >>> info = reporter.to_dict()
Formula Parsing
Plotting Rows
These functions prepare fitted result rows for downstream visualization or export without rendering figures directly.
Visualization
These functions render figures from fitted results. They require the optional
diddesign[plot] dependency (matplotlib).
- diddesign.plot_estimates(result, *, check_fit=None, title=None, xlabel=None, ylabel=None, figsize=(8, 5), style='publication', ci_level=0.9, save=None, dpi=150, ax=None, show=False)[source]
Plot Double-DID and SA-Double-DID effect estimates with confidence intervals.
Higher-order K-DID results remain available through the returned estimate, bootstrap, weight, and GMM frames. This helper renders the Double-DID-style display rows produced by
diddesign.fit().- Parameters:
result (DidResult) – The fitted DID result object.
check_fit (DidCheckResult, optional) – If provided, placebo estimates are overlaid on the negative time axis.
title (str, optional) – Custom figure title.
xlabel (str, optional) – Custom x-axis label.
ylabel (str, optional) – Custom y-axis label.
figsize (tuple) – Figure dimensions in inches.
style (str) –
"publication"for serif/clean style;"default"for matplotlib defaults.ci_level (float) – Confidence level (default 0.90).
save (str, optional) – If provided, save figure to this file path.
dpi (int) – Resolution for saved figure.
ax (matplotlib.axes.Axes, optional) – Pre-existing axes to draw on.
show (bool) – Deprecated. No longer calls
plt.show(). The returned Figure can be displayed by the caller.
- Return type:
matplotlib.figure.Figure
- diddesign.plot_diagnostics(check_result, *, result=None, panels='auto', ci=False, title=None, figsize=None, style='publication', ci_level=0.9, save=None, dpi=150, show=False)[source]
Plot combined diagnostic panel.
By default displays two panels (trends + placebo) or three panels (trends + estimates + placebo) when a fitted result is provided.
- Parameters:
check_result (DidCheckResult) – Diagnostic check result.
result (DidResult, optional) – If provided, an estimates panel is included in the middle.
panels (str) –
Panel layout mode:
"auto": two panels unless result is given, in which case three."trends+placebo": always two panels (trends/pattern + placebo)."trends+estimates+placebo": always three panels (requires result).
ci (bool) – Whether to show confidence bands on the trends subplot.
title (str, optional) – Overall figure title.
figsize (tuple, optional) – Figure dimensions. Defaults to
(12, 5)for two panels or(15, 5)for three panels.style (str) –
"publication"or"default".ci_level (float) – Confidence level.
save (str, optional) – File path to save figure.
dpi (int) – Resolution.
show (bool) – Deprecated. No longer calls
plt.show(). The returned Figure can be displayed by the caller.
- Return type:
matplotlib.figure.Figure
- diddesign.plot_trends(check_result, *, ci=False, title=None, xlabel=None, ylabel=None, figsize=(8, 5), style='publication', ci_level=0.9, save=None, dpi=150, ax=None, show=False)[source]
Plot treated vs. control outcome mean trends.
- Parameters:
check_result (DidCheckResult) – Diagnostic check result containing trend rows.
ci (bool) – Whether to show confidence bands.
title (str, optional) – Custom figure title.
xlabel (str, optional) – Custom axis labels.
ylabel (str, optional) – Custom axis labels.
figsize (tuple) – Figure dimensions.
style (str) –
"publication"or"default".ci_level (float) – Confidence level for bands.
save (str, optional) – File path to save figure.
dpi (int) – Resolution for saved figure.
ax (matplotlib.axes.Axes, optional) – Pre-existing axes.
show (bool) – Deprecated. No longer calls
plt.show(). The returned Figure can be displayed by the caller.
- Return type:
matplotlib.figure.Figure
- diddesign.plot_placebo(check_result, *, title=None, xlabel=None, ylabel=None, figsize=(8, 5), style='publication', ci_level=0.9, save=None, dpi=150, ax=None, show=False)[source]
Plot pre-treatment placebo test results.
- Parameters:
check_result (DidCheckResult) – Diagnostic check result containing placebo rows.
title (str, optional) – Custom figure title.
xlabel (str, optional) – Custom axis labels.
ylabel (str, optional) – Custom axis labels.
figsize (tuple) – Figure dimensions.
style (str) –
"publication"or"default".ci_level (float) – Confidence level for error bars (default 0.90).
save (str, optional) – File path to save figure.
dpi (int) – Resolution for saved figure.
ax (matplotlib.axes.Axes, optional) – Pre-existing axes.
show (bool) – Deprecated. No longer calls
plt.show(). The returned Figure can be displayed by the caller.
- Return type:
matplotlib.figure.Figure
- diddesign.plot_pattern(check_result, *, title=None, xlabel=None, ylabel=None, figsize=(10, 6), style='publication', save=None, dpi=150, ax=None, show=False)[source]
Plot staggered-adoption treatment timing heatmap.
- Parameters:
check_result (DidCheckResult) – Diagnostic check result containing pattern rows (SA design).
title (str, optional) – Custom figure title.
xlabel (str, optional) – Custom axis labels.
ylabel (str, optional) – Custom axis labels.
figsize (tuple) – Figure dimensions.
style (str) –
"publication"or"default".save (str, optional) – File path to save figure.
dpi (int) – Resolution for saved figure.
ax (matplotlib.axes.Axes, optional) – Pre-existing axes.
show (bool) – Deprecated. No longer calls
plt.show(). The returned Figure can be displayed by the caller.
- Return type:
matplotlib.figure.Figure
Data Loading
Built-in example datasets for quick-start workflows and reproducible examples.
Built-in example datasets for diddesign.
- diddesign.data.data(name)[source]
Load a built-in example dataset by name.
- Parameters:
name (str) – Dataset name. Available: “malesky2014”, “paglayan2019”.
- Return type:
pd.DataFrame
- Raises:
ValueError – If name is not a recognized dataset.
Examples
>>> from diddesign.data import data >>> df = data("malesky2014")
- diddesign.data.load_malesky2014()[source]
Load Malesky et al. (2014) Vietnam communes repeated cross-section data.
This dataset contains observations from Vietnamese communes across three time periods (2006, 2008, 2010), used to study the effects of recentralization on public services. Suitable for RCS (repeated cross-section) design.
- Returns:
DataFrame with columns including: id_district, year, treatment, post_treat, pro4, tapwater, agrext, lnarea, lnpopden, city, reg8.
- Return type:
pd.DataFrame
Examples
>>> from diddesign.data import load_malesky2014 >>> data = load_malesky2014() >>> from diddesign import did >>> result = did(data, outcome="pro4", treatment="treatment", ... time="year", post="post_treat", data_type="rcs", ... id_cluster="id_district", n_boot=20)
- diddesign.data.load_paglayan2019()[source]
Load Paglayan (2019) US states teacher collective bargaining panel data.
This dataset contains state-level panel data on teacher salaries and expenditures from 1959-2000, used to study the effects of collective bargaining laws. Suitable for staggered adoption (SA) design.
- Returns:
DataFrame with columns including: state, year, treatment, pupil_expenditure, teacher_salary.
- Return type:
pd.DataFrame
Examples
>>> from diddesign.data import load_paglayan2019 >>> data = load_paglayan2019() >>> from diddesign import did >>> result = did(data, outcome="pupil_expenditure", treatment="treatment", ... time="year", unit_id="state", design="sa", ... thres=1, n_boot=20)
Errors and Validation
- class diddesign.DidDataError[source]
Bases:
ValueErrorRaised when input data cannot satisfy the DID data requirements.
This is the backward-compatible base class.
DataContractErroris an alias for this class.
- class diddesign.DidError(code, message, context=None)[source]
Bases:
ExceptionBase DIDdesign structured error with code and context.
- class diddesign.DidValueError(code, message, context=None)[source]
Bases:
DidError,DidDataErrorStructured DIDdesign error for parameter / data validation failures.
Inherits from both
DidErrorandDidDataErrorso that existingexcept ValueErrorandexcept DataContractErrorhandlers continue to catch these errors.
- class diddesign.DidRuntimeError(code, message, context=None)[source]
Bases:
DidError,RuntimeErrorStructured DIDdesign error for computation failures.
Inherits from both
DidErrorandRuntimeErrorso that existingexcept RuntimeErrorhandlers continue to catch these errors.
- class diddesign.DidWarning(code, message, context=None)[source]
Bases:
UserWarningDIDdesign structured warning with code and context.
- Parameters:
code (WarningCode)
message (str)
context (Optional[Dict[str, Any]])
- diddesign.DataContractError
alias of
DidDataError
- class diddesign.ErrorCode(*values)[source]
Bases:
IntEnumStandard error codes matching Stata’s E001-E018 system.
Package Metadata
- diddesign.__version__
The installed package version string.