Claude for Applied Economists

A working script β€” roughly one hundred pages β€” that takes a working economist from "I have a messy folder of CSVs and a deadline" to "I delegate the boring 80% and keep the judgment."

This is a script, not a reference manual. It is meant to be read front to back, at a desk, with a terminal open. Every chapter has things to type, dialogues to imitate, and exercises with an answer you can check. The voice is deliberately plain: I am talking to an applied economist β€” someone who knows their reghdfe from their ivreghdfe, who has fought a panel into shape at midnight, and who has never been paid to be a software engineer and does not intend to start now.

The promise of the script is narrow and honest. Agentic coding tools will not write your paper or have your ideas. They will collapse the time between an idea and a first result from days to minutes, and they will do it in whatever language you already use β€” Stata, R, Python, Julia, or a pile of shell scripts held together by hope. The skill you are learning is not "prompting." It is delegation under uncertainty: deciding what to hand off, how to specify it, how to check it, and where to keep your hands firmly on the wheel.

How to read this

Each chapter opens with a page marker like pp. 12–24 Β· ~25 min so you can pace yourself. Tick the checkboxes as you go; progress is saved in your browser. Code blocks are written to be copied. The grey/orange boxes labelled You and Claude are transcripts of real-shaped sessions β€” read them as scripts you can perform, not magic incantations.

Who this is for, and what you will be able to do

This script assumes you are an applied microeconomist, macroeconomist, or empirical researcher in a related field (finance, public health, political economy). You have a laptop, data you are allowed to touch, and at least one project that is behind schedule. You do not need to know what a "context window" is, what Git is for, or what an "MCP server" does. You will by the end.

When you finish the script you will be able to:

That is the whole syllabus. Six substantive parts, a setup chapter, and a capstone. Let us begin where every honest course begins: with the boring setup that everyone wants to skip and no one should.


Part 0 β€” Setup, and the Mental Model

pp. 1–14 Β· ~40 min Β· do this once

Two things have to happen before any of the fun. You have to install the tool, and you have to build a correct mental model of what it is. The second matters more than the first. Most economists who bounce off agentic coding do so not because they could not install it but because they carried over a wrong intuition β€” either "it is autocomplete" (too small) or "it is a colleague who knows my project" (too generous). Neither is right. Spend the forty minutes.

Lesson 0.1 β€” What this actually is, in economist terms

Think of Claude Code as a very fast research assistant who has read essentially all public code and documentation, has no memory between sessions, cannot see your screen, and will do exactly what you literally asked β€” including the dumb literal thing β€” but who can run code, read files, and check its own output if you tell it to. Hold that sentence in your head; everything in this script is a corollary of it.

Unpack it the way you would unpack an identification assumption:

The one law

You own the judgment; you delegate the typing. Every good practice in this script is a way of keeping that line bright. Every disaster you will read about is someone letting the line blur.

The agent loop (one diagram in words)

Internally the tool runs a loop: it reads your request and the relevant files, decides on an action (run a command, edit a file, search), takes the action, reads the result, and repeats until it believes the task is done. You do not manage the loop. But you should picture it, because two facts fall out of it:

  1. It works from what it can see. If the relevant fact is in your head and not in a file or your message, the loop never encounters it. Hence: state the non-obvious.
  2. It stops when it thinks it is done, not when you are satisfied. "Done" for the loop means "no error and the request looks addressed." "Done" for you means "correct and defensible in a seminar." Closing that gap is your job, and the script returns to it constantly.

Lesson 0.2 β€” Installation and your first project folder

Installation specifics change; the official instructions live at the Claude Code documentation site and you should follow whatever is current there. The shape, however, is stable, and the shape is what you need to understand:

Set up a clean sandbox project now. Do not point the tool at your dissertation folder on day one. Make a scratch directory with a copy β€” never the original β€” of some non-sensitive data:

mkdir ~/claude-sandbox
cd ~/claude-sandbox
# copy in a NON-confidential, throwaway dataset β€” a copy, never the original
cp ~/Downloads/some_public_extract.csv ./data_raw.csv
Why a copy, always

This is not paranoia, it is the cheapest insurance you will ever buy. The original file, untouched, on disk, is a perfect backup that no agent can corrupt because the agent never sees it. We will make this rigorous in Part 6, but the habit starts on page one: the tool works on copies; the originals are read-only and elsewhere.

Lesson 0.3 β€” Your first session: a ten-minute win

Open the tool in ~/claude-sandbox. Here is the script. Type the You lines; the Claude lines show the shape of what comes back so you know whether you are on track.

YouLook at data_raw.csv. Don't change anything yet. Tell me: how many rows and columns, what each column appears to be, the share of missing values per column, and anything that looks wrong (duplicate IDs, impossible values, mixed types in a column). Show me the commands you ran.
Claude(Loads the file, runs a profiling pass, reports: 48,213 rows, 11 columns; hourly_wage has 311 negative values and 4 entries above 99999; state mixes "CA" and "California"; person_id has 27 duplicates; year stored as text. Lists the exact commands used.)
YouGood. Don't fix anything. Write what you found to a plain-text file called FINDINGS.md, one bullet per issue, each with the column name and a one-line description. Then stop.
Claude(Writes FINDINGS.md and stops.)

That is a complete, useful, safe first session, and it teaches the three habits the whole script rests on:

  1. Look before you leap. "Don't change anything yet" is the single most valuable phrase you will learn. A profiling pass costs you nothing and tells you whether the tool even understands the data the way you do.
  2. Make it show its work. "Show me the commands you ran" converts a black box into something you can audit. You are an empiricist; demand the equivalent of a do-file.
  3. Externalize memory. Writing findings to FINDINGS.md means the knowledge survives the session. Next week, in a fresh context with no memory, that file is still there.

Lesson 0.4 β€” CLAUDE.md: the one file that gives the tool a memory

Because there is no memory between sessions, you create memory by putting durable facts in a file the tool reads automatically: CLAUDE.md in your project root. Treat it as the README you would write for a new RA on their first morning β€” the things that are true about the project no matter what task is in front of them.

Ask the tool to draft it, then edit it by hand:

