Instrumental variables table

OLS against 2SLS, LIML and GMM, with the second stage and the first stage in two panels and the usual diagnostics — first-stage F, partial R², endogeneity and overidentification tests.

Instrumental variables table

When a regressor is endogenous, correlated with the error because of an omitted factor, reverse causality or measurement error, OLS is biased. An instrument shifts the regressor but affects the outcome only through it; two-stage least squares (2SLS) keeps only the variation in the regressor that the instruments explain. The table follows the layout of applied economics journals: Panel A is the second stage, the equation of interest, and Panel B the first stage, the regression of the endogenous variable on the excluded instruments. Column (1) is OLS; (2) uses one instrument (exactly identified); (3) to (5) use three, estimated by 2SLS, LIML (more robust when instruments are weak) and efficient two-step GMM.

The foot gives the diagnostics a referee asks for. The first-stage F of the excluded instruments (heteroskedasticity-robust Wald statistic divided by the number of instruments) should be well above 10; the partial R² is the share of the regressor's variance they explain. The endogeneity test (Wooldridge's robust regression test, or the C statistic for GMM) asks whether trade can be treated as exogenous, and the overidentification test (Wooldridge's score test, or Hansen's J for GMM) checks that the instruments agree with one another; it is not defined with a single instrument. With strong instruments LIML and 2SLS nearly coincide, as here.

The setting is Janicki, Warin & Wunnava (2009) on Mundell's intuition of endogenous optimum currency areas: does trade make business cycles more synchronised? Trade is endogenous — trade driven by specialisation goes with less correlated cycles, which biases OLS downwards — so it is instrumented with gravity variables: distance, a common border and a common language, as in Frankel & Rose (1998). The data are simulated for illustration — they are not the paper's data or results: 435 pairs of 30 countries, with a true effect of trade of 0.080. Pair errors are independent by construction; with real dyadic data, standard errors should allow for correlation across pairs that share a country. The models come from linearmodels (IV2SLS, IVLIML, IVGMM with the [endog ~ instruments] formula syntax, and their first_stage diagnostics); the table is built with Great Tables in the journal style of this family.

instrumental-variables.py · 142 lines
Download 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()

Figures use the optional PyStatlas style: add plt.style.use("pystatlas.mplstyle") to match the look exactly.

Data source

  • 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.

The examples illustrate statistical methods. Their numbers are simulated unless an entry says otherwise, and their titles describe what each figure shows in these simulated data — not findings of the cited papers, nor the author's position on the substantive question. For results, context and data, rely on the papers cited here.

How to cite

PyStatlas is created and maintained by Thierry Warin. If it helped your work, please cite it.

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}
}

More in Academic tables