工具变量表
把 OLS 与 2SLS、LIML 和 GMM 并列,第二阶段和第一阶段分为两个面板,并附常用诊断——第一阶段 F、偏 R²、内生性检验和过度识别检验。

当某个解释变量是内生的,即由于遗漏因素、反向因果或测量误差而与误差项相关时,OLS 是有偏的。工具变量会改变该解释变量,但只通过它影响结果;两阶段最小二乘(2SLS)只保留解释变量中可由工具变量解释的变化。表格采用应用经济学期刊的版式:面板 A 是第二阶段,即我们关心的方程;面板 B 是第一阶段,即内生变量对排除工具变量的回归。第 (1) 列是 OLS;第 (2) 列用一个工具变量(恰好识别);第 (3) 至 (5) 列用三个工具变量,分别用 2SLS、LIML(工具变量较弱时更稳健)和有效的两步 GMM 估计。
表尾给出审稿人会要求的诊断。排除工具变量的第一阶段 F(异方差稳健的 Wald 统计量除以工具变量个数)应远大于 10;偏 R² 是工具变量所解释的解释变量方差比例。内生性检验(Wooldridge 稳健回归检验,GMM 用 C 统计量)检验能否把贸易视为外生,过度识别检验(Wooldridge 得分检验,GMM 用 Hansen J)检查各工具变量是否彼此一致;只有一个工具变量时它没有定义。工具变量很强时,LIML 与 2SLS 几乎一致,正如本例。
背景是 Janicki、Warin 和 Wunnava (2009) 对 Mundell 关于内生最优货币区直觉的检验:贸易会让经济周期更同步吗?贸易是内生的——由专业化驱动的贸易伴随着相关性更低的周期,使 OLS 向下偏——因此像 Frankel & Rose (1998) 那样,用引力变量作工具变量:距离、共同边界和共同语言。数据为说明用的模拟数据,并非论文的数据或结果:30 个国家的 435 个国家对,贸易的真实效应为 0.080。国家对的误差在构造上相互独立;对于真实的双边数据,标准误应考虑共享同一国家的国家对之间的相关。模型来自 linearmodels(使用 [endog ~ instruments] 公式语法的 IV2SLS、IVLIML、IVGMM 及其 first_stage 诊断);表格用 Great Tables 按本类别的期刊版式构建。
代码及图中文字均为英文。
from itertools import combinations
import numpy as np
import pandas as pd
from great_tables import GT, html, loc, style
from linearmodels.iv import IV2SLS, IVGMM, IVLIML
# Simulated data, set in the context of Janicki, Warin & Wunnava (2009) [janicki2009]
# Data: all 435 pairs of 30 countries. Gravity (distance, border, language) drives trade;
# an unobserved specialisation factor raises trade but de-synchronises cycles (OLS biased down)
rng = np.random.default_rng(2009)
C = 30
xy = rng.uniform(0, 30, (C, 2)) # country locations
lang = rng.choice(6, C, p=[.3, .2, .15, .15, .1, .1]) # language groups
gdp = rng.normal(0, 1, C)
i, j = np.array(list(combinations(range(C), 2))).T
dist = np.hypot(*(xy[i] - xy[j]).T) + 0.5
df = pd.DataFrame({"log_dist": np.log(dist), "border": (dist < 5).astype(int),
"language": (lang[i] == lang[j]).astype(int), "size": gdp[i] + gdp[j],
"similarity": rng.uniform(0, 1, len(i))})
n = len(df)
specialisation = rng.normal(0, 1, n) # unobserved
df["trade"] = (1 - 0.9 * df.log_dist + 0.5 * df.border + 0.4 * df.language + 0.4 * df["size"]
- 0.6 * df.similarity + 0.7 * specialisation + rng.normal(0, .6, n))
df["corr"] = (0.25 + 0.08 * df.trade + 0.25 * df.similarity + 0.02 * df["size"]
- 0.07 * specialisation + rng.normal(0, .12, n))
# Five estimators, heteroskedasticity-robust standard errors
exog = "1 + similarity + size"
all_iv = f"corr ~ {exog} + [trade ~ log_dist + border + language]"
fits = {
"OLS": IV2SLS.from_formula(f"corr ~ {exog} + trade", df),
"2SLS": IV2SLS.from_formula(f"corr ~ {exog} + [trade ~ log_dist]", df),
"2SLS ": IV2SLS.from_formula(all_iv, df),
"LIML": IVLIML.from_formula(all_iv, df),
"GMM": IVGMM.from_formula(all_iv, df),
}
fits = {k: m.fit(cov_type="robust") for k, m in fits.items()}
cols = [f"({k + 1})" for k in range(len(fits))]
res = dict(zip(cols, fits.values()))
iv_cols = cols[1:]
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("-", "−")
def pval(p):
return "< 0.001" if p < .001 else f"{p:.3f}"
def coef_rows(panel, labels, get):
"""Coefficient row and standard-error row per term; get(col) returns a fit or None."""
out = []
for term, name in labels.items():
coef, se = {}, {}
for c in cols:
r = get(c)
ok = r is not None and term in r.params
coef[c] = num(r.params[term]) + stars(r.pvalues[term]) if ok else ""
se[c] = f"({num(r.std_errors[term])})" if ok else ""
out += [{"panel": panel, "term": name, **coef}, {"panel": panel, "term": "", **se}]
return out
panel_a = "Panel A. Second stage — dependent variable: business-cycle correlation"
panel_b = "Panel B. First stage — dependent variable: log bilateral trade"
first = lambda c: res[c].first_stage.individual["trade"] if c in iv_cols else None
rows = (coef_rows(panel_a, {"trade": "Log bilateral trade", "similarity": "Industry similarity",
"size": "Economic size (log GDP)", "Intercept": "Constant"}, res.get)
+ coef_rows(panel_b, {"log_dist": "Log distance", "border": "Common border",
"language": "Common language"}, first))
n_a = 8 # rows in Panel A
# Foot: sample and IV diagnostics ("—" where a statistic is not defined)
diag = {c: res[c].first_stage.diagnostics.loc["trade"] for c in iv_cols}
n_inst = {c: len(res[c].model.instruments.cols) for c in iv_cols}
gmm = lambda c: c == "(5)" # GMM has its own tests: C statistic and Hansen's J
endog = {c: res[c].c_stat() if gmm(c) else res[c].wooldridge_regression for c in iv_cols}
overid = {c: res[c].j_stat if gmm(c) else res[c].wooldridge_overid for c in iv_cols if n_inst[c] > 1}
foot = [
("Instruments", ["—"] + ["Distance" if n_inst[c] == 1 else "All three" for c in iv_cols]),
("Observations (country pairs)", [f"{res[c].nobs:,}" for c in cols]),
("First-stage F, excluded instruments", ["—"] + [f"{diag[c]['f.stat'] / n_inst[c]:.1f}" for c in iv_cols]),
("Partial R² of instruments", ["—"] + [num(diag[c]["partial.rsquared"]) for c in iv_cols]),
("Endogeneity test, p-value", ["—"] + [pval(endog[c].pval) for c in iv_cols]),
("Overidentification test, p-value", ["—"] + [pval(overid[c].pval) if c in overid else "—" for c in iv_cols]),
]
panel_f = "Diagnostics"
rows += [{"panel": panel_f, "term": t, **dict(zip(cols, v))} for t, v in foot]
tab = pd.DataFrame(rows)
coef_idx = [k for k in range(len(tab) - len(foot)) if k % 2 == 0]
se_idx = [k for k in range(len(tab) - len(foot)) if k % 2 == 1]
table = (
GT(tab)
.tab_stub(rowname_col="term", groupname_col="panel")
.tab_header(title="TABLE VI", subtitle="Trade integration and business-cycle synchronisation: IV estimates")
.tab_spanner(label="Instrumental variables", columns=iv_cols, id="iv")
.cols_label(**{c: html(f"{c}<br>{name.strip()}") for c, name in zip(cols, fits)})
.cols_align("center", columns=cols)
.cols_width({"term": "250px", **{c: "142px" for c in cols}})
.tab_source_note(f"Notes: n = {n} country pairs of {C} countries (simulated); true effect of log trade = 0.080. "
"Heteroskedasticity-robust standard errors in parentheses. *p < 0.1; **p < 0.05; ***p < 0.01. "
"The first stage also includes industry similarity, economic size and a constant.")
.tab_source_note("First-stage F: robust Wald statistic of the excluded instruments divided by their number. "
"Endogeneity: Wooldridge's robust regression test (C statistic for GMM). Overidentification: "
"Wooldridge's score test (Hansen's J for GMM).")
# 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",
row_group_border_top_style="none", row_group_border_bottom_style="none",
row_group_padding="6px",
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="3px", 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.row_groups(), loc.spanner_labels(ids=["iv"])])
# standard error tucked under its coefficient
.tab_style(style.css("padding-bottom: 0;"), [loc.body(rows=coef_idx), loc.stub(rows=coef_idx)])
.tab_style(style.css("padding-top: 0;"), [loc.body(rows=se_idx), loc.stub(rows=se_idx)])
# thin rules above Panel B and above the diagnostics
.tab_style(style.borders(sides="top", style="solid", weight="1px", color="#000"),
loc.row_groups(rows=[panel_b, panel_f]))
)
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. - Janicki, Warin & Wunnava (2009), endogenous optimum currency areas. Janicki, H., Warin, T., & Wunnava, P. (2009). Testing Mundell's intuition of endogenous OCA theory. Review of International Economics, 17(1), 74–86. https://doi.org/10.1111/j.1467-9396.2008.00802.x
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). Instrumental variables 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/instrumental-variables/
@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 风格的回归表
三个嵌套 OLS 模型并排,系数下方是标准误,表尾是拟合统计量,按期刊表格排版。
stargazer::stargazer(type = "html")描述性统计表
实证论文的“表 1”——按面板列出每个变量的 N、均值、标准差、最小值、中位数和最大值,并给出分组均值及其差异检验。
modelsummary::datasummary_balance()机器学习模型比较表
用重复交叉验证比较五个分类器——区分度、分类和校准指标以均值(标准差)表示,最优值加粗,并对 AUC 差距做校正检验。
tidymodels::workflow_map() + collect_metrics()