YouCreate a CLAUDE.md for this project. Include: this is a research project, not production software; the analysis language is Stata (do-files in /do, never edit files in /data_raw, treat them as read-only); the canonical dataset after cleaning is data/analysis.dta; key conventions (real wages are wage_r, deflated to 2015 USD; the 1998 wave is known-unreliable and excluded). Keep it under one page. Plain, declarative sentences.
Claude(Writes a concise CLAUDE.md with those rules as short imperative bullets.)

A good economist's CLAUDE.md usually contains: the language and why; the directory layout and which directories are read-only; the name of the canonical dataset; variable conventions that are not obvious from names; known data problems and the decisions made about them; and how to run the pipeline end to end. It should not contain task-specific instructions ("now add a control for tenure") β€” those go in the conversation. The test: would this still be true and useful in six months? If yes, it belongs in CLAUDE.md.

Exercise 0

In your sandbox: (a) run the profiling dialogue above on any throwaway dataset; (b) have it write FINDINGS.md; (c) draft and then hand-edit a CLAUDE.md with at least three project-specific conventions; (d) close the terminal, reopen it, and ask "What do you know about this project?" β€” confirm it recovers the conventions from CLAUDE.md and nothing from the lost session. That contrast is the lesson.


Part 1 β€” Research Workflows: Cleaning, Scraping, Econometrics

pp. 15–40 Β· ~3 hrs across several sittings

This is the part that pays for the whole script in week one. The claim from the chapter outline is exact: the data cleaning, scraping, and econometric work that "used to take days or weeks" now takes minutes. The catch β€” and this part is mostly about the catch β€” is that wrong results also arrive in minutes, and they arrive looking confident. The discipline of this part is: go fast, then verify like the result is going into a top-five submission, because it is.

Lesson 1.1 β€” Data cleaning in your language

The tool is language-agnostic. The workflow below is shown in Stata, R, and Python so you can use whatever you already use. Nothing here requires you to switch languages, and you should not switch languages to please a tool.

The shape of a cleaning request

A good cleaning request has four parts: the input, the transformations, the output, and the checks. Most economists write the first three and skip the fourth. The fourth is what separates this from a disaster.

YouWrite a Stata do-file do/01_clean.do that reads data_raw/cps.csv and produces data/analysis.dta. Steps: keep ages 25–64; drop the 1998 wave (known unreliable, see CLAUDE.md); recode state to consistent two-letter codes; deflate wage to 2015 USD using data_raw/cpi.csv, call it wage_r; drop wage_r ≀ 0 or > 500. After cleaning, the do-file must: assert there are no duplicate person_id Γ— year; summarize and tab year; and write the N at each step to logs/01_clean.log so I can see exactly how many rows each filter dropped. Do not delete anything from data_raw.
Claude(Writes the do-file with assert statements and a step-by-step row-count log; runs it; reports the N at each stage and flags that the state recode left 134 unmatched values like "Calif.")
YouShow me the 134 unmatched state values and the row counts before and after each filter.

Notice the structure. The "drop N rows" log is a cleaning waterfall β€” the same table you would put in an online appendix. By asking for it as part of the job, you get the audit trail for free and you catch the moment a filter drops 40% of the sample when you expected 4%.

The same job in R

# You: "Same as above but in R, writing data/analysis.rds, using the
# tidyverse, and put the row-count waterfall in logs/01_clean.txt.
# Use a single pipe and stopifnot() for the assertions."
#
# Claude produces something like:
clean <- raw |>
  filter(age >= 25, age <= 64, year != 1998) |>
  mutate(state = recode_states(state),
         wage_r = wage / cpi * cpi_2015) |>
  filter(wage_r > 0, wage_r <= 500)
stopifnot(!any(duplicated(clean[, c("person_id","year")])))

The same job in Python

# You: "Same again in Python with pandas, writing data/analysis.parquet.
# Log the row count after every filter with logging, and assert
# uniqueness on ['person_id','year'] with a clear message."
#
# The point is not the code β€” it is that you specified the CHECKS,
# so the assertion and the waterfall are in every language version.
The cleaning trap

"Remove outliers," "fix the dates," "handle missing values," "clean it up" β€” these are not specifications, they are wishes. The tool will pick a reasonable-looking interpretation and apply it silently to every column. Always say which variable, which rule, and what the expected effect on N is. If you do not know the expected effect on N, that is a sign you should be looking at the data, not delegating yet.

Verifying a clean you did not write

You did not type the do-file, so you must audit it as if a first-year RA wrote it β€” because, in effect, one did. A reliable five-minute audit:

Lesson 1.2 β€” Reshaping, merging, and building panels

Panel construction is the canonical "ninety minutes to ninety seconds" task, and also the canonical place to get burned. The instruction that matters is to make the relational logic explicit, because the tool cannot see your data model β€” it can only see your columns.

YouI have three files: firms.csv (one row per firm, columns firm_id, sic, founded), finance.csv (firm_id, year, revenue, employees β€” one row per firm-year), and deals.csv (deal_id, acquirer_id, target_id, year). Build a firm-year panel keyed on firm_id Γ— year, 2000–2024, balanced on the calendar but unbalanced on existence (a firm only appears from its founded year). Carry firm-level attributes onto every firm-year. From deals, create made_acquisition (1 if the firm was an acquirer that year) and was_acquired (1 the year it was a target). Before writing output, report: the merge match rates, how many firm-years have revenue missing, and whether any firm appears before its founded year.
Claude(Builds the panel, reports a 1:m and m:1 merge diagnostic table, flags 9 firms with finance rows predating founded β€” a real data problem you now get to adjudicate.)

The flagged firms are the whole point. The tool did not "fix" them β€” you told it to report, not repair. Now you, the economist, decide: bad founding dates? subsidiaries reusing IDs? You make the call and tell it the rule. That division β€” machine reports anomalies, human makes the structural call β€” is the template for every merge you will ever delegate.

Merge discipline

For every merge, always ask for the match-rate table (matched, master-only, using-only) before accepting the result. In Stata that is the _merge tabulation; in R/pandas it is an indicator on the join. A merge you have not tabulated is a merge you have not done.

Lesson 1.3 β€” Scraping and APIs without writing the scraper

Pulling data from BLS, FRED, Eurostat, the World Bank, SEC EDGAR, or Companies House, or scraping a public table off a webpage, is now a stating-what-you-want exercise. Two responsibilities stay entirely yours and the tool will not raise them for you: legality/terms of service and politeness (rate limits, caching, identifying your requests). State them yourself, every time.

Official APIs first

