操作変数法の表

OLS と 2SLS、LIML、GMM を比べます。第 2 段階と第 1 段階を 2 つのパネルに分け、第 1 段階 F、偏 R²、内生性検定、過剰識別検定といった定番の診断を添えます。

操作変数法の表

説明変数が内生的で、欠落要因、逆因果、測定誤差のために誤差項と相関していると、OLS は偏ります。操作変数は説明変数を動かしますが、結果にはその説明変数を通じてしか影響しません。2 段階最小二乗法(2SLS)は、操作変数で説明される説明変数の変動だけを使います。表は応用経済学の学術誌の体裁に従います。パネル A は関心のある式である第 2 段階、パネル B は内生変数を除外操作変数に回帰した第 1 段階です。列 (1) は OLS、(2) は操作変数 1 つ(丁度識別)、(3)〜(5) は 3 つの操作変数を使い、それぞれ 2SLS、LIML(操作変数が弱いときにより頑健)、効率的な 2 段階 GMM で推定します。

表の末尾には査読者が求める診断を示します。除外操作変数の第 1 段階 F(不均一分散に頑健な Wald 統計量を操作変数の数で割ったもの)は 10 を大きく上回るべきです。偏 R² は操作変数が説明する説明変数の分散の割合です。内生性検定(Wooldridge の頑健な回帰検定、GMM では C 統計量)は貿易を外生として扱えるかを問い、過剰識別検定(Wooldridge のスコア検定、GMM では Hansen の J)は操作変数どうしが整合しているかを確かめます。操作変数が 1 つのときは定義されません。操作変数が強いと、ここでのように 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 を使って組みます。

コードおよび図中のテキストは英語です。

instrumental-variables.py · 142 行
ダウンロード GitHub
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}
}

学術論文の表のその他のグラフ