SuperAPI AI Directory

Foreign-CF-Study

Writing & research

View repository

Updated 10-15 17:30

About this skill

Foreign Corporate Finance Empirical Study (foreign-cf-study)

1. Positioning and Scope of Application

This skill guidescorporate finance empirical research based on a foreign (non-China) institutional environmentas a complete workflow. It mainly covers:

  • US samples (primary): WRDS databases such as CRSP / Compustat / IBES / Thomson-Reuters / BoardEx / ExecuComp / 13F / Dealscan / SDC Platinum, etc.
  • International samples: Compustat Global, Worldscope, Orbis/BvD, Amadeus, Osiris (Europe/multinational), Nikkei NEEDS (Japan), SDC M&A (global)
  • Identification strategies: DID (including staggered / Callaway-Sant'Anna / Sun-Abraham / Stacked DID), Panel FE + IV/2SLS, PSM-DID / Entropy Balancing, DML / DML-IV, Synthetic Control / Synthetic DID, RDD (including Geographic RDD, Regression Kink), SEO / IPO event studies, high-frequency identification (high-frequency FOMC shocks, FedFund rate shocks, etc.)
  • Research topics: investment and financing, capital structure, dividend policy, M&A, IPO/SEO, corporate governance (boards, CEO compensation), institutional investors (13F, mutual funds), analysts, ESG / CSR, bank credit (Dealscan), bankruptcy (Chapter 11), taxation (TCJA / state corporate tax), regulation (SOX, Dodd-Frank, JOBS Act, MiFID II, GDPR), trade (China Shock, Trade War, Brexit), innovation (USPTO patents, NBER patent database)
  • Code language: Python(pandas / numpy / statsmodels / linearmodels / pyfixest / econml / doubleml / scikit-learn / matplotlib / wrds-py)
  • Table output: LaTeX(strictly follow the template/ format and rule/ specifications)

This skill does not replace the researcher's judgment on research design; rather, it provides the researcher with thestandard workflow, code skeleton, and table/figure templatesfor each stage, ensuring that the output quality meets the writing and methodological requirements of top international corporate finance journals (JF, JFE, RFS, JFQA, RCFS, RAPS; JAR, JAE, TAR, RAST in accounting; AER, QJE, JPE, REStud in general-interest economics).

2. Working Directory Structure (the project root is the working directory)

Foreign-CF-study/                 ← working directory
├── asset/                        ← **优先**的数据源索引(非唯一来源,详见 §7)
│   ├── nber_releases_list.csv         # NBER / 美联储(Fed)/ BLS / BEA 定期发布清单
│   ├── wrds_research_data_overview.pdf # WRDS 数据库概览(CRSP、Compustat、IBES、BoardEx、13F…)
│   ├── macrodatas_list.csv            # 全球宏观数据索引(含 IMF / WB / OECD / FRED 条目)
│   ├── ppmandata_trade_list.csv       # 贸易 / 关税 / 供应链层面扩展数据索引
│   └── MCP.docx                       # 登记的 MCP 服务器清单(IMF / World Bank / Supply Chain / OECD),
│                                      #   作为 asset/ 本地清单缺失时的补充来源;安装方式见各 URL
├── rule/                         ← 强制性写作与方法论规范(AI 必须逐项遵循)
│   ├── 通用实证研究逻辑与规范总结.docx
│   └── 回归表写作规范总结.docx
├── template/                     ← LaTeX 表格与图片模板(格式模仿对象)
│   ├── sum_stat.tex                   # 描述性统计
│   ├── variables.tex                  # 变量定义
│   ├── baseline.tex                   # 基准回归(渐进式加控制 + 渐进式加 FE)
│   ├── addctr.tex                     # 加入附加控制变量
│   ├── measures.tex                   # 替换因变量度量
│   ├── specification.tex              # 高维交互固定效应
│   ├── iv.tex                         # 2SLS 工具变量
│   ├── psm_ddml.tex                   # PSM + DML(Panel A / Panel B)
│   ├── bunching-did.tex               # Bunching-DID
│   ├── channel1.tex, channel2.tex, channel3.tex   # 机制分析(按渠道分组)
│   ├── heterogeneity1.tex, heterogeneity2.tex, heterogeneity3.tex # 异质性(bdiff)
│   ├── sampling.tex                   # 样本筛选稳健性
│   ├── further.tex                    # 进一步分析
│   ├── main.tex                       # 论文正文骨架
│   ├── parallel.pdf                   # 平行趋势图
│   ├── csdid-figure.pdf               # Callaway-Sant'Anna DID 动态效应
│   ├── estimator.pdf                  # 不同 DID 估计量对比
│   ├── psm-pre-post.pdf               # PSM 平衡检验前后
│   └── specurve.pdf                   # 规格曲线(specification curve)
└── 研究项目输出/                   ← 每个实证项目的产出目录(按本 skill 建议结构创建)
    └── {项目名}/
        ├── data/{raw,cleaned}/
        ├── code/                       # Python 脚本
        ├── results/                    # 表格 (.tex) 与图像 (.pdf/.png) 统一存放,不再区分 tables/ 与 figures/
        ├── ref.bib                     # 参考文献数据库
        └── main.tex                    # 论文正文(**位于项目根,不放入 paper/ 子目录**)
                                        # 头部样式与 \bibliography / \appendix 结构严格照搬 template/main.tex
                                        # 通过 \input{results/xxx} 引入表格;通过 \includegraphics{results/xxx.pdf} 引入图像

3. Trigger Conditions and Startup Workflow

3.1 The sole trigger condition: the researcher submits a research proposal

This skill onlytriggers when the researcher provides a **Research Proposal**. The proposal may be submitted in any of the following forms:

  • A plain-text description
  • .docx / .pdf / .md / .tex A file path
  • Items listed point by point in the conversation

3.2 Fields that the proposal should contain (if items are missing, automatically follow up and complete them all at once)

CONTRACT — 研究计划书最小字段清单
────────────────────────────────────────────────────────
(1) 研究题目 (Title)
(2) X → Y 因果假设 (Hypothesis):主假设 H1 + 最多 2 条子假设
(3) 预期结果 (Expected Findings):X 对 Y 的预期符号与显著性、预期机制
    渠道、预期异质性方向(此项至关重要——是后续"备选方案"的触发判据)
(4) 识别策略 (Identification):DID / Staggered DID / Panel FE + IV /
    PSM-DID / RDD / Synthetic Control / Synthetic DID / DML / Event Study 中择一
(5) 样本范围 (Sample):国家/地区、层级(公司-年/公司-季度/交易-日/state-年)、
    时间窗、交易所(NYSE/NASDAQ/AMEX)、是否剔除 ADR/Dual class、排除条款
(6) 政策冲击 (Shock):【DID/RDD 必填】政策名称(e.g., SOX 2002, Dodd-Frank 2010,
    JOBS Act 2012, TCJA 2017, MiFID II 2018, Brexit 2016, China Shock,
    state corporate tax changes, state-level minimum wage...)、公布/实施年份/月份、
    处理组定义(e.g., pre-SOX accelerated filers, post-JOBS Act EGCs...)
(7) 数据需求 (Data):asset/ 中需检索的关键词清单(WRDS 库名 + 政策集)
(8) 机制假说 (Mechanism):预期作用渠道 M1 / M2 / M3
(9) 异质性维度 (Heterogeneity):预期分组维度(公司规模、融资约束、KZ/WW index、
    董事会独立性、机构持股、行业集中度 HHI、所处州等)+ 预期组间差异方向

3.3 Immediately after startup, the skill performs the following actions

  1. Parse the proposal -> extract the nine CONTRACT fields, and follow up once to complete all missing items at the same time.
  2. 🆕 Recommend the 5 most suitable target journals (see §3.4): based on the four dimensions of the proposal—research topic (Topic), identification strategy (Method), contribution margin (Novelty), and sample scope (Sample)—select the top 5 from the foreign CF top-journal pool (§3.4.1) by weighted score (§3.4.2), and present them as [J1]–[J5] A number + 4-dimensional star rating + a one- or two-sentence "Why it fits" + "Editorial preference" + bib style presentation (see §3.4.3 for the output format).After presenting, stop and explicitly ask the researcher which one to choose(the user is also allowed to propose journals outside the list). Before receiving the choice,do not proceed to step 3。
  3. Solidify as 00_proposal.md: write to the project root {项目名}/00_proposal.md,append at the top as a YAML block the target_journal / bibliography_style / writing_preferences three groups of fields(see the example at the end of §3.4.3), as the baseline file for all subsequent judgments and main.tex rendering.
  4. Generate the research project skeleton: according to the directory structure in Section 9, establish {项目名}/ all subdirectories and placeholder scripts under it;main.tex in the header, according to the table in §3.4.4, replace \bibliographystyle{} and the Section skeleton with the version for the target journal.
  5. Advance stage by stage: strictly follow the order in Section 4, and upon completing each stage, compare with the expected results (3) in the planitem by item。

3.4 Journal Targeting — the basis for the second step after startup

3.4.1 Candidate journal pool (common submission pools for foreign CF)

Tier Journal Full name Preference characteristics bib style
T1 General AER American Economic Review Extremely strong causal identification + broad economic significance; CF must be able to tell a "story beyond finance" aer
T1 General QJE Quarterly Journal of Economics Natural experiments + far-reaching policy implications; rare for CF but there are precedents qje
T1 General JPE Journal of Political Economy Leans toward theoretical structural estimation; CF is mostly seen in governance and contracts jpe
T1 General RES Review of Economic Studies Leans toward structural + methodological innovation restud
T1 Finance JF Journal of Finance Complete story + deep mechanisms + large sample; prefers "new phenomena / new mechanisms" jf
T1 Finance JFE Journal of Financial Economics Rigorous identification + CF/asset pricing; the strictest table formatting jfe
T1 Finance RFS Review of Financial Studies Theoretical embedding + empirical linkage rfs
T2 Finance JFQA Journal of Financial and Quantitative Analysis Rigorous empirical work; suitable for moderate contributions with clear identification jfqa
T2 Finance RCFS Review of Corporate Finance Studies CF-dedicated OA journal rcfs
T2 Finance RAPS Review of Asset Pricing Studies Mainly asset pricing raps
T2 Finance JCF Journal of Corporate Finance Mainstream mid-to-lower-tier CF journal elsarticle-num
T2 Finance JBF Journal of Banking and Finance Banking / cross-country / regulatory elsarticle-num
T2 Finance JFI Journal of Financial Intermediation Banking / credit / intermediation jfi
T2 Finance JFM Journal of Financial Markets Microstructure / liquidity elsarticle-num
T2 Finance FM Financial Management CF application-oriented apa
T1 Accounting JAR Journal of Accounting Research Information disclosure / intersection of analysts and CF jar
T1 Accounting JAE Journal of Accounting and Economics Economic consequences of accounting choices; contracts / governance jae
T1 Accounting TAR The Accounting Review Broadest coverage, high identification requirements tar
T2 Accounting RAST Review of Accounting Studies Information environment / valuation / disclosure rast
T2 Accounting CAR Contemporary Accounting Research Similar platform to TAR car
Management MS Management Science Interdisciplinary innovation / data science / causality informs
Management SMJ Strategic Management Journal Governance / M&A / corporate strategy smj
Management OS Organization Science Organization + CF intersection (board, CEO) orsc
International JIBS Journal of International Business Studies Cross-border / institutional differences / cross-border M&A jibs
Public JPubE Journal of Public Economics CF consequences of taxation / regulation elsarticle-num
Labor ILR Industrial and Labor Relations Review Labor × CF intersection sage
Environmental JEEM Journal of Environmental Economics and Management ESG / climate policy × CF elsarticle-num

If the researcher names a journal outside the list (e.g., Journal of Accounting and Public Policy、Financial Review、European Financial Management、Pacific-Basin Finance Journal、Journal of Banking & Finance Letters , etc.), simply select it as specified, and apply the bib style and Section skeleton by analogy to journals of the same tier.

3.4.2 Matching scoring (internal to skill)

Score each candidate on 4 dimensions from 1–5:

T = topic_fit       # CF 主题与期刊偏好对齐
M = method_fit      # 识别策略与期刊门槛对齐
N = novelty_fit     # 贡献边际能否打动该刊编辑
S = sample_fit      # 样本与期刊地理偏好
score = 0.35 T + 0.30 M + 0.25 N + 0.10 S

Matching examples (for internal skill reference only; not output to the researcher):

  • "SOX × investment efficiency (U.S. staggered DID)" → JFE / JF / JAR / RFS / JFQA
  • "TCJA 2017 × capital expenditure" → JFE / JPubE / JAE / JF / AER
  • "Brexit × cross-border investment and financing" → JFE / JIBS / JF / MS / JFQA
  • "U.S. innovation policy × corporate investment spillovers" → JFE / AER / RFS / MS / JF
  • "MiFID II × analyst coverage and corporate information environment" → JAR / JAE / RFS / JFE / TAR
  • "Dodd-Frank × bank credit supply" → JFE / RFS / JF / JFI / JBF

3.4.3 Recommended output format (must present 5 journals in this format)

[J1] JFE — Journal of Financial Economics
     Topic ★★★★★  Method ★★★★★  Novelty ★★★★☆  Sample ★★★★★   Score 4.70
     Why it fits: {2 句话——对齐研究主题与识别方法;指本刊近 3 年发表的相近政策/主题论文(举 1 篇)}
     Editorial preference: 偏好识别透明 + 表格规范严 + 控制变量逐项展示
     Bibliography style: jfe

[J2] JF  — Journal of Finance
     ...

After presenting the 5 journals,must explicitly stop and ask(do not automatically select):

Please select one from [J1]–[J5] as the target journal; if dissatisfied, please directly tell me any top foreign CF journal name. Your choice will determine main.tex 's \bibliographystyle{}, Section skeleton, Introduction style, and minimum table note length.

After the researcher selects, append at the top of 00_proposal.md (example is JFE):

---
target_journal: JFE
bibliography_style: jfe
writing_preferences:
  identification_emphasis: high
  table_format_strict: yes
  introduction_style: "5 paragraphs, identification details surface early"
  notes_paragraph_length: ">= 6 lines"
  section_skeleton:
    - Introduction
    - Background
    - Data
    - Empirical Strategy
    - Results
    - Robustness
    - Conclusion
---

3.4.4 Writing differences triggered by different journals

Journal bib style Section skeleton Intro style Minimum table notes Special requirements
JF jf Intro / Setting / Hypotheses / Data and Methodology / Results / Mechanism / Conclusion 5–6 paragraphs, puzzle-driven ≥ 8 lines Prefers concise column headers; appendix no more than 30% of main text
JFE jfe Intro / Background / Data / Empirical Strategy / Results / Robustness / Conclusion 5 paragraphs, identification details appear early ≥ 6 lines Strictest table conventions; requires showing control variables one by one; clearly state standard error clustering
RFS rfs Intro / Theoretical Motivation / Data / Identification / Empirical Findings / Conclusion 4–5 paragraphs, theoretical motivation prominent ≥ 6 lines Prefers embedded theory; main text 25–30 pages
JFQA jfqa JFE-like JFE-like ≥ 5 lines Strict table conventions; prefers clear identification of new phenomena
JAR / JAE jar / jae Intro / Hypothesis / Sample and Data / Research Design / Results / Conclusion 6 paragraphs, hypothesis in a separate §2 ≥ 6 lines Predictive hypotheses; hypothesis section must be independent
TAR tar JAR-like JAR-like ≥ 5 lines JAR-like; prefers new measures
AER aer Intro / Background / Data / Empirical Strategy / Results / Mechanism / External Validity / Conclusion 4 paragraphs, broad impact ≥ 5 lines Must have an external validity discussion; broad economic implication
QJE / JPE / RES qje / jpe / restud AER-like (more compact structure) 4 paragraphs, puzzle + economic significance ≥ 5 lines Readability across subdisciplines; requires significant methodological/conceptual innovation
MS informs Intro / Background / Hypotheses / Data and Methods / Results / Discussion / Conclusion 4–5 paragraphs, interdisciplinary motivation ≥ 5 lines Must include managerial implication
JCF / JBF / JPubE / JEEM elsarticle-num JFE-like 4 paragraphs ≥ 5 lines More flexible; narrower topics acceptable
JIBS jibs Intro / Theory and Hypotheses / Methods / Results / Discussion / Conclusion 5 paragraphs, cross-country comparative perspective ≥ 5 lines Must include international business contribution

render_main_tex() When generating main.tex , read 00_proposal.md 's target_journal / bibliography_style / section_skeleton, automatically replace \bibliographystyle{} and Section naming; at the same time pass the target journal's notes_paragraph_length threshold into each render_*_tex() function, ensuring that the table note length reaches the target journal threshold.

3.A Adaptive mechanism (Plan-B): switching logic when results do not meet expectations

The core capability of this skill—when the empirical results of any step do not match the "(3) Expected results" in 00_proposal.md , the skill does not require researcher interventionand autonomously selects and executes from the following alternative plan tree until the research project reaches closure.

3.A.1 Failure criteria (triggered immediately after each step is completed)

Step Expected result Failure criterion (triggers Plan-B)
Parallel trends test All pre-period coefficients are insignificant Any pre-period |t| > 1.96
Baseline regression The sign of the X coefficient is consistent with expectations and p < 0.1 Sign is reversed / all insignificant / coefficient jumps substantially as control variables/FE are added
Robust DID estimators CS-DID / Sun-Abraham / Stacked conclusions are directionally consistent with TWFE Sign is reversed or the p-value magnitude does not match at all
IV first stage F statistic > 10 (Kleibergen-Paap), IV significant F < 10 or IV insignificant
IV second stage LATE is directionally consistent with OLS and interpretable Sign is reversed and the magnitude is anomalous
Mechanism analysis Expected channels M1/M2/M3 are significant All channels are insignificant
Heterogeneity Expected between-group differences along the dimension are significant bdiff p > 0.1
Robustness The sign/significance of the X coefficient is stable in most columns More than 1/3 of columns flip
Placebo The true coefficient lies outside the false distribution The true coefficient falls within the [5%, 95%] range of the false distribution

3.A.2 Plan-B decision tree (try in order; each step can be stacked)

失败环节 → 依次尝试:

【基准回归】系数不显著 / 符号反向
  ├─ B1. 替换 Y 度量(从 template/measures.tex 思路:log(1+Y)、缩尾重算、
  │       行业/年份调整后的残差、Book vs Market leverage、Cash / Net debt 切换)
  ├─ B2. 替换 X 度量(连续 vs 虚拟 / 强度 vs 0-1 / 滞后一期 vs 当期)
  ├─ B3. 替换 FE 规格(加 Industry×Year (FF48/49)、State×Year、Firm×Quarter 高维交互)
  ├─ B4. 替换聚类层级(firm → industry → state → industry×year 双向)
  ├─ B5. 样本细化(剔除 SIC 6000-6999 金融业、SIC 4900-4949 公用事业;
  │       剔除 ADR、dual-class、IPO 当年、total assets < $10M 小样本、
  │       锁死 NYSE/AMEX/NASDAQ 普通股 share code 10/11)
  ├─ B6. 换时间窗(缩短到政策前后 ±5 年 / 剔除 2008-09 金融危机 / 剔除 2020 COVID)
  └─ B7. 若仍不显著 → 考虑反向假设(Y→X 或 U 型/门槛),在 proposal 中注明假设修正

【平行趋势】pre 期显著
  ├─ B1. 重新定义政策时点(announce vs effective vs compliance deadline;
  │       SOX 分 accelerated (2004) / non-accelerated (2007) filer)
  ├─ B2. 用 Sun-Abraham / CS-DID / Stacked DID 替代 TWFE(避免负权重问题)
  ├─ B3. 限制政策前窗口(仅保留 pre_3 到 last_K)
  ├─ B4. 加入 Group × linear trend 控制差异化趋势
  └─ B5. 改为 PSM-DID / Entropy Balancing 缓解选择偏差后重测

【IV 第一阶段弱】F < 10(Stock-Yogo / KP-rk Wald)
  ├─ B1. 尝试 asset/ 中其他同维度外生冲击(e.g., 历史定居地 → Bartik;
  │       州际距离;历史 broadband 铺设;历史 interstate highway network)
  ├─ B2. 构造 Bartik / Shift-Share IV(行业份额 × 全国冲击;Autor-Dorn-Hanson 型)
  ├─ B3. 用 Judge IV(法官随机分配)/ Lottery IV / 同伴均值 (peer mean within industry-year)
  ├─ B4. 改为 DML-Partial(弱化 IV 依赖,用 ML 处理高维混淆)
  └─ B5. 改用断点/匹配的自然实验替代 IV(RDD / Synthetic Control / Stacked DID)

【机制不显著】所有 M 均无效应
  ├─ B1. 换中介变量度量(同一渠道的不同代理;e.g., 信息不对称可用
  │       bid-ask spread / analyst forecast dispersion / PIN / Amihud illiquidity)
  ├─ B2. 换渠道组合(从"信息→治理→融资"三维度替换)
  ├─ B3. 拆分样本(分组后分别做机制,寻找条件性渠道)
  ├─ B4. 改用交互项检验(X × M → Y 是否有调节)
  └─ B5. 若仍无渠道显著 → 在"进一步分析"中承认黑箱,改做异质性深挖

【异质性不显著】bdiff p > 0.1
  ├─ B1. 换分组切点(median → tertile / quartile)
  ├─ B2. 换分组变量(同维度其他代理:如融资约束可用 KZ → WW → SA → HP index)
  ├─ B3. 连续调节变量做交互项(公司级)
  ├─ B4. 换分组维度("公司层面→行业层面→地区层面→宏观层面"四大簇切换)
  └─ B5. 保留为"null heterogeneity"——在论文正文中作为结论的边界条件陈述

【稳健性大面积翻转】
  ├─ B1. 回溯样本构造(检查 CRSP share code、SIC、delisting code、
  │       CRSP-Compustat Merged link、IBES ticker 对齐)
  ├─ B2. 检查是否遗漏同期政策(e.g., SOX 与 Reg FD 重叠)→ 加入 co-shock dummy
  ├─ B3. 重算处理组/对照组的定义口径
  └─ B4. 若仍不稳健 → 核心结论弱化为"条件性证据",在正文强调边界

【安慰剂失败】真实系数落在虚假分布内
  ├─ B1. 增加 reps(500 → 1000 → 2000)
  ├─ B2. 换安慰剂设计(跨公司随机 → 跨时间随机 → 跨行业随机 →
  │       跨州随机;"fake treatment" assigned to untreated firms only)
  ├─ B3. 回溯基准 → 基准本身可能有 confounder,返回【基准回归】的 B1-B7

3.A.3 Mandatory record when switching

Each time Plan-B is triggered, one entry must be appended in {项目名}/DECISION_LOG.md :

## YYYY-MM-DD HH:MM — 环节 {X} Plan-B
- **预期**(引自 proposal 第 3 条):...
- **实测**:系数 = ..., t = ..., p = ...
- **触发判据**:...
- **选择分支**:B{n} — {方案名}
- **后续调整**:...
- **再测结果**:...

3.A.4 Termination conditions

  • Success: baseline regression + mechanism + heterogeneity + robustness + placebo all pass (or some can be explained in the form of "boundary conditions")
  • Downgraded closure: when the depth of Plan-B exceeds 3 levels and still cannot converge, downgrade the study to a "null-effect identification report" or "conditional evidence report"; the output is still complete: all .tex / figures / code are delivered as usual, and the conclusion paragraph of the main text is rewritten as a null-result narrative
  • Never: abandon the project or "surrender" to the researcher; the skill must produce a complete, deliverable research output

4. Main line of research logic (strictly in order, not to be reversed)

The order comes from rule/通用实证研究逻辑与规范总结.docx Section 7.2. Each step is accompanied by the Python code skeleton below and the corresponding LaTeX template in template/.

# Stage Required? Corresponding Python output Corresponding LaTeX template
1 Descriptive statistics Required 02_sumstat.py → sum_stat.tex template/sum_stat.tex + variables.tex
2 Parallel trends test DID Required; others skipped 03_parallel.py → results/parallel.pdf template/parallel.pdf
3 Heterogeneity-robust DID estimator staggered DID Required 03b_csdid.py(CS-DID / Sun-Abraham / Stacked) template/csdid-figure.pdf + estimator.pdf
4 Baseline regression Required (the anchor) 04_baseline.py → baseline.tex template/baseline.tex
5 Endogeneity test Panel FE Required; recommended for DID 05_iv.py + 05b_dml.py template/iv.tex + psm_ddml.tex Panel B
6 Dependent variable decomposition / alternative measures Recommended 06_measures.py template/measures.tex
7 Heterogeneity analysis Required 07_hetero1.py, 07_hetero2.py, 07_hetero3.py template/heterogeneity1/2/3.tex
8 Mechanism analysis Required 08_channel1.py, 08_channel2.py, 08_channel3.py template/channel1/2/3.tex
9 Robustness checks (placed in appendix) Required 09_addctr.py, 09_spec.py, 09_sampling.py, 09_bunching.py template/addctr/specification/sampling/bunching-did.tex
10 PSM-DID / Entropy Balancing DID Recommended 10_psm.py → psm_ddml.tex Panel A template/psm_ddml.tex + psm-pre-post.pdf
11 Placebo test Required 11_placebo.py → results/placebo.pdf Refer to rule Section 5.2 placebo distribution plot specification
12 Further analysis / specification curve Optional 12_further.py, 12_specurve.py template/further.tex + specurve.pdf

5. Python code skeleton (all using Python, not using Stata)

Iron rule: this skill always implements econometrics in Python.rule/ The Stata code in (esttab, etc.) is for format reference only; the final .tex is rendered directly by Python functions in the handwritten table-shell format of template/.

5.1 Dependencies and standard imports

# 所有脚本统一导入
import numpy as np
import pandas as pd
import statsmodels.api as sm
from linearmodels.panel import PanelOLS
from linearmodels.iv import IV2SLS
import pyfixest as pf                  # 高维固定效应 + reghdfe 等价
from doubleml import DoubleMLPLR, DoubleMLPLIV, DoubleMLData
from sklearn.linear_model import LassoCV, RidgeCV
from sklearn.ensemble import RandomForestRegressor
import lightgbm as lgb
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.family'] = 'Times New Roman'
mpl.rcParams['axes.facecolor'] = 'white'
mpl.rcParams['figure.facecolor'] = 'white'
mpl.rcParams['axes.edgecolor'] = 'black'

# 若使用 WRDS 原生接口
# import wrds
# db = wrds.Connection(wrds_username='...')  # 研究者提供凭证;skill 不替研究者保存

5.2 Standard regression with fixed effects + clustered standard errors

def reg_hdfe(df, y, x, controls, fe, cluster):
    """
    y: 因变量名 (str)
    x: 核心解释变量名 (str)
    controls: 控制变量名列表
    fe: 固定效应列表, e.g. ['gvkey','fyear']  # firm + year
                       or ['gvkey','fyear','ff48']  # firm + year + industry
    cluster: 聚类层级, e.g. 'gvkey'  (firm-clustered SE, Petersen 2009 标准)
    返回 pyfixest.Feols 对象
    """
    rhs = x + ' + ' + ' + '.join(controls)
    fe_str = ' + '.join(fe)
    formula = f"{y} ~ {rhs} | {fe_str}"
    return pf.feols(formula, data=df, vcov={'CRV1': cluster})

5.3 Instrumental variables / 2SLS (including Kleibergen-Paap rk Wald F)

def iv_2sls(df, y, x_endog, instruments, controls, fe, cluster):
    """
    pyfixest 原生支持 IV:
      formula = "y ~ controls | FE | (x_endog ~ iv1 + iv2)"
    报告 Kleibergen-Paap rk Wald F(弱工具检验)、Hansen J(过度识别检验)。
    常用外国 IV:Bartik / Shift-share、历史 broadband 铺设、historical settler mortality、
    geographic distance、judge fixed effect、natural disaster exposure 等。
    """
    rhs = ' + '.join(controls)
    fe_str = ' + '.join(fe)
    iv_str = f"({x_endog} ~ {' + '.join(instruments)})"
    formula = f"{y} ~ {rhs} | {fe_str} | {iv_str}"
    return pf.feols(formula, data=df, vcov={'CRV1': cluster})

5.4 Double Machine Learning(DML / DML-IV)

def dml_plr(df, y, d, controls, learner='lasso', n_folds=5, n_reps=10):
    learners = {
        'lasso': LassoCV(cv=5),
        'ridge': RidgeCV(),
        'rf':    RandomForestRegressor(n_estimators=500, max_depth=8, n_jobs=-1),
        'lgbm':  lgb.LGBMRegressor(n_estimators=500, num_leaves=31),
    }
    dml_data = DoubleMLData(df, y_col=y, d_cols=d, x_cols=controls)
    model = DoubleMLPLR(dml_data,
                        ml_l=learners[learner],
                        ml_m=learners[learner],
                        n_folds=n_folds, n_rep=n_reps)
    model.fit()
    return model   # .coef, .se, .t_stat, .pval, .confint()

5.5 Staggered DID:Callaway-Sant'Anna / Sun-Abraham / Stacked DID

# Sun-Abraham:interaction-weighted estimator,用 pyfixest 的 sunab() 便捷函数
# CS-DID:用 Python 包 "csdid" 或 "differences";或手写 group-time ATT 聚合
# Stacked DID:Cengiz et al. (2019) / Deshpande-Li (2019) 风格

def csdid_event_study(df, y, cohort, time, controls, cluster):
    """
    cohort: 处理开始年份(未处理组为 NaN/Inf)
    time:   日历年份
    返回:{e: att, se, ci} 的字典,用于画动态效应图(event_study plot)
    实现 Callaway & Sant'Anna (2021);或调用 pyfixest.feols 配合
    i(time, treat, ref=-1) 画事件研究(TWFE)作对照。
    """
    ...

def stacked_did(df, y, treat, cohort, time, controls, cluster, window=(-5, 5)):
    """
    Stacked DID:为每个 cohort 构造 "clean" control pool(永不处理 + 尚未处理),
    复制行叠加后跑 TWFE。规避异质处理效应下的负权重问题。
    """
    ...

5.6 PSM / Entropy Balancing

def psm_match(df, treat, covariates, k=4, caliper=0.002):
    """最近邻 1:k 匹配 + caliper。返回带权重的新 DataFrame。
       对应 template/psm-pre-post.pdf 的平衡检验图。"""
    from sklearn.linear_model import LogisticRegression
    from sklearn.neighbors import NearestNeighbors
    # 估计倾向得分 → 最近邻匹配 → 返回匹配后样本
    ...

def entropy_balance(df, treat, covariates):
    """使用 ebalance / cvxpy 实现熵平衡重加权(Hainmueller 2012)。"""
    ...

5.7 Bootstrap Fisher permutation test (between-group heterogeneity difference)

def bdiff_bootstrap(df, y, x, controls, fe, cluster, group_var, reps=500, seed=42):
    """
    对异质性分析的两组(High/Low)做 bootstrap Fisher 置换检验。
    rule/ 回归表写作规范总结.docx 第 4.5 节要求 500 reps。
    返回:p-value for (b_high - b_low)
    """
    rng = np.random.default_rng(seed)
    ...

5.8 Synthetic Control / Synthetic DID (cross-country / state-level policy)

def synthetic_control(df, outcome, unit, time, treat_unit, treat_time,
                       predictors, donor_pool):
    """Abadie-Diamond-Hainmueller (2010) 合成控制法。
       适用:单一处理单元(single-country / single-state shock),
       e.g., Brexit, German reunification, California tobacco control."""
    ...

def synthetic_did(df, outcome, unit, time, treat_unit, treat_time):
    """Arkhangelsky et al. (2021) Synthetic DID。
       综合 SC 与 DID 的思路,适合多处理单元 + 时期加权。"""
    ...

6. LaTeX output: strictly follow template/ + rule/

All .tex are handwritten and generated by Python functions, the goal is to make the output and template/ the corresponding file invisually consistent: the same \toprule / \midrule / \bottomrule, the same \sym{} macro, the same column-header structure (&\multicolumn{1}{c}{(1)}…), the same table-note justifying paragraph.

6.1 Iron rules (from the two documents in rule/)

  1. No vertical lines (|), no additional \hlinein the coefficient area. Three-line table:\toprule / \midrule / \bottomrule one each (the \hline seen in template/ is a column-header separator, keep it as in the template).
  2. Control variables must display coefficients and t-values one by one,Prohibited "Controls: Yes/No" abbreviation.
  3. Variable order is fixed: core X → (interaction terms) → control variables → Constant (usually omitted).
  4. Inside parentheses are t-values(not standard errors), the first line of the table note is fixed as t statistics in parentheses(if changed to SE, change the table note accordingly).
  5. Significance symbolsfixed as *** p<0.01, ** p<0.05, * p<0.1, asterisks embedded in \sym{} macro.
  6. Numeric format: coefficient %.4f, t-value (%.2f), number of observations %,.0f,R² %.2f。
  7. Bottom fixed effects row:Firm FE / Year FE / Industry FE / State FE / Ind × Year FE / State × Year FE …, with explicit Yes/No notation (Firm FE and Industry FE are mutually exclusive when the firm dimension is included; choose according to the model).
  8. Clustering level matching: the clustering level for standard errors must match the level of variation of the core explanatory variable; state clearly in the table notes "robust t-statistics clustered by the firm / industry / state / ...". For U.S. firm panels the default is firm-clustered (Petersen 2009).
  9. Table notes (noindent + justifying paragraph) must be complete: sample scope (e.g., "U.S. Compustat non-financial, non-utility firms listed on NYSE/AMEX/NASDAQ from YYYY to YYYY"), dependent variable definition, core X definition, control variables listed one by one, FE combination, clustering level,cross-reference Table \ref{definition}, significance symbol explanation.
  10. Heterogeneity tablemust include \cmidrule(lr){i-j} grouping column headers, and add at the bottom of the table a p-value for Diff. (High-Low) row (bootstrap Fisher permutation test, reps=500).

6.2 Python rendering functions (skeleton)

def render_baseline_tex(models, labels_cols, var_order, var_labels,
                        fe_rows, nobs, r2, caption, label, note,
                        out_path):
    """
    按 template/baseline.tex 的结构写出 .tex。
    models: 列表,每个元素是 (coef_dict, t_dict, stars_dict);
            key 与 var_order 一致。
    fe_rows: [('Firm FE', ['Yes','Yes',...]), ('Year FE', [...]),
              ('Industry FE', [...]), ('State FE', [...])]
    """
    lines = [r'\begin{table}[htbp]\centering\scriptsize',
             r'\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}',
             rf'\caption{{\textbf{{{caption}}}}}',
             rf'\label{{{label}}}',
             '',
             rf'\noindent{{\justifying{{{note}\par}}}}',
             r'\bigskip',
             '',
             rf'\begin{{tabularx}}{{\textwidth}}{{l{"Y"*len(models)}@{{}}}}',
             r'\toprule', '']

    # 列序号行
    header1 = '                ' + ''.join([rf'&\multicolumn{{1}}{{c}}{{({i+1})}}'
                                            for i in range(len(models))]) + r'\\'
    lines.append(header1)
    # 可选:第二行列头(因变量名 / 分组名)
    if labels_cols:
        header2 = '                ' + ''.join([rf'&\multicolumn{{1}}{{c}}{{{c}}}'
                                                for c in labels_cols]) + r'\\'
        lines.append(header2)
    lines.append(r'\hline\\')

    # 系数与 t 值:每个变量两行
    for v in var_order:
        vlab = var_labels.get(v, v)
        coef_line = f'{vlab:<16}' + ''.join(
            [rf'& {fmt_coef(m[0][v], m[2][v]):>17}' for m in models]) + r'\\'
        t_line = ' ' * 16 + ''.join(
            [rf'& {fmt_t(m[1][v]):>17}' for m in models]) + r'\\'
        lines += [coef_line, t_line]

    lines.append(r'\hline')
    # Obs + FE 行 + Adj R²
    lines.append(f'Obs             ' + ''.join([rf'&{n:>10,}        ' for n in nobs]) + r'\\')
    for name, vals in fe_rows:
        lines.append(f'{name:<16}' + ''.join([rf'&{v:>10}        ' for v in vals]) + r'\\')
    lines.append(f'Adjusted $ R^2$ ' + ''.join([rf'&{r:>10.2f}        ' for r in r2]) + r'\\')
    lines += [r'\bottomrule', r'\end{tabularx}', r'\end{table}']

    with open(out_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(lines))

def fmt_coef(b, stars):
    s = {3:r'\sym{***}', 2:r'\sym{**}', 1:r'\sym{*}'}.get(stars, '')
    sign = '  ' if b >= 0 else ' '
    return f'{sign}{abs(b):>7.4f}{s}'  # 与 template/baseline.tex 的对齐一致

def fmt_t(t):
    return f'({t:>5.2f})'

render_sumstat_tex、render_iv_tex(including First Stage / Second Stage grouping column headers + \cmidrule, reporting KP rk Wald F, Anderson-Rubin CI),render_channel_tex(dependent variable row in the second-level column headers),render_heterogeneity_tex(including the p-value for Diff. row),render_psm_ddml_tex(Panel A + Panel B composite table),render_variables_tex(p{2.0cm}p{13.5cm} two-column definition table) are implemented one-to-one according to the corresponding files in template/.

6.3 Figure plotting (matplotlib)

Follow rule/回归表写作规范总结.docx Part Five figure specifications: white background, black frame, Times New Roman,.pdf + .png dual output.

  • Event study plot:errorbar(rcap 样式) + axhline(0) + axvline(基准期, linestyle='--'), with the base period defaulting to t-1
  • Specification curve: scatter of sorted coefficient values + variable-check matrix below (specification curve analysis)
  • Placebo distribution:hist + kde, true coefficient axvline(color='red')
  • Forest plot: horizontal errorbar, grouped by "firm / industry / state / macro", with one subplot per group
  • PSM balance: scatter or bar chart of |% standardized bias| before/after matching
  • Binscatter:seaborn.regplot or hand-coded residualization followed by binning, with navy scatter points and maroon fitted line (Cattaneo et al. 2023)

6.4 main.tex assembly rules (placed in theproject root, with the header copied from template/main.tex)

main.tex located in the {项目名}/ root directory (not placed in the paper/ subdirectory), with all table/figure paths written uniformly as results/xxx.tex or results/xxx.pdf(relative paths, no need for ../)。

6.4.1 Header (preamble / titlepage / abstract)

  • Copy verbatim the template/main.tex settings in lines 1–85 of documentclass、usepackage、titleformat、newcolumntype、titlepage / \maketitle、abstract、baselinestretch ;
  • replace only the paper title, authors, affiliations, JEL, keywords, and abstract body;
  • According to the 00_proposal.md field in the YAML block at the top of bibliography_style (see §3.4.3), replace \bibliographystyle{jfe} with the bib style corresponding to the target journal(jf / jfe / rfs / jar / jae / aer / informs / elsarticle-num / jibs / …, see §3.4.4);
  • The Section skeleton is rendered according to the target journal's section_skeleton list(e.g., JF uses "The Setting / Hypotheses", JAR uses "Hypothesis / Sample and Data / Research Design", AER must include "External Validity", MS must include "Discussion" and managerial implication in the final paragraph);
  • Other macro packages, page geometry, hyperlink colors,\newcolumntype{Y}、\renewcommand\Authands , etc.must not be modified。

6.4.2 Body structure (generate only Section / Subsection titles,leave the body empty)

Iron rule:

  • Do not generate any narrative .tex sub-files(do not introduction.tex / background.tex / data.tex / results.tex …). All narrative prose must not be written; leave it for the researcher to fill in.
  • main.tex The body area only outputs the \section{...} and \subsection{...} title skeleton; the body between titles iscompletely blank(optionally add one line of placeholder comment % TODO: prose, but do not write any sentences, do not write boilerplate like "In this section we …").
  • \input{results/xxx} and \includegraphics{results/xxx.pdf} suchintroduction commands for empirical productsappear as usual at the positions in §6.4.3 / §6.4.4, because what they introduce are tables/figures automatically generated by the skill, not narrative prose.
  • Section/Subsection title text is rendered according to the target journal section_skeleton (see §3.4.4); the subsection list below is the "general minimal skeleton" for each journal; if the target journal has different preferences, adjust according to §3.4.4.

General skeleton (using JFE as an example; for other journals replace the top-level section names according to §3.4.4):

%==============================================================
%  正文(仅标题,内容留空)
%==============================================================

\section{Introduction}\label{sec:intro}
% TODO: prose

\section{Background}\label{sec:bg}
  \subsection{Institutional Setting}
  % TODO: prose
  \subsection{Related Literature}
  % TODO: prose

\section{Hypothesis Development}\label{sec:hyp}
  \subsection{Main Hypothesis}
  % TODO: prose
  \subsection{Mechanism Hypotheses}
  % TODO: prose

\section{Data and Sample}\label{sec:data}
  \subsection{Data Sources}
  % TODO: prose
  \subsection{Sample Construction}
  % TODO: prose
  \subsection{Variable Definitions}
  % TODO: prose(变量定义表在附录 \ref{tab:variables})
  \subsection{Summary Statistics}
  % TODO: prose(表 \ref{tab:sumstat})

\section{Empirical Strategy}\label{sec:strategy}
  \subsection{Identification}
  % TODO: prose
  \subsection{Baseline Specification}
  % TODO: prose
  \subsection{Parallel Trends}  % DID 项目才保留
  % TODO: prose(图 \ref{fig:dynamic})

\section{Empirical Results}\label{sec:results}
  \subsection{Baseline Results}
  % TODO: prose(表 \ref{tab:baseline})
  \subsection{Addressing Endogeneity}
  % TODO: prose(表 \ref{tab:iv}、\ref{tab:psm_ddml})
  \subsection{Heterogeneity}
  % TODO: prose(表 \ref{tab:het1}–\ref{tab:het3})
  \subsection{Mechanism}
  % TODO: prose(表 \ref{tab:ch1}–\ref{tab:ch3})
  \subsection{Further Analysis}
  % TODO: prose(表 \ref{tab:further})

\section{Conclusion}\label{sec:conclude}
% TODO: prose

Differences triggered by the target journal(at render time, replace top-level section names + necessary subsections according to the table in §3.4.4):

Target journal Top-level section and additional subsection requirements
JF "The Setting" replaces Background; Hypotheses becomes a separate section; Mechanism becomes a separate subsection within Results
JFE Example above (Background → Data → Empirical Strategy → Results → Robustness → Conclusion)
RFS "Theoretical Motivation" as a separate section, placed after Background and before Data
JAR / JAE "Hypothesis" as a separate section (in §2, independent of Background); "Research Design" replaces Empirical Strategy
TAR Same as JAR
AER Add at the end \section{External Validity} before Conclusion
MS \section{Discussion} between Results and Conclusion, containing \subsection{Managerial Implications}
JIBS \section{Theory and Hypotheses} replaces Background + Hypothesis Development; add at the end \subsection{Contribution to International Business}
JCF / JBF / JPubE / JEEM Same as the general JFE skeleton

When render_main_tex writes out the title skeleton,it is strictly forbiddento generate any prose sentences; any sentence beginning like "This paper studies …", "We document …", "Section 2 describes …", "In this section …" is a violation. Only % TODO: prose one line of placeholder comment is allowed.

6.4.3 After the references: first figures, then tables, finally appendix (strict order)

After the body \section{Conclusion} , write in sequence:

\bibliographystyle{jfe}
\bibliography{ref}

%%%%% Figures(主体图:平行趋势 + 估计量对比)%%%%%%%%
\clearpage
\begin{figure}[ht]\begin{center}
  \includegraphics[width=0.9\linewidth]{results/parallel.pdf}
  \caption{\textbf{Dynamic Treatment Effect}}\label{dynamic}
\end{center}\end{figure}

\clearpage
\begin{figure}[ht]\begin{center}
  \includegraphics[width=0.9\linewidth]{results/estimator.pdf}
  \caption{\textbf{DID Estimator Comparison}}\label{estimator}
\end{center}\end{figure}

%%%%% Tables(主体表:descriptive → baseline → endogeneity → heterogeneity → mechanism → further)%%%%%%%%
\clearpage \input{results/sum_stat}       % 描述性统计
\clearpage \input{results/baseline}       % 基准回归
%% 内生性处理紧跟 baseline:
\clearpage \input{results/iv}             % 2SLS / IV
\clearpage \input{results/psm_ddml}       % PSM-DID (Panel A) + DML (Panel B)
%% 异质性在机制之前:
\clearpage \input{results/heterogeneity1}
\clearpage \input{results/heterogeneity2}
\clearpage \input{results/heterogeneity3}
%% 机制分析:
\clearpage \input{results/channel1}
\clearpage \input{results/channel2}
\clearpage \input{results/channel3}
%% 进一步分析:
\clearpage \input{results/further}

6.4.4 Appendix — robustness + variable definitions + sample construction + appendix figures

\appendix At the start of \setcounter{table}{0}、\setcounter{figure}{0}、\renewcommand{\thetable}{S\arabic{table}}、\renewcommand{\thefigure}{S\arabic{figure}} must be preserved (appendix tables/figures are numbered independently as S1, S2, …, consistent with template/main.tex lines 660–665).

Appendix content order:

\clearpage
\setcounter{table}{0}
\setcounter{figure}{0}
\renewcommand{\thetable}{S\arabic{table}}
\renewcommand{\thefigure}{S\arabic{figure}}
\appendix

\begin{large}\begin{center}
\bf {论文题目} \\ Online Appendix
\end{center}\end{large}

%% 附录图(PSM 平衡、CS-DID 事件研究、规格曲线、安慰剂分布)
\clearpage
\begin{figure}[ht]\begin{center}
  \includegraphics[width=0.9\linewidth]{results/psm-pre-post.pdf}
  \caption{\textbf{Kernel Density of Propensity Scores}}\label{kernel-psm}
\end{center}\end{figure}

\clearpage
\begin{figure}[ht]\begin{center}
  \includegraphics[width=0.9\linewidth]{results/csdid-figure.pdf}
  \caption{\textbf{Callaway-Sant'Anna Event Study}}\label{csdid}
\end{center}\end{figure}

\clearpage
\begin{figure}[ht]\begin{center}
  \includegraphics[width=0.9\linewidth]{results/placebo.pdf}
  \caption{\textbf{Placebo Test}}\label{placebo}
\end{center}\end{figure}

\clearpage
\begin{figure}[ht]\begin{center}
  \includegraphics[width=0.8\linewidth]{results/specurve.pdf}
  \caption{\textbf{Specification Curve}}\label{specurve}
\end{center}\end{figure}

%% 附录表(**必含**:变量定义 + 样本构造/分布;以及稳健性四件套)
\clearpage \input{results/variables}            % 变量定义表(必做)
\clearpage \input{results/sample_construction}  % 样本构造/分布表(必做)
%% 稳健性表格全部进附录:
\clearpage \input{results/measures}             % 替换度量
\clearpage \input{results/sampling}             % 样本筛选
\clearpage \input{results/specification}        % 高维交互 FE
\clearpage \input{results/addctr}               % 追加控制变量
\clearpage \input{results/bunching-did}         % Bunching-DID(若适用)

%% (可选)理论推导附录——参照 template/main.tex 第 716 行后
%% \section*{Appendix: Theoretical Derivations} ...

\end{document}

6.4.5 render_main_tex Skeleton (auto-generated by Python) main.tex)

def render_main_tex(title, authors, affils, abstract, jel, keywords,
                    target_journal, bibliography_style, section_skeleton,
                    main_figures, main_tables, appendix_figures, appendix_tables,
                    out_path='main.tex', template='template/main.tex'):
    """
    读取 template/main.tex,切出 [preamble][title/abstract block][正文标题骨架]
    [bibliography][figures][tables][appendix-figs][appendix-tabs] 八段,
    将:
      - 标题/作者/单位/abstract/JEL/keywords 替换为本项目内容
      - 根据 target_journal / bibliography_style 替换 \bibliographystyle{...}
      - 根据 section_skeleton(从 00_proposal.md YAML 读出)渲染 §6.4.2 的
        【仅标题、正文留空】骨架;section/subsection 之间只放
        一行 `% TODO: prose` 占位注释,**绝对不生成任何 prose 句子**
      - **不生成任何叙述性 .tex 子文件**(不要 introduction.tex / background.tex …)
      - main_figures = ['results/parallel.pdf', 'results/estimator.pdf']
      - main_tables  = ['results/sum_stat', 'results/baseline', 'results/iv',
                        'results/psm_ddml', 'results/heterogeneity1', ...,
                        'results/channel1', ..., 'results/further']
      - appendix_figures = ['results/psm-pre-post.pdf','results/csdid-figure.pdf',
                            'results/placebo.pdf','results/specurve.pdf']
      - appendix_tables  = ['results/variables','results/sample_construction',
                            'results/measures','results/sampling',
                            'results/specification','results/addctr',
                            'results/bunching-did']
    按 6.4.2 / 6.4.3 / 6.4.4 的严格顺序组装 main.tex,写入项目根目录。
    """
    ...

List of prohibited behaviors during rendering(render_main_tex must self-check):

Violation Correct practice
After \section{Introduction} , write any sentence Only write % TODO: prose one line
Create results/introduction.tex and other narrative subfiles Do not create; leave the body empty
Write "In this section we …"/"This paper …"/"Section 2 describes …" All prohibited
Use \input{prose/xxx} to introduce narrative Prohibited; prose can only be written directly into main.tex by the researcher
Automatically fill in abstract content The abstract is written by the researcher; render only copies the passed-in abstract string (may be empty)

6.4.6 References

  • \bibliographystyle{jfe}(Journal of Financial Economics style, template default)
  • \bibliography{ref} → project root's ref.bib
  • If the researcher does not provide ref.bib, the skill provides an empty file and in the main.tex body \citep{} lists the literature keywords that need to be added, to be completed by the researcher

6.4.7 render_sample_construction_tex(required for the appendix)

Add a new Python rendering function that outputs results/sample_construction.tex, a two-column or three-column table, with example content:

                                                                    Obs.
----------------------------------------------------------------------
Initial Compustat-CRSP merged sample, YYYY-YYYY               XXX,XXX
Less: Financial firms (SIC 6000-6999)                         -XX,XXX
Less: Utilities (SIC 4900-4949)                                -X,XXX
Less: Non-common stock (CRSP share code ≠ 10, 11)              -X,XXX
Less: ADRs / dual-class / SPACs                                -X,XXX
Less: Firm-years with total assets < $10M                      -X,XXX
Less: Firms missing CCM link (LINKTYPE not in LU/LC)           -X,XXX
Less: Observations with missing controls                       -X,XXX
Final analysis sample                                         XXX,XXX
----------------------------------------------------------------------

Panel B. Industry distribution (Fama-French 48)
Panel C. Year distribution
Panel D. Country distribution   (仅跨国样本)

Format imitates template/variables.tex 's p{...cm}p{...cm} two-column definition table shell + \toprule/\midrule/\bottomrule, and the table note states the source and rationale of the sample screening.

7. Data Sources and Retrieval Process (researcher input-driven)

7.1 Data source hierarchy (priority from high to low)

asset/ is not the only source, but the "preferred" source. When asset/ no suitable entry can be found, expand the retrieval scope in the following order:

Level Source Positioning Typical data
L1 asset/ local inventory Preferred WRDS main databases (CRSP / Compustat / IBES / BoardEx / 13F / Dealscan / Audit Analytics / ExecuComp / RavenPack / Patent DB), NBER/Fed/BLS/BEA releases, registered policy shock databases
L2 asset/MCP.docx registered MCP servers First choice as a supplement when asset/ is missing Macro panels, cross-country panels, trade / supply chain
L3 Other public external sources Considered only when neither asset/ nor MCP is available Official websites of central banks / statistical bureaus / securities regulators of various countries, Kenneth French Library, Global Financial Data, Refinitiv, Bloomberg (if the researcher subscribes), public GitHub replication packages, data on paper authors' homepages
L4 Researcher-constructed Only when none of L1-L3 is available Manual extraction from annual reports, text crawling, manual coding by RA

Principle: Find the top 5 candidates in L1 and return them to the researcher; if the researcher judges them insufficient, jump to L2 and call MCP; if still insufficient, go to L3/L4.Do not skip L1 and go directly to L3, unless the researcher explicitly names a certain external source.

7.2 MCP servers (asset/MCP.docx)

asset/MCP.docx The MCP (Model Context Protocol) servers registered in official supplementary sources beyond the asset/ local inventory. Currently four are registered:

MCP server Purpose Installation/usage entry point
IMF Data MCP IMF WEO / IFS / DOT / BOP macro panels (country GDP / inflation / exchange rates / balance of payments / policy rates) https://github.com/c-cf/imf-data-mcp
World Bank Data MCP WDI / WGI / Doing Business / Enterprise Surveys (cross-country institutional quality, financial depth, business environment) https://github.com/llnormll/world-bank-data-mcp
Supply Chain MCP Global supply chain data (tariffs, ports, shipping, trade flows, inventories) https://mcpmarket.com/zh/server/supply-chain
OECD MCP OECD STAN / PDB / SDBS / PMR (industry panels, productivity, regulatory intensity, corporate tax rates) https://github.com/isakskogstad/OECD-MCP

Installation and Usage: Follow the installation commands in each MCP repository's README one by one (usually npx -y ... or uvx ... Connect to Claude Code's .mcp.json)。Credentials and API keys are configured locally by the researcher, and the skill does not store any token.

How to call in research: After MCP is enabled, the skill calls directly through the corresponding MCP tools (e.g., mcp__imf__get_series、mcp__world-bank__query_wdi , etc.) to pull data; after pulling, it is uniformly written to disk at {项目名}/data/raw/, and the subsequent cleaning process remains unchanged.

Path determination before querying:

研究者关键词
   │
   ▼
asset/ 本地清单(nber/macrodatas/ppmandata/WRDS overview)命中?
   ├── 是 → 返回 top 5,交研究者选定(L1)
   └── 否 → 检查关键词主题:
              ├── 跨国宏观 / 主权 / 汇率 / 国际收支 → IMF MCP
              ├── 制度 / 发展 / 营商环境 / 金融深度 → World Bank MCP
              ├── 关税 / 贸易流 / 供应链 / 航运  → Supply Chain MCP
              ├── OECD 成员国产业 / 监管 / 税率  → OECD MCP
              └── 均不匹配 → 走 L3 外部源(让研究者点名)

7.3 Retrieval function (L1 local inventory)

Do not actively scan the entire asset/ table, to avoid input token explosion. Correct process:

  1. Have the researcher state the needed datakeywords(e.g., "CRSP", "Compustat", "IBES", "BoardEx", "13F", "Dealscan", "USPTO patents", "SOX compliance", "Dodd-Frank", "Brexit", "China Shock", "TCJA", "state corporate tax", "FOMC shocks"...) or policy name.
  2. Use Grep / pandas in asset/nber_releases_list.csv、asset/macrodatas_list.csv、asset/ppmandata_trade_list.csv to search the title / data_source / keyword / data_intro / data_indicators columns by keyword; at the same time, in asset/wrds_research_data_overview.pdf locate the corresponding WRDS library.
  3. Return the top 5 candidates, showing title、data_source、data_indicators(first 200 characters) and the download / access URL; after the researcher selects, they download / authorize use (WRDS subscription credentials are kept by the researcher).
  4. If there is no hit in L1 or the researcher considers the candidates unsuitable → follow §7.1 / §7.2 to try MCP → L3 external sources → L4 self-construction in sequence.
def search_asset(keyword, top=5):
    """L1:本地 asset/ 清单检索。"""
    results = []
    for csv in ['asset/nber_releases_list.csv',
                'asset/macrodatas_list.csv',
                'asset/ppmandata_trade_list.csv']:
        try:
            df = pd.read_csv(csv, encoding='utf-8')
        except UnicodeDecodeError:
            df = pd.read_csv(csv, encoding='utf-8-sig')
        hit = df[df.apply(lambda r: keyword.lower() in str(r.to_dict()).lower(), axis=1)]
        if len(hit):
            results.append(hit.head(top).assign(source=csv))
    if not results:
        return pd.DataFrame()
    return pd.concat(results, ignore_index=True)

def route_to_mcp(keyword):
    """L2:根据关键词建议应调用哪个 MCP(asset/MCP.docx 登记)。"""
    kw = keyword.lower()
    routes = [
        (['gdp','inflation','exchange','bop','sovereign','policy rate','imf'],
         'IMF Data MCP',         'https://github.com/c-cf/imf-data-mcp'),
        (['wdi','wgi','governance','doing business','financial depth','enterprise survey'],
         'World Bank Data MCP',  'https://github.com/llnormll/world-bank-data-mcp'),
        (['tariff','trade flow','supply chain','shipping','port','inventory'],
         'Supply Chain MCP',     'https://mcpmarket.com/zh/server/supply-chain'),
        (['oecd','stan','regulation','productivity','corporate tax rate','pmr'],
         'OECD MCP',             'https://github.com/isakskogstad/OECD-MCP'),
    ]
    for kws, name, url in routes:
        if any(k in kw for k in kws):
            return {'mcp': name, 'install_url': url}
    return None  # 走 L3 / L4

7.4 Data provenance registration (reproducibility requirement)

Every piece of data that lands in data/raw/ must be registered in {项目名}/data/raw/SOURCES.md :

| 文件 | 来源层级 | 原始出处 | 拉取时间 | 备注 |
|---|---|---|---|---|
| compustat_funda_2000_2023.parquet | L1 | WRDS Compustat Fundamentals Annual | 2026-04-23 | 已应用 consol='C', popsrc='D', indfmt='INDL' |
| wb_wgi_2000_2023.csv            | L2 | World Bank Data MCP → WGI | 2026-04-23 | 通过 mcp__world-bank__query_wdi 拉取 |
| sox_accelerated_filer.csv       | L4 | 研究者手工整理自 SEC Release 33-8128 | 2026-04-20 | RA: XXX,双人复核 |

8. Common pitfalls in foreign corporate finance research (must-check)

Pitfall Practice
Sample does not exclude financial industry (SIC 6000-6999) and utilities (SIC 4900-4949) Exclude by default (unless the research subject is exactly these two industries)
Common stock CRSP share code 10 / 11 not restricted Keep only 10/11 by default (exclude ADR, REIT, ETF, closed-end fund, SPAC)
CRSP-Compustat Merged matching omissions Use the CCM link table (LINKTYPE in ('LU','LC') and LINKPRIM in ('P','C'))
Extreme values in continuous variables 1% / 99% winsorization, state in table notes; financial ratios additionally handle ±inf / nan
Industry classification standard Prefer Fama-French 48 (FF48); in robustness replace with SIC 2-digit / NAICS 3-digit / FF12
U.S. state-level merger changes Note missing data for West Virginia / Alaska; use FIPS for state codes
Clustering level Company panels default to firm (Petersen 2009); state policies default to state; for cross-period correlation use firm + year two-way (Thompson 2011)
staggered DID Must be cross-validated with CS-DID or Sun-Abraham or Stacked DID to avoid TWFE negative weights (Goodman-Bacon 2021)
Policy timing: announce vs effective Distinguish, and substitute in robustness; e.g., SOX split into accelerated (2004) / non-accelerated (2007) filers
Contemporaneous policy confounding Search the asset/NBER policy list, and add dummy controls for contemporaneous policies in the baseline regression (e.g., SOX × Reg FD)
Crisis / pandemic sample contamination Exclude the 2008-2009 (GFC) and 2020-2021 (COVID) periods in robustness
Handling missing M&A / delisting CRSP delisting return adjustment; Compustat delisting / privatization / bankruptcy flag dlrsn
Reverse causality Lag the explanatory variable by 1 period, use pre-determined controls, Granger test
US dollar inflation Deflate continuous variables (assets, investment amounts) to constant-year dollars using CPI / GDP deflator

9. Output project directory (automatically suggested when running the skill)

After the nine CONTRACT fields are confirmed, automatically generate the following skeleton (all Python scripts pre-embed calls to the template/ reference render_*_tex ):

{项目名}/
├── 00_proposal.md                          # 计划书固化版(CONTRACT 九字段)
├── DECISION_LOG.md                         # Plan-B 切换记录(3.A.3)
├── main.tex                                # 论文正文(项目根;头部照搬 template/main.tex;
│                                           #   先图后表,稳健性放附录;见 §6.4)
├── ref.bib                                 # 参考文献(bibliographystyle=jfe)
├── data/raw/                               # 研究者放入原始数据(WRDS 导出 / 第三方)
├── data/cleaned/sample.parquet             # 清洗后样本
├── code/
│   ├── 00_config.py                        # 全局变量(样本年份、控制变量列表、FE 配置)
│   ├── 01_clean.py                         # CRSP × Compustat × IBES × BoardEx 对齐
│   ├── 02_sumstat.py                       # → results/sum_stat.tex + variables.tex
│   │                                       #   + results/sample_construction.tex(附录必含)
│   ├── 03_parallel.py                      # → results/parallel.pdf   [DID 专用]
│   ├── 03b_csdid.py                        # → results/csdid-figure.pdf + estimator.pdf
│   ├── 04_baseline.py                      # → results/baseline.tex
│   ├── 05_iv.py                            # → results/iv.tex                【紧跟 baseline】
│   ├── 05b_dml.py                          # → results/psm_ddml.tex Panel B  【紧跟 baseline】
│   ├── 06_measures.py                      # → results/measures.tex          【稳健性,入附录】
│   ├── 07_hetero.py                        # → results/heterogeneity{1,2,3}.tex 【异质性先于机制】
│   ├── 08_channel.py                       # → results/channel{1,2,3}.tex
│   ├── 09_robust.py                        # → results/{addctr,specification,sampling,bunching-did}.tex
│   │                                       #   【全部入附录】
│   ├── 10_psm.py                           # → results/psm_ddml.tex Panel A + results/psm-pre-post.pdf
│   ├── 11_placebo.py                       # → results/placebo.pdf            【入附录】
│   ├── 12_further.py                       # → results/further.tex (+ results/specurve.pdf)
│   └── 99_assemble_main.py                 # 调用 render_main_tex():生成项目根 main.tex
└── results/                                # 最终交付物:.tex 表格 + .pdf/.png 图像 全部放此处
                                            # 不再区分 tables/ 与 figures/ 子目录

Final deliverables (only three categories):

  1. Python code:code/ All .py scripts under the directory, which can run from raw data in one click through to all tables and figures + assembly main.tex。
  2. Figures and tables:results/ The .texunder (LaTeX tables, conforming to the template/ format) + .pdf and .png(two exported copies of the images).Tables and images are placed uniformly in results/, without creating a separate tables/ figures/ directory。
  3. Paper main text: the project root's main.tex(+ ref.bib), with a structure consistent with template/main.tex ; concatenate the figures/tables in results/ in the order of §6.4.

Do not deliver Word / Markdown reports; do not deliver Stata .do files; do not deliver intermediate datasets.

10. AI code of conduct under this skill

  1. Proposal-driven: Do not start without a proposal; the proposal is the contract. When encountering any judgment fork during execution, first check back 00_proposal.md。 1.1 Journal positioning first(§3.3 step 2, §3.4): after parsing the proposal,immediatelyrecommend the 5 best-matching target journals ([J1]–[J5]) and explicitly ask the researcher to choose;before receiving the choice, do not jump to data retrieval, skeleton generation, or any §4 mainline step. After the researcher chooses, you must write target_journal / bibliography_style / section_skeleton into the YAML at the top of 00_proposal.md , and carry it through subsequent main.tex and all render_*_tex() calls.
  2. Autonomous closed loop, no stalling: When results fall short of expectations, follow the Plan-B decision tree in Section 3.Ato switch autonomously and continue execution, without stopping to wait for the researcher to decide. Record every switch DECISION_LOG.md。
  3. Small steps, fast iteration: complete only one step of the research chain at a time; after completing it, show the .tex abstract (first 10 lines + last 10 lines) and its comparison against the proposal expectations (✅/⚠️/❌), then proceed to the next step.
  4. Format consistency check: before writing each .tex file, first Read the corresponding template/*.tex, compare the number of columns, column headers, FE row, and Notes paragraph, then render.
  5. Do not change the rules without authorization:rule/ 's rules are mandatory; if the researcher requests a deviation, the researcher must provide an explicit written statement (e.g., reviewer requests changing reported standard errors / switching to Driscoll-Kraay SE).
  6. Do not run Stata: all regressions, PSM, DML, CS-DID, Stacked DID, and bdiff are implemented in Python.rule/ 's Stata code serves only as an "output format reference".
  7. Protect the working directory:asset/ rule/ template/ : the three folders are read-only; do not write to, modify, or rename them. All research outputs go only into the {项目名}/ subdirectory.
  8. Self-check after generating tables: check item by item against rule/回归表写作规范总结.docx Part 9's "AI writing checklist" (three-line table, all control variables displayed, t-values in parentheses,\sym{} asterisks, FE row, clustering level, complete table notes).
  9. Deliver only code and figures/tables: the final deliverables are limited to code/*.py + results/*.tex + results/*.pdf|png(tables and figures both in results/); do not produce additional reports, abstracts, PPTs, or Word documents. 9.1 Do not write any narrative prose(§6.4.2 / §6.4.5):main.tex : the main text area only renders \section{...} and \subsection{...} heading skeleton + % TODO: prose one-line placeholder;forbiddento generate introduction.tex / background.tex and other narrative subfiles;forbiddento write boilerplate such as "In this section we …"/"This paper …"/"Section 2 describes …". The same applies to the Abstract: unless the researcher explicitly provides abstract text, keep it blank. Narrative prose is to be filled in by the researcher themselves.
  10. All-English expression: for foreign-sample studies, variable names, table titles, column headers, FE rows, and table notes (\noindent{\justifying{...}})must all be in English; avoid mixing Chinese and English. Comments inside the code may use Chinese to facilitate the researcher's understanding.
  11. Credential security: WRDS / FRED / Bloomberg / S&P Capital IQ account names, API keys, and tokens must not be written into any file or log; they are only read in code/00_config.py via os.environ[...] , set by the researcher themselves in the local .env .

11. Startup example

Minimal proposal (text form)

Research Proposal Title: Sarbanes-Oxley Act and Corporate Investment Efficiency Hypothesis: The internal control disclosure requirement of SOX Section 404 (X = SOX404 compliance) improves investment efficiency (Y), measured as lower deviation from the predicted level of investment. Expected findings: X reduces |investment deviation| significantly (p<0.05); channel is "reduced information asymmetry → better project selection"; heterogeneity is stronger for firms with (i) higher pre-SOX agency cost, (ii) less analyst coverage, (iii) weaker external governance. Identification: Staggered DID exploiting accelerated-filer (2004) vs non-accelerated- filer (2007) compliance deadlines. Backed up by Sun-Abraham & Stacked DID. Sample: U.S. non-financial, non-utility Compustat firms, 2000-2010, NYSE/AMEX/NASDAQ common stock (share code 10/11); exclude firms with assets < $10M. Shock: SOX Section 404 compliance; treatment = firms that cross accelerated-filer threshold ($75M public float) in year $t$. Data: WRDS CRSP + Compustat + Audit Analytics (internal control opinion) + IBES (analyst coverage). Keywords: "SOX", "internal control", "accelerated filer". Mechanism: M1 = information asymmetry (bid-ask spread, analyst forecast dispersion); M2 = governance quality (G-index, board independence); M3 = external financing cost (bond spread, Dealscan loan spread). Heterogeneity: pre-SOX G-index (tertile); analyst coverage (above/below median); institutional ownership (tertile).

After submission, the skill immediately:

  1. Generates SOX_Investment_Efficiency/00_proposal.md(solidifying the nine CONTRACT fields)
  2. Searches asset/ and returns candidate datasets (WRDS Audit Analytics / Compustat fundamentals annual / IBES Summary), then waits for the researcher to select and authorize
  3. Executes along the main line in Section 4; if the baseline X coefficient direction is reversed or the parallel trends test fails, automatically enters the corresponding Plan-B branch in 3.A.2
  4. Final deliverables:code/ full set of Python + results/*.tex full set of tables + results/*.pdf|png full set of figures (tables and figures both in results/) + project root main.tex + ref.bib + DECISION_LOG.md traceability record