YouWrite a Python script src/pull_fred.py that downloads these FRED series β€” UNRATE, CPIAUCSL, GDPC1 β€” using the FRED API. Read the API key from the environment variable FRED_API_KEY; never hardcode it. Cache each raw JSON response to data_raw/fred/<series>.json and only re-download if the cache is older than 24h. Then build a tidy long CSV data/fred_long.csv with columns series, date, value. Print the date range and row count per series.
Claude(Writes the script with env-var key handling, on-disk caching, a polite single-threaded pull, and a summary table.)

Three instructions in there are non-negotiable and you must supply them because the tool will not: key from environment, never hardcoded (Part 6); cache raw responses (so a re-run does not re-hammer the API and so you have the immutable raw pull for your appendix); and raw layer separate from tidy layer (so cleaning bugs never force a re-download).

Scraping a web page

Your call, not the tool's

Before any scrape you state: is this permitted by the site's terms and robots.txt? Is there an official API or bulk download you should use instead? Are you adding a delay between requests and a descriptive User-Agent so you are not hammering someone's server anonymously? The tool will happily write an aggressive scraper if you ask for one. Do not ask for one. "Scrape politely: one request every 3 seconds, cache every page to disk, identify the request, and stop and ask me if you hit a CAPTCHA or a block" is the standing instruction.

