双重差分表

用四种方法估计交错采用——双向固定效应、加控制变量、Gardner 两阶段 DiD 和 Wooldridge 扩展 TWFE——并附平行趋势前检验和用于比较的真实效应。

双重差分表

双重差分(DiD)比较采用某项处理的单位与未采用单位的结果变化。当各单位在不同时间采用、且效应随时间增大时,教科书式的双向固定效应(TWFE)回归会有偏:它把已处理的单位当作后采用单位的对照,这些“禁止的比较”会拉低估计值。第 (1) 和 (2) 列是不加和加控制变量的 TWFE。第 (3) 列是 Gardner 两阶段 DiD(did2s),只用未处理观测估计固定效应,再把残差化的结果对处理变量回归;第 (4) 列是 Wooldridge 扩展 TWFE,对每个采用批次 × 季度估计一个效应,并按处理观测加权平均(标准误用 delta 方法)。两者都对效应异质性稳健。

由于数据是模拟的,注释给出了处理组的真实平均效应,从而可以看出 TWFE 列的偏误。表尾报告平行趋势前检验,按 Borusyak、Jaravel 和 Spiess 推荐的方式进行:只用未处理观测,在固定效应模型中加入采用前五个季度的虚拟变量并做联合检验。标准误按市场聚类。

背景是 Marty & Warin (2025) 关于算法合谋与反垄断的研究。数据为说明用的模拟数据,并非论文的数据或结果:150 个地方燃油零售市场、24 个季度,其中 60% 市场的加油站在三批中的某一批采用算法定价软件;结果变量是每升以分计的零售毛利。四个模型都来自 pyfixest(feols()、did2s()、wald_test()),即 R 的 fixest 的 Python 版本;表格用 Great Tables 按本类别的期刊版式构建。

代码及图中文字均为英文。

difference-in-differences.py · 122 行
下载 GitHub
import numpy as np
import pandas as pd
import pyfixest as pf
from great_tables import GT, html, loc, style
# Simulated data, set in the context of Marty & Warin (2025) [marty2025collusion]

# Data: 150 fuel markets × 24 quarters; three adoption waves (quarters 8, 12, 16) and never-adopters.
# Margins rise after adoption, more so the longer the software runs and for the first wave.
rng = np.random.default_rng(2026)
M, T = 150, 24
wave = rng.choice([8, 12, 16, 0], M, p=[.2, .2, .2, .4])            # 0 = never adopts
df = pd.DataFrame({"market": np.repeat(np.arange(M), T), "quarter": np.tile(np.arange(T), M),
                   "wave": np.repeat(wave, T)})
df["treat"] = ((df.wave > 0) & (df.quarter >= df.wave)).astype(int)
since = df.quarter - df.wave                                         # quarters since adoption
effect = np.where(df.treat == 1, (0.6 + 0.12 * since) * np.where(df.wave == 8, 1.5, 1.0), 0.0)
df["cost"] = rng.normal(0, 1, M * T)                                 # wholesale cost shock
df["rivals"] = rng.poisson(4, M * T)                                 # competing stations
df["margin"] = (12 + np.repeat(rng.normal(0, 2, M), T)                       # market level
                + np.tile(np.linspace(0, 1.5, T) + rng.normal(0, .3, T), M)  # common quarter shocks
                + 0.8 * df.cost - 0.3 * df.rivals + effect + rng.normal(0, 1, M * T))
true_att = effect[df.treat == 1].mean()
cluster = {"CRV1": "market"}

# (1)–(2) Two-way fixed effects
twfe = pf.feols("margin ~ treat | market + quarter", df, vcov=cluster)
twfe_x = pf.feols("margin ~ treat + cost + rivals | market + quarter", df, vcov=cluster)

# (3) Gardner's two-stage DiD: fixed effects and controls fitted on untreated observations only
gardner = pf.did2s(df, yname="margin", first_stage="~ cost + rivals | market + quarter",
                   second_stage="~ treat", treatment="treat", cluster="market")

# (4) Wooldridge's extended TWFE: one effect per wave × quarter cell, then the treated-weighted mean
df["cell"] = np.where(df.treat == 1, df.wave.astype(str) + "_" + df.quarter.astype(str), "untreated")
etwfe = pf.feols("margin ~ i(cell, ref='untreated') + cost + rivals | market + quarter", df, vcov=cluster)
share = df[df.treat == 1].cell.value_counts(normalize=True)           # treated-observation weights
w = np.array([share.get(c.removeprefix("cell::"), 0.0) for c in etwfe.coef().index])
etwfe_att = float(w @ etwfe.coef())
att_test = etwfe.wald_test(R=w[None, :], distribution="chi2")         # H0: w'b = 0
etwfe_se, etwfe_p = abs(etwfe_att) / np.sqrt(att_test.stat), att_test.pvalue   # delta-method SE

# Pre-trend test (Borusyak, Jaravel & Spiess): on untreated observations only, add dummies for
# the 5 quarters before adoption to the fixed-effects model and test them jointly
untreated = df[df.treat == 0].copy()
untreated["lead"] = np.where((untreated.wave > 0) & (untreated.quarter - untreated.wave >= -5),
                             untreated.quarter - untreated.wave, 0)
pre = pf.feols("margin ~ i(lead, ref=0) + cost + rivals | market + quarter", untreated, vcov=cluster)
leads = [i for i, c in enumerate(pre.coef().index) if c.startswith("lead::")]
pretrend = pre.wald_test(R=np.eye(len(pre.coef()))[leads], distribution="chi2")

