面板数据回归表

混合 OLS、随机效应、国家固定效应和双向固定效应并排,附聚类标准误、固定效应标识和豪斯曼检验。

面板数据回归表

使用国家-年份数据的应用经济学的主力表格。同一回归用四种方式估计:忽略面板结构的混合 OLS;把各国水平视为随机噪声的随机效应;只保留各国内部变化的国家固定效应;以及同时吸收某一年所有国家共同冲击的双向固定效应。标准误按国家聚类,表尾说明每列包含哪些固定效应、使用了多少观测和国家,以及组内 R² 和总体 R²。

比较各列正是关键。这里,制度质量在那些因其他长期原因吸引更多 FDI 的国家中更高,因此混合 OLS 和随机效应的系数向上偏误;固定效应列消除了这种偏误。稳健豪斯曼检验拒绝随机效应、支持固定效应:这是 Mundlak 版本,把每个解释变量的国家均值加入随机效应模型,并用聚类协方差对它们做联合检验(经典豪斯曼公式可能为负,且忽略聚类)。可混合性 F 检验拒绝混合模型。与 fixest 和 Stata 一样,当固定效应吸收常数项时不报告常数项。

背景是 Stojkov & Warin (2018, Journal of East-West Business) 关于转型经济体中欧盟成员身份与外国直接投资的研究。数据为说明用的模拟数据,并非论文的数据或结果:28 个经济体观测 18 年,FDI 流入以占 GDP 的百分比表示。模型来自 linearmodels(PooledOLS、RandomEffects,以及含 EntityEffects 和 TimeEffects 的 PanelOLS,用 cov_type="clustered" 估计,Mundlak 检验用 wald_test());表格用 Great Tables 构建,采用与本类别其他表格相同的期刊版式。

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

panel-regression.py · 131 行
下载 GitHub
import numpy as np
import pandas as pd
from great_tables import GT, html, loc, style
from linearmodels.panel import PanelOLS, PooledOLS, RandomEffects
# Simulated data, set in the context of Stojkov & Warin (2018) [stojkov2018fdi]

# Data: 28 transition economies × 18 years; a permanent country "attractiveness" raises both
# FDI and institutional quality, so pooled estimates of the institutions effect are biased
rng = np.random.default_rng(2018)
n_c, n_t = 28, 18
country = np.repeat([f"C{i:02d}" for i in range(n_c)], n_t)
year = np.tile(np.arange(2000, 2000 + n_t), n_c)
appeal = np.repeat(rng.normal(0, 1.5, n_c), n_t)                         # unobserved country effect
shock = np.tile(rng.normal(0, 0.8, n_t) + np.linspace(-1, 1, n_t), n_c)  # common year shocks
entry = np.repeat(rng.integers(2004, 2025, n_c), n_t)                    # some never join in-sample
df = pd.DataFrame({
    "country": country, "year": year,
    "eu_member": (year >= entry).astype(int),
    "institutions": 0.6 * appeal + 0.04 * (year - 2000) + rng.normal(0, 0.6, n_c * n_t),
    "openness": np.repeat(rng.normal(0, 1, n_c), n_t) + rng.normal(0, 0.5, n_c * n_t),
    "log_gdp": np.repeat(rng.normal(3, 0.8, n_c), n_t) + 0.03 * (year - 2000) + rng.normal(0, 0.1, n_c * n_t),
    "ulc": rng.normal(0, 1, n_c * n_t),
})
df["fdi"] = (2 + 0.5 * df.institutions + 0.6 * df.openness + 1.2 * df.log_gdp - 0.4 * df.ulc
             + 1.5 * df.eu_member + 1.8 * appeal + shock + rng.normal(0, 1.2, n_c * n_t))
panel = df.set_index(["country", "year"])

labels = {"institutions": "Institutional quality", "openness": "Trade openness",
          "log_gdp": "Market size (log GDP)", "ulc": "Unit labour cost", "eu_member": "EU member (0/1)",
          "Intercept": "Constant"}
rhs = " + ".join(list(labels)[:-1])
specs = {
    "Pooled OLS": PooledOLS.from_formula(f"fdi ~ 1 + {rhs}", panel),
    "Random effects": RandomEffects.from_formula(f"fdi ~ 1 + {rhs}", panel),
    "Country FE": PanelOLS.from_formula(f"fdi ~ 1 + {rhs} + EntityEffects", panel),
    "Two-way FE": PanelOLS.from_formula(f"fdi ~ 1 + {rhs} + EntityEffects + TimeEffects", panel),
}
fits = {k: m.fit(cov_type="clustered", cluster_entity=True) for k, m in specs.items()}
cols = [f"({k + 1})" for k in range(len(fits))]

