差の差分法の表
時期がずれた導入を 4 通りに推定します。二元固定効果、統制変数付き、Gardner の 2 段階 DiD、Wooldridge の拡張 TWFE です。事前トレンド検定と、比較のための真の効果を添えます。

差の差分法(DiD)は、処置を導入した単位での結果の変化を、導入しなかった単位での変化と比べます。単位が異なる時期に導入し、効果が時間とともに大きくなる場合、教科書どおりの二元固定効果(TWFE)回帰は偏ります。すでに処置を受けた単位を後から導入した単位の対照として使い、その「禁じられた比較」が推定値を引き下げるからです。列 (1) と (2) は統制変数なしとありの TWFE です。列 (3) は Gardner の 2 段階 DiD(did2s)で、未処置の観測だけで固定効果を推定し、残差化した結果を処置に回帰します。列 (4) は Wooldridge の拡張 TWFE で、導入の波 × 四半期ごとに 1 つの効果を推定し、処置観測の重みで平均します(標準誤差はデルタ法)。どちらも効果の異質性に頑健です。
データはシミュレーションなので、注記に処置群における真の平均効果を示し、TWFE の列の偏りが見えるようにしています。表の末尾には、平行トレンドの確認である事前トレンド検定を、Borusyak, Jaravel & Spiess の推奨どおりに示します。未処置の観測だけを使い、導入前 5 四半期のダミーを固定効果モデルに加えて同時に検定します。標準誤差は市場でクラスター化しています。
設定は Marty & Warin (2025) によるアルゴリズム的共謀と競争法の研究です。データは説明のためのシミュレーションであり、論文のデータや結果ではありません。24 四半期にわたる 150 の地域燃料小売市場で、60% の市場のスタンドが 3 つの波のいずれかでアルゴリズム価格設定ソフトを導入します。結果変数は 1 リットルあたりのセント建て小売マージンです。4 つのモデルはすべて R の fixest の Python 版である pyfixest(feols()、did2s()、wald_test())によるもので、表はこのファミリーの学術誌の体裁で Great Tables を使って組みます。
コードおよび図中のテキストは英語です。
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}
}学術論文の表のその他のグラフ
stargazer 形式の回帰表
入れ子になった 3 つの OLS モデルを横に並べ、係数の下に標準誤差、末尾に適合度の統計量を置いて、学術誌の表のように組みます。
stargazer::stargazer(type = "html")記述統計の表
実証論文の「表 1」。変数ごとの N、平均、標準偏差、最小値、中央値、最大値をパネルに分けて示し、群ごとの平均とその差の検定を添えます。
modelsummary::datasummary_balance()機械学習モデルの比較表
繰り返し交差検証で 5 つの分類器を比較します。識別、分類、較正の指標を平均(標準偏差)で示し、最良値を太字にし、AUC の差を補正済み検定で調べます。
tidymodels::workflow_map() + collect_metrics()