# Assemble the table: estimate over (SE), as in stargazer
results = [(twfe.coef()["treat"], twfe.se()["treat"], twfe.pvalue()["treat"]),
           (twfe_x.coef()["treat"], twfe_x.se()["treat"], twfe_x.pvalue()["treat"]),
           (gardner.coef()["treat"], gardner.se()["treat"], gardner.pvalue()["treat"]),
           (etwfe_att, etwfe_se, etwfe_p)]
cols = ["(1)", "(2)", "(3)", "(4)"]
names = ["TWFE", "TWFE", "Two-stage DiD", "Extended TWFE"]


def stars(p):
    return "***" if p < .01 else "**" if p < .05 else "*" if p < .1 else ""


def num(x, d=3):                      # typographic minus sign, as in print
    return f"{x:.{d}f}".replace("-", "−")


pre_mean = df.loc[(df.wave > 0) & (df.treat == 0), "margin"].mean()
row = lambda term, values: {"term": term, **dict(zip(cols, values))}
rows = [
    row("Algorithmic pricing (ATT)", [num(e) + stars(p) for e, _, p in results]),
    row("", [f"({num(s)})" for _, s, _ in results]),
    row("Controls (cost, rival stations)", ["No", "Yes", "Yes", "Yes"]),
    row("Market fixed effects", ["Yes"] * 4),
    row("Quarter fixed effects", ["Yes"] * 4),
    row("Robust to heterogeneous effects", ["No", "No", "Yes", "Yes"]),
    row("Observations", [f"{len(df):,}"] * 4),
    row("Markets (adopting)", [f"{M} ({(wave > 0).sum()})"] * 4),
    row("Pre-adoption mean of margin", [num(pre_mean, 2)] * 4),
    row("Pre-trend test, leads = 0",
        ["", "", f"χ²({pretrend.df1}) = {pretrend.stat:.1f} (p = {pretrend.pvalue:.2f})", ""]),
]
tab = pd.DataFrame(rows)

table = (
    GT(tab, rowname_col="term")
    .tab_header(title="TABLE V", subtitle="Algorithmic pricing and retail margins: difference-in-differences")
    .tab_spanner(label="Dependent variable: retail margin (cents per litre)", columns=cols, id="dep")
    .cols_label(**{c: html(f"{c}<br>{n}") for c, n in zip(cols, names)})
    .cols_align("center", columns=cols)
    .cols_width({"term": "260px", **{c: "170px" for c in cols}})
    .tab_source_note(f"Notes: {M} markets × {T} quarters (simulated); adoption in three waves. Standard errors "
                     "clustered by market in parentheses. *p < 0.1; **p < 0.05; ***p < 0.01.")
    .tab_source_note(f"True average effect on the treated in the simulation: {true_att:.3f}. "
                     "Pre-trend test: Wald test of 5 pre-adoption leads, untreated observations only.")
    # Same journal look as the other tables: serif type, small-caps title, horizontal rules only
    .opt_table_font(font=["Latin Modern Roman", "Times New Roman", "Georgia", "serif"])
    .tab_options(
        table_width="960px", table_font_size="15px", table_font_color="#000",
        heading_title_font_size="15px", heading_subtitle_font_size="15px", heading_padding="1px",
        table_border_top_style="hidden", table_border_bottom_style="hidden",
        heading_border_bottom_style="none",
        column_labels_border_top_style="solid", column_labels_border_top_width="1.5px",   # top rule
        column_labels_border_top_color="#000",
        column_labels_border_bottom_style="solid", column_labels_border_bottom_width="1px",
        column_labels_border_bottom_color="#000",
        table_body_border_top_style="solid", table_body_border_top_width="1px",
        table_body_border_top_color="#000",
        table_body_hlines_style="none", stub_border_style="none",
        table_body_border_bottom_style="solid", table_body_border_bottom_width="1.5px",
        table_body_border_bottom_color="#000",
        data_row_padding="4px", source_notes_font_size="13px", source_notes_padding="1px",
    )
    .tab_style(style.css("font-variant: small-caps; padding-bottom: 8px;"), loc.subtitle())
    .tab_style(style.text(style="italic"), loc.spanner_labels(ids=["dep"]))
    .tab_style(style.css("padding-bottom: 0;"), [loc.body(rows=[0]), loc.stub(rows=[0])])
    .tab_style(style.css("padding-top: 0;"), [loc.body(rows=[1]), loc.stub(rows=[1])])
    # thin rules above the specification rows and above the sample statistics
    .tab_style(style.borders(sides="top", style="solid", weight="1px", color="#000"),
               [loc.body(rows=[2, 6]), loc.stub(rows=[2, 6])])
)
table.show()

图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。

数据来源

  • Simulated data. Simulated data with a fixed random seed, created for this example.
    No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work.
  • Marty & Warin (2025), algorithmic collusion and antitrust. Marty, F., & Warin, T. (2025). Deciphering algorithmic collusion: Insights from bandit algorithms and implications for antitrust enforcement. Journal of Economy and Technology, 3, 34–43. https://doi.org/10.1016/j.ject.2024.10.001
    The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.

这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。

如何引用

PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。

Warin, T. (2026). Difference-in-differences table. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/academic-tables/difference-in-differences/

@misc{warin2026statlas,
  author       = {Warin, Thierry},
  title        = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
  year         = {2026},
  version      = {1.1.0},
  howpublished = {\url{https://warin.ca/pystatlas/}},
  note         = {Source code: https://github.com/warint/pystatlas}
}

更多学术表格图表