# Robust Hausman test (Mundlak): add each regressor's country mean to the RE model and
# test that the means are jointly zero with the clustered covariance — FE vs. RE
xs = list(labels)[:-1]
means = panel[xs].groupby(level="country").transform("mean").add_prefix("mean_")
mundlak = RandomEffects.from_formula(f"fdi ~ 1 + {rhs} + " + " + ".join(means.columns),
                                     panel.join(means)).fit(cov_type="clustered", cluster_entity=True)
hausman = mundlak.wald_test(formula=[f"{m} = 0" for m in means.columns])
f_pool = fits["Country FE"].f_pooled
fe_cols = {"(3)", "(4)"}                  # the constant is not reported with fixed effects


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


# Body: coefficient row and standard-error row per term, as in stargazer
rows = []
for term, name in labels.items():
    keep = {c: term in r.params and not (term == "Intercept" and c in fe_cols)
            for c, r in zip(cols, fits.values())}
    coef = {c: num(r.params[term]) + stars(r.pvalues[term]) if keep[c] else ""
            for c, r in zip(cols, fits.values())}
    se = {c: f"({num(r.std_errors[term])})" if keep[c] else "" for c, r in zip(cols, fits.values())}
    rows += [{"term": name, **coef}, {"term": "", **se}]
n_body = len(rows)
coef_rows, se_rows = list(range(0, n_body, 2)), list(range(1, n_body, 2))

# Foot: fixed effects, sample, fit and specification tests
yes_no = lambda flags: dict(zip(cols, ["Yes" if f else "No" for f in flags]))
rows += [
    {"term": "Country fixed effects", **yes_no([0, 0, 1, 1])},
    {"term": "Year fixed effects", **yes_no([0, 0, 0, 1])},
    {"term": "Observations", **{c: f"{r.nobs:,}" for c, r in zip(cols, fits.values())}},
    {"term": "Countries", **{c: f"{r.entity_info['total']:.0f}" for c, r in zip(cols, fits.values())}},
    {"term": "R² (within)", **{c: num(r.rsquared_within) for c, r in zip(cols, fits.values())}},
    {"term": "R² (overall)", **{c: num(r.rsquared_overall) for c, r in zip(cols, fits.values())}},
    {"term": "F-test, no country effects", **dict(zip(cols, ["", "", f"{f_pool.stat:.1f} (p {pval(f_pool.pval)})", ""]))},
    {"term": "Robust Hausman test, FE vs. RE",
     **dict(zip(cols, ["", f"χ²({hausman.df}) = {hausman.stat:.1f} (p {pval(hausman.pval)})", "", ""]))},
]
tab = pd.DataFrame(rows)
n_foot_first = n_body                 # rule above the fixed-effect indicators
n_stats_first = n_body + 2            # thin rule above the sample statistics

table = (
    GT(tab, rowname_col="term")
    .tab_header(title="TABLE IV", subtitle="Institutions, EU membership and FDI: panel estimates")
    .tab_spanner(label="Dependent variable: FDI inflows (% of GDP)", columns=cols, id="dep")
    .cols_label(**{c: html(f"{c}<br>{name}") for c, name in zip(cols, fits)})
    .cols_align("center", columns=cols)
    .cols_width({"term": "210px", **{c: "185px" for c in cols}})
    .tab_source_note(f"Notes: n = {n_c} economies × {n_t} years (simulated). Standard errors clustered by "
                     "country in parentheses. *p < 0.1; **p < 0.05; ***p < 0.01.")
    .tab_source_note("Robust Hausman test: Mundlak regression, Wald test that the country means of the "
                     "regressors are zero. F-test of poolability for (3).")
    # 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"]))
    # standard error tucked under its coefficient
    .tab_style(style.css("padding-bottom: 0;"), [loc.body(rows=coef_rows), loc.stub(rows=coef_rows)])
    .tab_style(style.css("padding-top: 0;"), [loc.body(rows=se_rows), loc.stub(rows=se_rows)])
    # thin rules: above the fixed-effect indicators and above the sample statistics
    .tab_style(style.borders(sides="top", style="solid", weight="1px", color="#000"),
               [loc.body(rows=[n_foot_first, n_stats_first]), loc.stub(rows=[n_foot_first, n_stats_first])])
)
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.
  • Stojkov & Warin (2018), EU membership and FDI. Stojkov, A., & Warin, T. (2018). EU membership and FDI: Is there an endogenous credibility effect? Journal of East-West Business, 24, 144–169. https://doi.org/10.1080/10669868.2018.1431579
    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). Panel data regression 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/panel-regression/

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

更多学术表格图表