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.
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:
- Hand Claude a directory of raw downloads and get back a clean, documented, reproducible panel β and know how to verify it is correct.
- Scrape a website or pull an API (BLS, FRED, Companies House, Eurostat) without writing the scraper yourself, while staying on the right side of terms of service.
- Go from a cleaned dataset to a publication-quality regression table and a robustness appendix in one sitting.
- Draft referee responses, tighten prose in your own voice, and produce a Beamer deck with a non-trivial TikZ figure in minutes.
- Decide before you delegate whether a task needs a written plan, and write one that survives a fresh context window.
- Build a reusable "skill" β a regression-table skill, a referee-response skill β that you and your coauthors invoke by name forever after.
- Use Git as a safety net without memorizing Git, so that no agent and no late-night mistake can destroy three weeks of work.
- Set permissions so the tool physically cannot delete your data, and work safely with confidential, IRB-restricted, or enclave-bound datasets.
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 onceTwo 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:
- "Very fast" β a task that is ninety minutes of fiddly
reshapeandmergefor you is ninety seconds for it. This is the entire economic case. Your time is the scarce input; this lowers its shadow price on routine work. - "Has read essentially all public code" β it knows Stata syntax, the
fixestpackage,pandasidioms, BeautifulSoup, regex, LaTeX, TikZ. You do not have to teach it the language. You have to teach it your problem. - "No memory between sessions" β close the terminal and it forgets everything except what you wrote down in files. This is why Part 3 (planning) and the
CLAUDE.mdfile exist. Memory is something you engineer, not something you get. - "Cannot see your screen" β it does not know your variable means a percentage, that
wage2is the deflated one, or that the 1998 wave is unreliable. Unstated context is unavailable context. - "Will do the dumb literal thing" β ask it to "remove outliers" and it may drop the 1% tails of every variable, including your treatment dummy. The judgment is yours; the typing is its.
- "Can run code and check itself" β this is the superpower most people never switch on. An assistant that can execute
summarizeafter a merge and read the result can catch its own mistakes β if you build verification into the request.
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:
- 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.
- 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:
- Claude Code is a command-line program. You run it from a terminal, sitting "inside" a folder β your project. It can see and act on files in that folder and its subfolders, and nothing else by default. That boundary is your first and best safety feature; respect it.
- You start it by opening a terminal,
cd-ing into your project, and launching it. You then talk to it in plain English. It proposes actions; depending on your permission settings it either asks before each one or runs within limits you set (all of Part 6). - There is also a web/desktop entry point, but the discipline is identical: it operates on a project, in a working directory, with a permission policy.
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
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.
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.)That is a complete, useful, safe first session, and it teaches the three habits the whole script rests on:
- 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.
- 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.
- Externalize memory. Writing findings to
FINDINGS.mdmeans 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:
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.
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 sittingsThis 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.
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.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.")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.
"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:
- Read the waterfall. Does every filter drop a plausible number of rows? A surprise is a bug until proven otherwise.
- Spot-check five rows by hand. "Show me
person_id4471 in the raw file and in the cleaned file, side by side, and explain every difference." If you cannot reconcile one person, you do not understand the cleaning. - Check the joins. Merges are where silent disaster lives. "After the CPI merge, how many rows had no CPI match, and what years were they?" An unmatched year means a wrong deflator means every real-wage result is wrong.
- Re-run from scratch. Delete
data/analysis.dta, run only the do-file, confirm it regenerates byte-for-identical. Reproducibility is not a virtue you add later; it is a property you verify now.
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.
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.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.
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
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.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
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.
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.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.
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.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.
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."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.
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.
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.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."
03_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."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.
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.
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 hrsCoding 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.
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.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 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:
[SHARPEN?] marker rather than guessing what I meant. [paste 300 ugly words][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.
- "Cut this 240-word paragraph to under 120 words. Remove hedging. Keep every numeric claim. Do not merge it with the next paragraph."
- "This abstract is 210 words; the journal limit is 150. Cut to 148 without losing the result or the contribution sentence. Show me what you removed."
- "Find every sentence over 40 words and offer a shorter rewrite, side by side. Change nothing else."
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.
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.[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.
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.
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."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
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.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.
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.
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 hrsThis 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 stages | It 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 sitting | It finishes in one short session |
| A coauthor or future-you must understand the choices | It is throwaway exploration you will not keep |
| You are not yet sure the task is even well-posed | The 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.
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:
- Goal β one sentence, in terms of the research output, not the code.
- Inputs and the data model β exact files, keys, the relational logic the model cannot see.
- Steps β ordered, each producing a checkable artifact.
- Checks β for each step, how we will know it is correct (the match rate, the assertion, the expected N).
- Decisions already made β the identification choices, sample restrictions, conventions that are yours and not up for the model to revisit.
- Out of scope / do not touch β explicitly, including
data_raw/.
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].[CONFIRM] markers on data-model assumptions.)"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/package | Whether that command answers your question |
| Mechanical reshape/merge it then tabulates | Which estimator is appropriate for your design |
| LaTeX/TikZ that compiles and you can see | Whether a control is a good or bad control |
| Refactoring code with a test that passes | Any causal/economic interpretation |
| Pulling a documented API | A 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.
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 hrsThe 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.
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.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.
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).
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.
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 hrsThe 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:
- Speed of change. The agent can touch twenty files before you finish your coffee. Frequent commits are restore points between those bursts.
- Delegated edits you did not type. A commit is the clean diff you review to see exactly what the agent changed β your audit log. "Show me the diff" (Part 1's debugging rule) only works if there is a committed baseline to diff against.
- Fearless experiments. A branch lets you try a risky reanalysis knowing the main line is untouched and one command away.
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:
.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..gitignore, stages code/config, shows the staged file list for approval, commits after you confirm.)"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.
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.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:
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.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.
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 skipThe 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:
- The working directory is a boundary. By default the tool acts within the project folder. Keeping confidential originals outside the project the tool runs in is itself a control β possibly the strongest one you have.
- Permissions are configurable per project. Your sandbox can be permissive; your project sitting next to confidential microdata is locked down. Match the policy to the blast radius.
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:
- 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.
- 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. - Git is the time machine. Everything not gitignored has a history (Part 5). Frequent commits make destruction recoverable.
- 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.
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 type | Working rule |
|---|---|
| Public / open | Normal 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 data | Whatever 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. |
(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.
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.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.
- Secrets live in
.env(or your OS keychain)..envis in.gitignorefrom the first commit. - Code reads
os.environ[...]/Sys.getenv(...)β never a literal. - Standing instruction: "Never hardcode a credential; never print one to a log; never include one in a commit. If you need a secret, read it from the environment and tell me which variable you expect."
- Before any push, the staged-list review (Part 5) is also your last secret check.
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.
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 weekendOne project that exercises every part. Pick a real research question you can answer with public data.
- Safety first (Part 6): set up the project with read-only originals,
.gitignore, permission posture, and aCLAUDE.mddata-handling rule β before writing any code. - Version control (Part 5): initialise Git; commit the empty scaffold.
- Plan (Part 3): write a six-part
PLAN.md; resolve every[CONFIRM]; fill "decisions already made" with your own identification choices. - 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.
- Reusable systems (Part 4): build and use a
regtableskill; run the robustness batch as parallel subagents. - 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. - Prove reproducibility: delete every generated file;
make allrebuilds everything from raw with no manual step. This passing is the capstone. - 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
| Situation | Say this |
|---|---|
| Starting on unknown data | "Don't change anything yet. Profile it and report; write findings to a file; then stop." |
| Any transformation | State 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.
- Stata: "β¦after cleaning,
assertno dupid year;tab year; write step Ns to a log." - R: "β¦
stopifnot(!any(duplicated(...)));count(year); write the waterfall to a txt." - Python: "β¦
assert df.duplicated(['id','year']).sum()==0; log row count after each filter."
Appendix C β Glossary
| Context window | The tool's finite working memory for one session. Fills with noise; degrades. Why we plan and write to files. |
| CLAUDE.md | Project file auto-read each session; durable, project-wide facts and conventions. Engineered memory. |
| Plan mode / PLAN.md | Investigate-and-propose-without-acting; the plan written to a file so it survives a fresh session. |
| Skill | A named, reusable codified procedure (e.g. /regtable) β your judgment made repeatable. |
| MCP server | A governed connector to an external system (DB, data API, docs). A permission surface; prefer read-only. |
| Subagent | An isolated fresh worker for a self-contained job; used for parallelism and context hygiene. |
| Synthetic fixture | Fake data matching a restricted dataset's schema; lets you develop code without exposing real data. |
| Waterfall | The 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.