Automate a finance paper in Claude Code with a kit you can copy and paste
One pasted request sets up the pipeline and one typed goal runs it, from literature search to a drafted paper. A referee file the agent cannot edit rejects invented references and typed-in numbers.
Nine steps for a first-time user
-
Install Claude Code. Open a terminal and paste this line. You need a Claude subscription or an Anthropic Console account.
curl -fsSL https://claude.ai/install.sh | bash -
Make the project folder.
mkdir finance-paper && cd finance-paper git init printf 'data/\n.env\n__pycache__/\n' > .gitignore -
Put your details in a file named
.env. The data providers ask who is calling. The last line is optional.CONTACT_NAME=Your Name CONTACT_EMAIL=you@university.edu S2_API_KEY= -
Start Claude Code. Type
claudeand press Enter. -
Choose Opus 5.5 and raise the effort.
/model opus /effort high -
Check that auto mode is on. The bottom of the window should say “auto mode on”. If it does not, press Shift+Tab until it does.
-
Paste the setup request.
Read https://aifinresearch.com/guides/automate-a-finance-paper.md and https://aifinresearch.com/guides/sec-filings-with-an-agent.md. Create every file in the first guide exactly as given, at the path shown above each one. Take sec.py from the second guide and make it read CONTACT_NAME and CONTACT_EMAIL from .env for its User-Agent header. Install requests, pandas, pyarrow, pytest and statsmodels. Do not read or print .env. Commit, then stop and list the files. -
Type the goal.
/goal paper/main.tex answers the question in config/question.md. Run the literature, data, estimate, write and referee skills in that order. Prove it by running pytest and showing that it exits 0, then show that git status is clean. Do not edit tests/ or config/. Stop after 60 turns. -
Leave it. To change the question, edit
config/question.mdbefore step 8.
> /goal paper/main.tex answers the question in config/question.md ... ● Skill(literature) ● Bash(python lit.py search "asset growth profitability") ⎿ 40 candidates ● Bash(python lit.py verify paper/refs.bib) ⎿ 1 of 14 references failed: title does not match the registered record ● Removing that reference and the sentence that cited it. ● Bash(pytest -q) ⎿ 1 failed: test_no_number_is_typed_by_hand ◎ Goal not yet met: pytest did not exit 0. ● Edit(paper/main.tex) ● Bash(pytest -q) ⎿ 7 passed
The pipeline has five stages
| Stage | The skill does | It leaves behind |
|---|---|---|
| Literature | Searches OpenAlex and arXiv, picks what bears on the question, checks every reference against Crossref | paper/refs.bib, lit/verified.json |
| Data | Pulls SEC filings data for the sample and builds a firm-year panel | data/panel.parquet |
| Estimate | Logs each specification before running it, picks one on the early years, then runs it once on the held-out years | results/specs.jsonl, results/numbers.json |
| Write | Drafts the paper with every number as a macro | paper/main.tex, paper/numbers.tex |
| Referee | Runs the tests, reads the draft as a referee would and fixes what code can fix | paper/referee.md |
The referee: tests/test_paper.py
# tests/test_paper.py: the referee. The agent may not edit this file.
import json
import re
from pathlib import Path
import pandas as pd
TEX = Path("paper/main.tex").read_text()
BIB = Path("paper/refs.bib").read_text()
NUMBERS = json.loads(Path("results/numbers.json").read_text())
SPECS = [json.loads(line) for line in Path("results/specs.jsonl").read_text().splitlines() if line.strip()]
VERIFIED = {r["key"]: r for r in json.loads(Path("lit/verified.json").read_text())}
BIB_KEYS = set(re.findall(r"@\w+\{([^,]+),", BIB))
def test_every_citation_is_in_the_bibliography():
cited = {key.strip() for group in re.findall(r"\\cite[tp]?\{([^}]+)\}", TEX) for key in group.split(",")}
assert cited and cited <= BIB_KEYS
def test_every_reference_resolves_at_crossref():
assert BIB_KEYS == set(VERIFIED)
assert all(r["ok"] for r in VERIFIED.values()), [k for k, r in VERIFIED.items() if not r["ok"]]
def test_every_number_comes_from_the_results_file():
used = set(re.findall(r"\\res\{([^}]+)\}", TEX))
assert used and used <= set(NUMBERS)
def test_no_number_is_typed_by_hand():
body = TEX.split(r"\begin{document}")[1]
body = re.sub(r"\\(res|cite[tp]?|ref|label|input|includegraphics)(\[[^\]]*\])?\{[^}]*\}", "", body)
typed = re.findall(r"(?<![\w.])\d+\.\d+(?![\w.])", body)
assert not typed, typed[:5]
def test_every_specification_is_logged_and_counted():
assert len(SPECS) >= 1
assert NUMBERS["n_specs"] == len(SPECS)
assert r"\res{n_specs}" in TEX
def test_the_main_result_is_reported_in_and_out_of_sample():
assert {"main_coef_insample", "main_t_insample", "main_coef_holdout", "main_t_holdout"} <= set(NUMBERS)
def test_panel_has_one_row_per_firm_year():
panel = pd.read_parquet("data/panel.parquet")
assert not panel.duplicated(["cik", "fiscal_year"]).any()
assert (panel["filing_date"] >= panel["period_end"]).all()
| Test | The failure it catches |
|---|---|
| Every citation is in the bibliography | A citation to a key that does not exist |
| Every reference resolves at Crossref | An invented paper, or a real DOI under a made-up title |
| Every number comes from the results file | A statistic with no code behind it |
| No number is typed by hand | A coefficient written into the prose |
| Every specification is logged and counted | A search over specifications that the paper hides |
| The main result is reported in and out of sample | A result that only holds on the years it was tuned on |
| One row per firm-year | Duplicates, and values dated before they were filed |
Literature search and reference check: lit.py
# lit.py: search the literature and verify every reference against Crossref.
import json
import os
import re
import sys
import time
import xml.etree.ElementTree as ET
from pathlib import Path
import requests
# Read .env so the keys never have to be typed into a prompt.
if Path(".env").exists():
for line in Path(".env").read_text().splitlines():
if "=" in line and not line.lstrip().startswith("#"):
name, value = line.split("=", 1)
os.environ.setdefault(name.strip(), value.split("#")[0].strip())
EMAIL = os.environ.get("CONTACT_EMAIL", "")
S2_KEY = os.environ.get("S2_API_KEY", "")
UA = {"User-Agent": f"finance-paper-kit (mailto:{EMAIL})"}
def openalex(query: str, n: int = 20) -> list[dict]:
"""Published work, most relevant first. No key needed for light use."""
r = requests.get(
"https://api.openalex.org/works",
params={"search": query, "per_page": min(n, 100)},
headers=UA,
timeout=30,
)
r.raise_for_status()
return [
{
"title": w["title"],
"year": w["publication_year"],
"doi": (w.get("doi") or "").replace("https://doi.org/", ""),
"cited_by": w["cited_by_count"],
"source": "openalex",
}
for w in r.json()["results"]
]
def arxiv(query: str, n: int = 20) -> list[dict]:
"""Working papers. arXiv asks for a three second pause between calls."""
time.sleep(3)
r = requests.get(
"http://export.arxiv.org/api/query",
params={"search_query": f"all:{query}", "max_results": n, "sortBy": "relevance"},
headers=UA,
timeout=30,
)
r.raise_for_status()
ns = {"a": "http://www.w3.org/2005/Atom"}
return [
{
"title": " ".join(e.find("a:title", ns).text.split()),
"year": int(e.find("a:published", ns).text[:4]),
"arxiv": e.find("a:id", ns).text.rsplit("/", 1)[-1],
"source": "arxiv",
}
for e in ET.fromstring(r.text).findall("a:entry", ns)
]
def semantic_scholar(query: str, n: int = 20) -> list[dict]:
"""Optional. Runs only when S2_API_KEY is set, at one request a second."""
if not S2_KEY:
return []
time.sleep(1)
r = requests.get(
"https://api.semanticscholar.org/graph/v1/paper/search",
params={"query": query, "limit": n, "fields": "title,year,externalIds,citationCount"},
headers={**UA, "x-api-key": S2_KEY},
timeout=30,
)
r.raise_for_status()
return [
{
"title": p["title"],
"year": p.get("year"),
"doi": (p.get("externalIds") or {}).get("DOI", ""),
"cited_by": p.get("citationCount"),
"source": "semantic_scholar",
}
for p in r.json().get("data", [])
]
def crossref(doi: str) -> dict | None:
"""The registered record for a DOI, or None if Crossref has none."""
r = requests.get(f"https://api.crossref.org/works/{doi}", params={"mailto": EMAIL}, headers=UA, timeout=30)
if r.status_code != 200:
return None
m = r.json()["message"]
return {"title": (m.get("title") or [""])[0], "year": (m.get("issued", {}).get("date-parts") or [[None]])[0][0]}
def words(text: str) -> set[str]:
return set(re.findall(r"[a-z]{4,}", text.lower()))
def verify(bib_path: str) -> list[dict]:
"""Check every entry in a .bib file. An entry passes when its DOI resolves
and the registered title shares most of its words with the title cited."""
out = []
for entry in re.split(r"\n(?=@)", Path(bib_path).read_text()):
key = re.match(r"@\w+\{([^,]+),", entry)
if not key:
continue
field = lambda name: (re.search(name + r"\s*=\s*[{\"](.+?)[}\"],?\s*\n", entry, re.S) or [None, ""])[1]
doi, title = field("doi"), field("title")
found = crossref(doi) if doi else None
overlap = len(words(title) & words(found["title"])) / max(1, len(words(title))) if found else 0.0
out.append({"key": key[1], "doi": doi, "ok": bool(found) and overlap >= 0.6, "registered_title": found["title"] if found else None})
time.sleep(0.2)
return out
if __name__ == "__main__":
command, arg = sys.argv[1], sys.argv[2]
if command == "search":
result = openalex(arg) + arxiv(arg) + semantic_scholar(arg)
elif command == "verify":
result = verify(arg)
Path("lit").mkdir(exist_ok=True)
Path("lit/verified.json").write_text(json.dumps(result, indent=2))
print(json.dumps(result, indent=2))
| Source | Key | The limit it sets |
|---|---|---|
| OpenAlex | None for light use | 100 requests a second |
| Crossref | None. It asks for your email | 10 requests a second with an email |
| arXiv | None | A pause of three seconds between calls |
| Semantic Scholar | Optional | One request a second with a key |
| SEC | None. It asks for your name and email | 10 requests a second |
A working paper on arXiv has no Crossref record and will fail the check. The rules below send it to a footnote.
Numbers as macros: make_numbers.py
# make_numbers.py: turn results/numbers.json into LaTeX macros, so the paper never holds a typed number.
import json
from pathlib import Path
numbers = json.loads(Path("results/numbers.json").read_text())
lines = [r"\newcommand{\res}[1]{\csname res@#1\endcsname}"]
for key, value in numbers.items():
text = f"{value:,.3f}" if isinstance(value, float) else f"{value:,}" if isinstance(value, int) else str(value)
lines.append(rf"\expandafter\def\csname res@{key}\endcsname{{{text}}}")
Path("paper/numbers.tex").write_text("\n".join(lines) + "\n")
The paper says \res{main_coef_insample} where a coefficient belongs. Change the code, rerun, and every number in the paper changes with it.
The rules: CLAUDE.md
# Finance paper kit
## The job
Answer the question in config/question.md with public data, and write the paper in paper/main.tex.
## Rules that do not change
- tests/ and config/ are read-only. Never edit them.
- Never read or print .env.
- Every number in the paper is a \res{key} macro. Keys come from results/numbers.json, which only code writes. Run `python make_numbers.py` after it changes. paper/main.tex loads paper/numbers.tex in its preamble.
- Append every specification to results/specs.jsonl before you look at its result. Report the count in the paper as \res{n_specs}.
- Hold out fiscal years 2022 onward. Choose the specification on earlier years, run it once on the held-out years and report both. numbers.json must hold main_coef_insample, main_t_insample, main_coef_holdout and main_t_holdout.
- Cite only papers returned by `python lit.py search`. After any change to paper/refs.bib run `python lit.py verify paper/refs.bib` and remove every reference that fails. A working paper with no DOI goes in a footnote with its URL.
- Use the filing date, not the period end, for anything that depends on when a value became known.
- Use sec.py for every SEC request, under 10 requests a second.
- Write plainly: the finding, the sample, the limitation. No claim without a number behind it.
## Git
- Commit after every stage that passes its checks. The message says what changed and why.
- Read `git log --oneline -20` before starting work.
- Never commit data/ or .env. Never force push, reset or amend.
The question: config/question.md
Question: Do firms that grow their assets faster earn a lower return on assets the following year?
Sample: the first 300 companies in the SEC's company_tickers.json, fiscal years 2012 to 2024.
Measures: asset growth is the yearly change in Assets divided by lagged Assets. Return on assets is NetIncomeLoss divided by lagged Assets.
Main test: regress next year's return on assets on asset growth, with year fixed effects and standard errors clustered by firm.
The five skills
Each goes in its own folder under .claude/skills/, in a file named SKILL.md.
---
name: literature
description: Find and verify the prior work for the question in config/question.md. Use at the start of the paper and whenever a reference is added.
---
1. Read config/question.md. Run `python lit.py search` with three different phrasings of the question.
2. Keep the 10 to 20 papers that bear on the question. Write them to paper/refs.bib with title, authors, year, journal and doi.
3. Run `python lit.py verify paper/refs.bib`. Remove every reference that fails and do not cite it.
4. Write lit/notes.md: one line per paper on what it found and how this paper differs.
---
name: data
description: Build the firm-year panel from SEC filings for the sample in config/question.md. Use when the panel is missing or the sample changes.
---
1. Read the sample from config/question.md and write config/ciks.csv.
2. For each firm call company_facts through sec.py. Keep annual values from 10-K filings.
3. Where a year was reported more than once, keep the first filing.
4. Write data/panel.parquet with cik, fiscal_year, period_end, filing_date and one column per measure.
5. Print the number of firms, firm-years and firms with no data.
---
name: estimate
description: Run the main test in config/question.md and its robustness checks. Use after the panel exists.
---
1. Split the panel: fiscal years before 2022 are in sample, 2022 onward are held out.
2. Before running any specification, append one line describing it to results/specs.jsonl.
3. Run the main test in sample. Run at most five robustness specifications, each logged first.
4. Run the main specification once on the held-out years. Do not change it afterwards.
5. Write results/numbers.json with every number the paper will use, including n_specs, the sample sizes and the four main_ keys. Run `python make_numbers.py`.
---
name: write
description: Draft or revise paper/main.tex from the results and the literature notes. Use after results/numbers.json exists.
---
1. Sections: introduction, data, method, results, robustness, limitations, conclusion.
2. Load paper/numbers.tex in the preamble. Write every number as \res{key}. Type no decimals.
3. Cite with \citep and \citet, using only keys in paper/refs.bib.
4. State the held-out result next to the in-sample result, and the number of specifications tried.
5. The limitations section says what the sample cannot show.
---
name: referee
description: Check the paper against the tests and against what a referee would ask. Use last, and after any revision.
---
1. Run pytest. Fix every failure in the code or the paper. Never touch tests/.
2. Read paper/main.tex as a referee at a finance journal. Write the three weakest points to paper/referee.md.
3. Fix the points that more analysis can fix, logging any new specification first. Leave the rest in the limitations section.
4. Run pytest again and commit.
Read the draft before anyone else does
- Read the commit log first. It shows what the agent did, in order, and where it changed course.
- Open
results/specs.jsonl. The count is your multiple-testing denominator. If it tried eleven specifications, say eleven. - Compare the two main numbers. A result that shrinks or flips on the held-out years is the finding.
- Read
paper/referee.md. The agent’s own list of weak points is where a real referee will start. - Check three references by hand. The test confirms each paper exists. It does not confirm the paper says what the draft claims.
- Disclose. Journals now ask how AI was used, and the commit log is your record.
Everything here runs on public data. To add licensed data such as CRSP returns, read the guide to agents and licensed data first, because the rules change once licensed rows are involved. The SEC filings guide explains the session settings used in the steps above.
References
- Keep Claude working toward a goal, Claude Code documentation code.claude.com
- Extend Claude with skills, Claude Code documentation code.claude.com
- OpenAlex API, rate limits and authentication help.openalex.org
- Crossref REST API, access and authentication crossref.org
- arXiv API user manual info.arxiv.org
- Semantic Scholar API semanticscholar.org
- EDGAR Application Programming Interfaces, SEC sec.gov