YouFirst check: fetch https://example.gov/statistics/robots.txt and the page's terms, and tell me whether scraping the tables at /statistics/regional is permitted. Do not scrape anything yet.
Claude(Fetches robots.txt and terms, summarizes what is and isn't allowed, recommends the bulk CSV endpoint it found instead of scraping.)
YouGood β€” use the bulk CSV endpoint. Download it to data_raw/regional.csv, don't parse it yet, just confirm the size and first 5 lines.

The lesson generalizes: the first scraping request should never scrape. It should investigate permission and look for the boring official download that makes scraping unnecessary. Nine times in ten there is one, and the tool will find it faster than you would.

Lesson 1.4 β€” Reproducible pipelines

You now have cleaning, merging, and pulling scripts. Tie them into one command so that "reproduce the paper" is a single line and so a coauthor (or Reviewer 2, or you in eighteen months) can regenerate everything from raw inputs.

YouCreate a Makefile so that make all runs, in order: pull_fred.py, then 01_clean.do, then 02_panel.do, then 03_analysis.do, then builds tables/main.tex. Each target depends on its inputs so unchanged steps are skipped. Add make clean that deletes everything in data/ and tables/ but NEVER touches data_raw/. Add a one-paragraph "How to reproduce" to the README pointing at make all.
Claude(Writes a dependency-correct Makefile, a guarded clean target that explicitly excludes data_raw, and the README paragraph.)

Read the clean target with your own eyes before you ever run it. make clean deleting your raw data because a wildcard was too greedy is a genuine way to lose a project. This is also the first place the script and Part 6 (Safety) touch: a destructive command is exactly the kind of thing you read line by line and run once in a sandbox before trusting.

Lesson 1.5 β€” Econometric analysis and tables

From a clean panel to results is the highest-leverage delegation in the script, and the one where your judgment is least substitutable. The tool knows the syntax of every estimator. It does not know whether the estimator answers your question. You keep that entirely.

YouUsing data/analysis.dta, estimate the effect of minwage on log_emp with a two-way fixed-effects model: state and year FE, clustered SE at the state level, weighted by pop. Use reghdfe. Then a second spec adding controls (the macro defined in CLAUDE.md). Then an event-study version around treat_year, leads and lags βˆ’5 to +5, omitting βˆ’1. Export all three to tables/main.tex with esttab β€” booktabs, 3 decimals, stars 0.10/0.05/0.01, and a note line stating the FE and clustering. Do not interpret the results; just show me the table and the exact commands.
Claude(Runs the three specifications, exports the LaTeX table, prints the commands. Does not editorialize.)

"Do not interpret the results; just show me the table and the exact commands." Say this every time. You do not want a language model's opinion about your coefficient; you want the number and the code that produced it, so that the interpretation is yours and is defensible. The model is a faster Stata, not a coauthor.

Econometric pitfalls the tool will not flag

It will cheerfully run a regression that is identified by an assumption you would never defend. It does not know your treatment is endogenous, that your "control" is a bad control (a post-treatment collider), that clustering should be at the level of treatment assignment, that your event study has a never-treated/already-treated problem better handled by a modern estimator, or that weights change the estimand. Every identification and specification decision is yours. Use it to execute the design you can defend in a seminar, never to choose it for you.

Robustness as a single delegated batch

Robustness tables are pure delegation gold: tedious, mechanical, and you know exactly what you want. Specify the grid; let it grind.

YouTake the main spec and produce a robustness appendix as tables/robust.tex: (1) drop California; (2) drop 2008–2010; (3) cluster two-way state and year; (4) winsorize log_emp at 1/99; (5) unweighted; (6) add state-specific linear trends. One column each, same outcome, same coefficient of interest highlighted. Below the table, a short text file tables/robust_notes.txt listing in plain words what each column changes versus the main spec. Don't tell me whether it's "robust" β€” I'll judge.
Claude(Produces the six-column table and the plain-language notes file, no editorializing.)

Lesson 1.6 β€” Debugging your own code

You can also point it at code you wrote that is broken. The effective pattern is not "fix this" β€” it is "diagnose, hypothesize, then fix the smallest thing."

You03_analysis.do errors at line 47 with "conformability error." Don't fix it yet. Explain what is happening at line 47, what state the data is in at that point (run the do-file up to line 46 and describe the matrix dimensions), and give me the two most likely causes ranked by probability.
Claude(Runs up to the failure, inspects dimensions, explains the mismatch, ranks causes: most likely a collinear dummy dropped by reghdfe changing the matrix; second, a missing-value pattern.)
YouCause 1 is right. Fix only that, change nothing else, and show me the diff.

"Don't fix it yet β€” diagnose first" prevents the single most common failure mode: the tool rewriting half your working code to make one error disappear, introducing three subtler errors you will not notice until the referee does. Diagnose, confirm the diagnosis yourself, then authorize the smallest possible fix, then read the diff. That sentence is most of what debugging-by-delegation is.

Worked example β€” raw download to regression table, end to end

Do this in your sandbox as the Part 1 capstone. (1) Pull a public series from FRED with the caching script. (2) Pull or load a second public dataset. (3) Clean each with a logged waterfall. (4) Merge into a panel with a reported match rate. (5) Run a two-way FE spec plus a six-column robustness table. (6) Wire all of it into make all. (7) Delete every generated file and run make all once β€” it must rebuild everything from raw with no manual steps. The deliverable is not the table. The deliverable is that step 7 works.

Exercises β€” Part 1

1A. Take a messy CSV. Get a profiling pass and a written FINDINGS.md with no changes made.
1B. Write a logged cleaning script in your language with at least one assert/stopifnot and a row-count waterfall; then reconcile one observation by hand from raw to clean.
1C. Build a three-file panel and produce the merge match-rate table; identify and adjudicate at least one flagged anomaly.
1D. Pull one official API with on-disk caching and a key read from the environment.
1E. Produce a main FE table and a robustness appendix where you specified every column; write the one-paragraph defense of your identification that the tool could not have written for you.


Part 2 β€” Writing with AI, and Beamer

pp. 41–58 Β· ~2.5 hrs

Coding is half of empirical work. The other half is writing and thinking β€” the introduction that frames the contribution, the referee response that saves the paper, the slide deck that has to land in a job talk. The chapter outline puts it precisely: the goal is to write in your voice, to accelerate referee responses, and to generate beautiful Beamer decks with complex TikZ figures in seconds. The danger is equally precise and you must internalize it before you touch the tool: a language model writing your prose with no constraint produces fluent, confident, generic text β€” and generic confident text is exactly what gets a paper rejected. Everything in this part is about keeping the thinking yours while delegating the typing, the formatting, and the mechanical revision.

Lesson 2.1 β€” Writing in your voice

The default register of an unconstrained model is bland consultant-English: hedged, list-happy, fond of "moreover" and "it is important to note." That is not your voice and it is not a good academic voice. You fix this not by asking nicely for "good writing" but by giving it your actual writing as the specification.

YouRead writing/sample_intro.tex and writing/sample_referee.tex β€” these are two things I wrote and am happy with. Describe my style back to me in ten concrete bullets: sentence length, how I use the first person, whether I hedge, how I open paragraphs, punctuation habits, vocabulary I avoid. Don't write anything yet.
Claude(Returns ten specific observations: short declarative openers, "we" only for joint work, no rhetorical questions, em-dashes for asides, never "moreover," prefers active voice, etc.)
YouThat's accurate. Save it as writing/STYLE.md as a set of imperative rules ("Open paragraphs with a claim, not a transition"). From now on, when I ask you to draft prose, follow STYLE.md and never use the words on the avoid list.

You have just built a reusable style specification β€” the writing analogue of CLAUDE.md. Reference writing/STYLE.md in every drafting request. It is the difference between text that sounds like everyone and text that sounds like you, and it is the single highest-return ten minutes in this part.

The line you do not cross

The model drafts; you decide what is true. It must never invent a citation, a number, a mechanism, or a result. The standing instruction in every writing session is: "If you do not have the source for a factual claim, write [CITE?] and a one-line note about what is needed β€” never fabricate a reference or a statistic." A hallucinated citation in a submitted paper is a career problem, not a typo. You catch it by making the model flag its own uncertainty rather than paper over it.

Lesson 2.2 β€” Drafting, tightening, and editing

The model is far better at transforming text you have already thought through than at generating thought. So generate the thought yourself β€” even badly β€” and delegate the transformation.

The brain-dump method

Talk or type the argument out, ugly and unstructured, in your own words. Then:

YouBelow is a messy brain-dump of my contribution paragraph. Do not add any ideas, do not add any claims, do not look anything up. Only: reorder for logical flow, cut repetition, and apply STYLE.md. Keep every factual claim exactly as I stated it; if a claim is vague, leave a [SHARPEN?] marker rather than guessing what I meant. [paste 300 ugly words]
Claude(Returns a tightened ~180-word paragraph in your style, with two [SHARPEN?] markers where your thinking was genuinely unfinished.)

The [SHARPEN?] markers are the feature, not the friction. They point exactly at the places where you have not finished thinking β€” which no model can do for you. Editing-by-delegation is most valuable when it surfaces the holes in your argument instead of smoothing them over.

Tightening on command

Concrete, measurable editing instructions work; vague ones produce vague edits.

Lesson 2.3 β€” Responding to referees

The referee response is where this part earns its keep. The work is high-stakes, emotionally taxing, and largely mechanical scaffolding around a few real intellectual decisions. Delegate the scaffolding; keep the decisions.

YouHere are the three referee reports (referee_1.txt, 2, 3) and our paper. Do NOT write responses yet. Produce a table: every distinct point each referee raised, one row each, columns = referee, point (paraphrased), type (data / identification / framing / typo), and your guess at severity (blocking / major / minor). Group points that overlap across referees.
Claude(Returns a deduplicated, triaged table of ~22 points across three referees, overlaps merged.)
YouGood triage. For the minor and typo rows only, draft the response-letter entries now, in my voice per STYLE.md, in the standard "We thank the referee… We have done X (see p. N)" form, with a [TODO p.?] where I must fill the page number. Leave every identification point blank β€” I will write those myself.

This is the canonical division of labour for the whole script, stated in its sharpest form. The triage (mechanical, the model is good and fast at it) is delegated. The minor responses (formulaic) are delegated with placeholders. The identification responses β€” the ones that decide whether the paper survives β€” you write yourself, because that is the part that is actually your job and the part a model cannot do without inventing. Use the saved hours on those.

Reusable: the referee-response skill

Notice that this triage-then-draft workflow is identical for every paper you will ever submit. That is the definition of something that should become a reusable skill β€” exactly what Part 4 builds. Keep this lesson in mind; you will turn it into a one-word command.

Lesson 2.4 β€” Beamer decks and TikZ figures

Beamer and TikZ are the perfect delegation target: the output is mechanically verifiable (it either compiles and looks right or it does not), the syntax is fiddly and universal, and your judgment is about content and emphasis, not about whether you remembered the \node[draw,circle] incantation.

YouCreate slides/talk.tex, a Beamer deck, metropolis theme, 16:9. Structure: title; one-sentence motivation slide; the research question as a single slide with one display equation; data slide (bullet the three sources from CLAUDE.md); identification slide; a results slide that \includegraphics the figure figures/event_study.pdf; one robustness slide; a one-line takeaway. No paragraphs anywhere β€” telegraphic bullets only. Compile it with latexmk and fix any errors until it builds clean. Show me the PDF page count and the log.
Claude(Writes the deck, compiles, fixes a missing-package error, reports "11 pages, builds clean.")

"Compile it and fix errors until it builds clean" is the instruction that turns LaTeX from a time sink into a non-event. You are not asking the model to be right about LaTeX; you are asking it to iterate against the compiler until the compiler is satisfied β€” verification it can do without you.

A non-trivial TikZ figure from a description

YouIn figures/dag.tex, standalone TikZ, draw the DAG for my identification: nodes Z (instrument), D (treatment), Y (outcome), U (unobserved confounder, dashed). Arrows Z→D, D→Y, U→D, U→Y. U and its arrows in grey and dashed. Lay it out left-to-right, U above. Compile to PDF, show me, and iterate until the U node sits centred above D and Y with no arrow crossings.
Claude(Produces the DAG, compiles, adjusts node positions over two iterations until the layout is clean, shows the PDF.)
You still read every slide

The deck compiling does not mean the deck is right. The model will happily put a confident, wrong sentence on your identification slide. Read every slide of a delegated deck before it leaves your laptop exactly as you read every line of a delegated do-file. The compiler checks syntax; only you check whether the claim on slide 7 is one you will defend when a hand goes up.

Worked example β€” referee response in one sitting

Take a real (or past) set of referee reports. Produce the triaged table; delegate the minor/typo letter entries with placeholders; write the two or three identification responses entirely yourself; have the model assemble the full response letter in your STYLE.md voice with every placeholder clearly marked; then do a final read where your only job is to confirm no fabricated citation, no overclaim, and no point silently dropped from the triage table.

Exercises β€” Part 2

2A. Build writing/STYLE.md from two samples of your own writing; then have a paragraph drafted with and without it and articulate, in writing, the difference.
2B. Brain-dump a contribution paragraph and tighten it via the [SHARPEN?] method; resolve every marker yourself.
2C. Triage a real referee report into the table; classify which rows you would never delegate and why.
2D. Produce a compiling Beamer deck and one non-trivial TikZ figure from a verbal description; log how many compile iterations it took.


Part 3 β€” Research Judgment: Planning Before Delegation

pp. 59–72 Β· ~2 hrs

This is the most intellectually important part of the script and the one with the least typing. The chapter outline frames it exactly: a common practice in agentic coding is to write a plan before doing the work, primarily to preserve the context window β€” and the real skill is knowing when this is worth doing and how to do it well. Planning is not bureaucracy. It is the mechanism by which you keep the judgment while delegating the labour, and it is the antidote to the structural weakness from Part 0: no memory between sessions, stops when it thinks it is done.

Lesson 3.1 β€” When planning is worth it (and when it is overhead)

Not everything needs a plan. Forcing a plan onto a thirty-second task is its own kind of waste. Use this decision rule, which is just expected-cost reasoning you already do instinctively for RA tasks:

Plan first when…Just do it when…
The task touches many files or several pipeline stagesIt is one file, one well-scoped change
A wrong approach is expensive to unwind (schema, panel structure, identification)A wrong approach is cheap to throw away
It will outlive one context window / one sittingIt finishes in one short session
A coauthor or future-you must understand the choicesIt is throwaway exploration you will not keep
You are not yet sure the task is even well-posedThe task is mechanical and unambiguous

The deep reason the left column wins is the Part 0 law restated: the loop "stops when it thinks it is done." On a large or ambiguous task, the model's notion of done and yours diverge badly. A plan is a contract that re-aligns them before any irreversible work happens β€” and crucially, before the cost of being wrong has been paid.

Lesson 3.2 β€” The cost of context, and why plans are written to a file

The model has a finite working memory (the "context window"). A long, exploratory session fills it with dead ends, abandoned attempts, and noise. As it fills, quality degrades β€” the model loses the thread exactly as a tired RA would at hour nine. Planning fights this two ways: it does the expensive thinking once, while context is clean; and it writes the conclusion to a file, so the plan survives into a fresh session where the model is sharp again.

The core move

Think in one session, write the plan to PLAN.md, then execute from PLAN.md in a new session. The fresh session reads the plan as if a careful colleague left clear instructions β€” because one did. This is the single most important technique in the script for non-trivial work, and it is the practical reason "no memory between sessions" is a manageable constraint rather than a fatal one.

Lesson 3.3 β€” Writing a plan that survives a fresh context

Use plan mode (or simply: "Do not change anything. Investigate, then propose a plan."). A plan good enough to execute from cold has six parts:

  1. Goal β€” one sentence, in terms of the research output, not the code.
  2. Inputs and the data model β€” exact files, keys, the relational logic the model cannot see.
  3. Steps β€” ordered, each producing a checkable artifact.
  4. Checks β€” for each step, how we will know it is correct (the match rate, the assertion, the expected N).
  5. Decisions already made β€” the identification choices, sample restrictions, conventions that are yours and not up for the model to revisit.
  6. Out of scope / do not touch β€” explicitly, including data_raw/.
YouDo not write or change anything. Investigate the three input files and CLAUDE.md, then propose a PLAN.md to build the firm-year panel and run the event study, using the six-part structure: goal, inputs/data model, ordered steps, per-step checks, decisions already made (I'll fill these), out-of-scope. Mark anywhere you are guessing about my data with [CONFIRM].
Claude(Writes a draft PLAN.md with several [CONFIRM] markers on data-model assumptions.)
You(Edit the plan by hand: resolve every [CONFIRM], fill the "decisions already made" section with my identification choices, sharpen step 4's check.) Now open a fresh session.
You(new session) Read PLAN.md and CLAUDE.md. Execute steps 1–3 only. After each step run its stated check and show me the result before continuing. Do not start step 4.

"Execute steps 1–3 only… do not start step 4" is deliberate. You are converting the model's open-ended loop into a series of small, checkpointed delegations, each with a verification gate you control. The plan made the work legible; the step-gating keeps the judgment yours throughout execution rather than only at the end.

Lesson 3.4 β€” Knowing when the model is wrong

Planning surfaces wrongness early, but you still need the instinct. The model is most dangerous when it is confidently plausible. Calibrate your suspicion by domain:

Trust more (verify lightly)Trust less (verify hard, or do it yourself)
Syntax of a known command/packageWhether that command answers your question
Mechanical reshape/merge it then tabulatesWhich estimator is appropriate for your design
LaTeX/TikZ that compiles and you can seeWhether a control is a good or bad control
Refactoring code with a test that passesAny causal/economic interpretation
Pulling a documented APIA factual claim or citation in prose

The pattern: trust it on the verifiable and mechanical; distrust it on the inferential and the unverifiable. The right column is, not coincidentally, the list of things that constitute economic expertise. The tool does not erode the value of that expertise β€” it concentrates your day onto it.

Exercises β€” Part 3

3A. For three real tasks from your current project, apply the decision rule and justify plan vs. just-do in one sentence each.
3B. Produce a six-part PLAN.md for a multi-stage task; resolve every [CONFIRM]; execute it from a fresh session with step-gating.
3C. Deliberately give an underspecified instruction, watch where the model's "done" diverges from yours, and rewrite the instruction so the divergence disappears. Write down the general rule you extracted.


Part 4 β€” Reusable Systems: Skills, MCPs, Subagents

pp. 73–86 Β· ~2 hrs

The chapter outline calls skills "the foundational agentic coding topic of greatest use to economists," and that is right for one reason: research is repetition. You build the same regression table, run the same referee triage, produce the same summary-stats panel, every project, for years. A skill turns a workflow you have already perfected into a one-word command that you and your coauthors invoke forever after. Subagents let you fan that work out in parallel; MCP servers connect the tool to your data sources. Together they convert one-off cleverness into durable infrastructure.

Lesson 4.1 β€” What a skill is, and using one

A skill is a named, reusable instruction package: a folder with a description of when to use it and step-by-step guidance the tool follows when you invoke it. You trigger it by name (typically /name). Think of it as a do-file for process rather than for data β€” a codified standard operating procedure. Installing a skill is just placing its folder where the tool looks for skills; from then on it is available in every session in that project.

Lesson 4.2 β€” Build your own: a regression-table skill

You will get more from one skill you built for your own workflow than from fifty generic ones. Build the regression-table skill, because every empirical economist needs it and it makes the abstraction concrete.

YouCreate a skill called regtable. Its job: given a dataset, an outcome, a treatment, optional controls, and an FE/cluster spec, produce a publication-quality LaTeX table. Encode my house style as fixed rules: reghdfe; booktabs via esttab; 3 decimals; stars 0.10/0.05/0.01; a note line stating FE and clustering; always also print N and within-RΒ²; ALWAYS run and show summarize on the estimation sample first; NEVER interpret coefficients. Write the skill so that invoking /regtable asks me for any of those inputs I didn't supply. Put it in the skills folder and show me the skill definition.
Claude(Writes the skill: a description of when to use it plus the encoded procedure and house-style rules; confirms where it was installed.)
You/regtable β€” dataset data/analysis.dta, outcome log_emp, treatment minwage, controls $controls, state and year FE, cluster state.
Claude(Follows the skill: prints the sample summarize, runs the spec, exports the styled table, does not interpret.)

What you have actually built is a codified standard. Your house regression-table style is now executable and consistent across every paper, every coauthor, every RA β€” and it embeds your safety rule ("always summarize the sample first, never interpret"). That is the real payoff: skills are how you make your judgment reusable, not just your code. Good starter skills for an economist: regtable, summstats, referee-triage (from Part 2), clean-waterfall (the logged-cleaning pattern from Part 1), beamer-deck, repro-check (delete generated files and rebuild from raw).

Lesson 4.3 β€” MCP servers: connecting the tool to data sources

An MCP server is a connector that gives the tool a structured, governed channel to a system β€” a database, a data vendor's API, a documentation source β€” instead of you exporting CSVs by hand. For economists the common cases are: a connector to a statistical-data API so series can be pulled by name with provenance; a connector to a SQL warehouse so the tool can query (read-only, by your design) rather than you round-tripping extracts; a connector to a documentation source so it cites real docs rather than recalling them imperfectly.

MCP is a permission surface

An MCP server is a door into a system, so it is governed by the same discipline as Part 6. Prefer read-only connectors for data sources. Know exactly what each connected server can see and do before you connect it. A connector to your confidential warehouse with write access is a connector that can corrupt your confidential warehouse. Treat connecting an MCP server as a security decision, because it is one.

Lesson 4.4 β€” Subagents for parallel research

A subagent is a fresh, isolated worker the main session dispatches to do a self-contained job and report back a summary. The two economist use-cases are parallelism (independent jobs at once) and context hygiene (a noisy search happens in the subagent and only the clean answer returns to your main session β€” directly the Part 3 context-cost concern).

YouRun four robustness checks as parallel subagents, each on a copy of the analysis, each returning only a one-paragraph summary plus the LaTeX for its column: (1) drop CA; (2) drop 2008–2010; (3) two-way clustering; (4) state trends. Don't dump their full logs into this session β€” just the four summaries and the four table columns.
Claude(Dispatches four subagents, returns four tight summaries and four table columns; the noisy execution stayed out of the main context.)

This is Part 1's robustness batch and Part 3's context discipline combining: the slow, log-heavy work is fanned out and isolated, while your main session stays clean and sharp for the decisions only you make.

Exercises β€” Part 4

4A. Build and use a regtable skill that encodes your house style and at least one safety rule.
4B. Convert the Part 2 referee triage into a referee-triage skill and run it on a real report.
4C. Describe one MCP connector that would help your project and write the read-only/least-privilege rule you would impose on it.
4D. Run a four-way robustness batch as parallel subagents returning summaries only; compare the main-session context cleanliness against doing it inline.


Part 5 β€” Version Control: Git, Branches, Collaboration

pp. 87–96 Β· ~1.5 hrs

The chapter outline states the stakes bluntly: agentic coding shifts Git "from an optional nuisance to an absolute necessity." Here is why, with no hand-waving. You are now authorizing a fast agent to modify many files quickly. Without version control, a wrong delegation silently overwrites three weeks of work and there is no undo. With version control, every state of your project is a place you can instantly return to, and "the agent broke something" becomes a thirty-second recovery instead of a catastrophe. You do not need to love Git. You need it to be your seatbelt, and you can let the tool operate most of it.

Lesson 5.1 β€” Why Git is now non-negotiable

Three properties of agentic work make Git mandatory rather than optional:

Lesson 5.2 β€” Git without memorizing Git

You can drive Git through the tool in plain English while keeping the dangerous parts under your own hand. The everyday loop:

YouBefore we start: is this a git repo? If not, initialise one, and write a .gitignore that excludes data_raw/, anything in data/ over 50MB, *.log, and .env. Then make an initial commit of the code and config only. Show me what is staged before you commit β€” I want to see no data files in the list.
Claude(Initialises the repo, writes .gitignore, stages code/config, shows the staged file list for approval, commits after you confirm.)
You(after a working change) Commit this with a clear message describing what changed and why. Show me the diff first.
Read the staged list every time

"Show me what is staged before you commit" is the Part 6 habit applied to Git. It is how a 14GB confidential extract or a .env full of API keys does not end up committed (and, if you ever push, published). Committing data is one of the few genuinely hard-to-fully-undo mistakes in this script β€” history is sticky. The thirty-second review prevents it entirely.

Lesson 5.3 β€” Branches: fearless experiments

A branch is a parallel universe of your project. Use one for anything you are not sure about β€” a referee's demanded reanalysis, a different identification strategy, a risky refactor. If it works, keep it; if it does not, abandon it and the main line never knew.

YouCreate a branch r2-alt-identification and switch to it. On it, redo the analysis with the instrument the referee suggested. The main branch must stay exactly as it is. When you're done, summarise the difference in the headline coefficient between this branch and main β€” don't merge anything.
Claude(Creates and switches to the branch, runs the alternative, reports the coefficient delta versus main, merges nothing.)

You can now show your coauthor both results and decide together, with neither version overwriting the other. That is the entire emotional case for branches: they make consequential experiments cheap and reversible, which is exactly the property the rest of this script keeps insisting on.

Lesson 5.4 β€” Collaboration and recovery

With coauthors, the same tool can explain state and resolve conflicts in plain English: "A coauthor pushed changes; pull them and tell me in plain words what they changed and whether it conflicts with my uncommitted work β€” do not overwrite anything of mine." And recovery β€” the reason the seatbelt exists:

YouThe last change broke the panel build and I haven't committed since this morning's good commit. Show me the difference between now and that commit. I want to discard today's changes to 02_panel.do only β€” nothing else β€” and get back to the working version of just that file. Confirm what you'll do before doing it.
Claude(Shows the diff, states exactly the single-file restore it will perform, waits for your confirmation, then restores only that file.)
Destructive Git stays under your hand

History-rewriting and discard operations (force-push, hard reset, discarding uncommitted work, deleting branches) are the few truly destructive moves here. The rule for the whole script applies in its strongest form: the tool may propose and explain these, but it states exactly what will happen and waits for your explicit confirmation, and you never authorize a force-push to a shared branch on reflex. Frequent commits make you almost never need these anyway β€” which is the point.

Exercises β€” Part 5

5A. Initialise a repo with a .gitignore that provably excludes raw/large/secret files; verify by inspecting the staged list.
5B. Do a small change β†’ review diff β†’ commit loop three times with messages that explain why.
5C. Run a risky reanalysis on a branch, report the coefficient delta versus main, and abandon the branch cleanly.
5D. Deliberately "break" a file with uncommitted changes and recover just that file to its last good commit, with a confirmation gate.


Part 6 β€” Safety: Permissions and Sensitive Data

pp. 97–110 Β· ~2 hrs Β· the part you do not skip

The chapter outline is exact: set up permissions so the tool cannot accidentally delete your data, and adopt real strategies for sensitive or restricted data. This part is last because it presumes everything before it, and first in importance because economists work with data they are legally and ethically responsible for β€” IRB-restricted, DUA-bound, confidential firm or administrative microdata. A leaked or destroyed restricted dataset is not a bug; it is a breach. Read this part twice.

Lesson 6.1 β€” The permission model

The tool runs under a permission policy you set. The spectrum runs from "ask me before every action" (slow, maximally safe) through "auto-allow a named safe set, ask for the rest" (the sweet spot for most research work) to "broadly autonomous" (appropriate only in a disposable sandbox with no real data). Two structural facts make this manageable:

Recommended posture for a real research project

Auto-allow read-only and clearly safe actions (reading files, running read-only analysis, building tables). Require explicit confirmation for every deletion, every overwrite of an input, every command containing rm / git reset --hard / git push / a force flag, and every network send. Never run in a broadly-autonomous mode in any directory that can reach real data.

Lesson 6.2 β€” Making it physically unable to delete your data

Permissions are layer one. The robust protections are structural, and you have already been practising them since page one of this script:

  1. Originals are read-only and outside the project. What the agent never sees, it can never destroy. The project gets a copy; the source of truth lives elsewhere, ideally on a path the project does not even reference.
  2. Operating-system read-only permissions on raw data. Set data_raw/ read-only at the filesystem level (e.g. chmod -R a-w data_raw). Now even a correctly-formed delete command fails. Belt and braces.
  3. Git is the time machine. Everything not gitignored has a history (Part 5). Frequent commits make destruction recoverable.
  4. An untouched backup that the workflow never references. A copy on separate storage that no script and no agent path points at. The backup you cannot reach from the project is the backup that survives the project.
The destructive-command rule

When the tool proposes anything that deletes or overwrites (an rm, a make clean, a hard reset, a script that opens a file for writing over an input), you do three things, every time, no exceptions: read the exact command; confirm it cannot touch data_raw/ or anything irreplaceable; run it once in a sandbox first if you are unsure. "It probably won't delete anything important" is not a risk assessment. The whole reason the originals are read-only and elsewhere is so that the day you are wrong about this is a non-event.

Lesson 6.3 β€” Sensitive, restricted, and enclave data

This is the part with legal weight. Categories and the rule for each:

Data typeWorking rule
Public / openNormal workflow; still keep originals read-only.
Confidential but locally held (licensed firm/admin data under a DUA)Tool may run locally on it. No network sends of the data or its contents. No raw observations pasted into prompts. Verify your configuration does not transmit file contents externally before you begin; if you cannot verify that, do not use the tool on this data.
IRB-restricted human-subjects dataWhatever your protocol says, full stop. If the protocol does not explicitly permit this class of tool touching the data, the answer is no until it is amended. The tool does not override your IRB.
Secure-enclave data (e.g. Census FSRDC and equivalents)Governed entirely by the enclave's rules. You almost certainly cannot run an external tool against enclave data. Do not attempt to move enclave data out to use the tool β€” that is the violation, not a workaround.
Two rules that are never bent

(1) Never paste confidential microdata β€” even a few rows β€” into a prompt. Work on the structure, the schema, the code; never the restricted observations themselves. Give the tool a tiny synthetic fixture with the same column names and types and let it write code against that.
(2) The data-use agreement / IRB protocol / enclave rules are the specification, and they outrank any instruction in this script. If a technique here conflicts with your DUA, the DUA wins, every time, without exception.

The synthetic-fixture pattern

This is how you get the full speed of the tool with zero exposure of restricted data. You never show it the real data; you show it a fake with the same shape.

YouHere is the schema of a confidential dataset (column names, types, value ranges β€” NO real rows). Generate a 500-row synthetic CSV data_fixture/fake.csv matching this schema. Write and fully test the cleaning and analysis code against the fixture only. I will run the finished, reviewed code against the real data myself, locally, with the tool offline. Do not ever ask to see the real data.
Claude(Generates the synthetic fixture, develops and tests all code against it, never requests the real data.)

You get the speed; the restricted data never enters a prompt, never crosses the network, never leaves the room. This single pattern reconciles "minutes instead of weeks" with "I am legally responsible for this data." Make it your default for anything non-public.

Lesson 6.4 β€” Secrets, keys, and .gitignore

API keys, database passwords, signed data-download URLs: keep them in environment variables or an untracked secrets file, never in code, prompts, or commits. This closes the loop with Parts 1 and 5 β€” every API script in Part 1 read its key from the environment for exactly this reason.

Lesson 6.5 β€” The safety checklist

Pin this. Run it at the start of any project that touches data you would be unhappy to lose or leak.

Exercises β€” Part 6

6A. Configure a real-project permission posture and demonstrate the tool asking before a deletion.
6B. Make data_raw/ filesystem read-only and confirm a delete command fails against it.
6C. Take a (real or invented) restricted schema, generate a synthetic fixture, develop working code entirely against it, and write the CLAUDE.md data-handling rule for that project.
6D. Run the full Lesson 6.5 checklist against your actual current project and fix every unchecked box before your next session.


Capstone β€” The Whole Script in One Project

pp. 111–116 Β· a weekend

One project that exercises every part. Pick a real research question you can answer with public data.

  1. Safety first (Part 6): set up the project with read-only originals, .gitignore, permission posture, and a CLAUDE.md data-handling rule β€” before writing any code.
  2. Version control (Part 5): initialise Git; commit the empty scaffold.
  3. Plan (Part 3): write a six-part PLAN.md; resolve every [CONFIRM]; fill "decisions already made" with your own identification choices.
  4. Workflows (Part 1): from a fresh session, execute the plan with step-gating β€” pull (cached), clean (logged waterfall), panel (reported match rate), main + robustness tables. Commit after each green step.
  5. Reusable systems (Part 4): build and use a regtable skill; run the robustness batch as parallel subagents.
  6. Writing (Part 2): build STYLE.md; draft the results section by the brain-dump + [SHARPEN?] method; produce a compiling Beamer deck with one TikZ figure.
  7. Prove reproducibility: delete every generated file; make all rebuilds everything from raw with no manual step. This passing is the capstone.
  8. Final judgement pass (all parts): read every diff, every table, every slide, every prose claim. Confirm there is no fabricated citation, no undefended identification, no point silently dropped, no secret committed, no restricted data exposed. Sign off only when you would defend all of it in a seminar.

Appendix A β€” Prompt Patterns Cheat Sheet

SituationSay this
Starting on unknown data"Don't change anything yet. Profile it and report; write findings to a file; then stop."
Any transformationState the input, the rule per variable, the output, and the check (assertion + expected effect on N).
Any merge"Report the match-rate table before accepting; flag, don't fix, anomalies."
Any API/scrape"Check terms/robots first; prefer the official bulk download; cache raw to disk; key from env; be polite; stop if blocked."
Econometrics"Run exactly this spec; show the commands; do not interpret the results."
Debugging"Don't fix it yet. Diagnose, rank causes; I'll confirm; then smallest fix; show the diff."
Prose"Follow STYLE.md. Add no ideas or claims. Mark [CITE?]/[SHARPEN?] instead of inventing."
Big/ambiguous task"Don't change anything. Investigate and propose a six-part PLAN.md; mark guesses [CONFIRM]."
Execution"Execute steps 1–N only; run each step's check and show me before continuing."
Anything destructive"State exactly what will happen and wait for my explicit confirmation. Confirm it cannot touch data_raw."
Restricted data"Here is the schema, no real rows. Build a synthetic fixture and develop against that only."

Appendix B β€” Language Quick Recipes

The same delegated task, three languages, to prove language-agnosticism. In every case you supply the check; only the syntax differs.

Appendix C β€” Glossary

Context windowThe tool's finite working memory for one session. Fills with noise; degrades. Why we plan and write to files.
CLAUDE.mdProject file auto-read each session; durable, project-wide facts and conventions. Engineered memory.
Plan mode / PLAN.mdInvestigate-and-propose-without-acting; the plan written to a file so it survives a fresh session.
SkillA named, reusable codified procedure (e.g. /regtable) β€” your judgment made repeatable.
MCP serverA governed connector to an external system (DB, data API, docs). A permission surface; prefer read-only.
SubagentAn isolated fresh worker for a self-contained job; used for parallelism and context hygiene.
Synthetic fixtureFake data matching a restricted dataset's schema; lets you develop code without exposing real data.
WaterfallThe logged row-count-after-each-filter table; your cleaning audit trail and appendix exhibit.

Appendix D β€” A Four-Week Schedule


Closing β€” The Skill You Actually Learned

Nothing in these hundred-odd pages was about prompting tricks. The through-line, stated once more because it is the only thing worth remembering: you delegate the typing, the formatting, the mechanical search, the boilerplate, and the fiddly syntax; you keep β€” entirely and without apology β€” the identification, the interpretation, the data-handling responsibility, the destructive decisions, and the final judgement. The tool collapses the cost of the first list to near zero. That does not make the second list less valuable. It makes it the entire job. Go and use the hours you just got back on the work only an economist can do.