# AGENTS.md — DEA Replication Kit

This file is an AI guidance document for the **DEA Denmark** replication kit. Drop it into any AI coding session (Claude Code, GitHub Copilot, Cursor, etc.) so the assistant understands the code structure and can help you run, debug, or adapt it.

---

## Instructions for the AI assistant reading this file

**Do this first, before anything else.**

1. Determine which AI coding tool you are currently operating in. Common possibilities:
   - **Claude Code** — look for a `.claude/` directory or a `CLAUDE.md` file in the repo root
   - **GitHub Copilot** — look for `.github/copilot-instructions.md`
   - **Cursor** — look for `.cursor/rules/` or a `.cursorrules` file
   - **Aider** — look for `CONVENTIONS.md` or `.aider.conf.yml`
   - **Continue.dev** — look for a `.continue/` directory

2. If you can determine the tool from the environment or project structure, tell the user which tool you detected and create the appropriate skill/instruction file for this replication kit in that tool's native format, using the content in this document as the source. Place the file where that tool expects it (e.g., `.claude/agents/dea-replication.md` for Claude Code, `.github/copilot-instructions.md` for Copilot).

3. If you cannot determine the tool, ask the user: *"Which AI coding tool are you using? (e.g., Claude Code, GitHub Copilot, Cursor, Aider, Continue.dev, or other)"* — then create the skill file in the appropriate format once they answer.

4. After creating the skill file, confirm to the user where it was written and what format was used.

---

## What this replication kit is

The kit reproduces all tables and figures in:

> Andersen, Huber, Johannesen, Straub, and Vestergaard. "Disaggregated Economic Accounts." *Quarterly Journal of Economics* 141(2), 2026, pp. 1005–1075.

It implements a **disaggregated circular flow model** for Denmark 2018 — tracking money flows between ~2,700 consumer cells (98 municipalities × ~28 industries) and producer cells. The model is used to compute fiscal multipliers, gravity relationships, regional balance of payments, and counterfactual policy experiments.

The companion data visualization website is at [disaggregatedaccounts.com/denmark](https://www.disaggregatedaccounts.com/denmark).

---

## Prerequisites

- **Python 3.11+** (tested on 3.11.14)
- **Git LFS** — required to fetch the main data file (`data/replication/flows.csv.gz`, 308 MB compressed / 3.4 GB uncompressed)
- **~31 GB free disk space** (peak usage)
- **LaTeX** — optional, only needed to compile standalone table PDFs

Install Git LFS:
```bash
brew install git-lfs          # macOS
sudo apt-get install git-lfs  # Linux
```

---

## Setup

```bash
git clone https://github.com/kilianhuber/dea-denmark.git
cd dea-denmark
python3.11 -m venv dea_venv
source dea_venv/bin/activate        # macOS/Linux
# dea_venv\Scripts\activate         # Windows
bash setup.sh                       # installs deps + creates output dirs
git lfs install
git lfs pull --include="data/replication/flows.csv.gz"
```

---

## How to run

```bash
python run_all.py
```

`run_all.py` orchestrates five steps in order:

| Step | What it does | Runtime (first run) | Runtime (cached) |
|------|-------------|-------------------|-----------------|
| 0 | Clean output dirs | < 1 s | < 1 s |
| 1 | Build circular flows (`flows/`) | ~15 min | ~15 min |
| 2 | Generate facts/figures (`facts/`) | ~6.4 hrs | ~6 min |
| 3 | Verify outputs | < 1 s | < 1 s |
| 4 | Copy outputs to `paper_output/` | < 1 s | < 1 s |
| 5 | Format for Tableau (`format_for_tableau.py`) | ~4 min | ~4 min |

**First run** (~7 hours): computes and caches multipliers in `data/intermediate/`.
**Subsequent runs** (~25 minutes): reuses cached multipliers automatically.

All outputs land in `output/` (figures as PDFs, tables as `.tex`), then get copied to `paper_output/Tables and Figures/python25/`.

---

## Code structure

```
dea-denmark/
├── run_all.py                  # master script — start here
├── setup.sh                    # one-time setup
├── requirements.txt
├── denmarkmacro/               # core Python package
│   ├── circular_flow.py        # main CircularFlow class
│   ├── circular_flow_prices.py # price-augmented version
│   ├── demand_system.py        # demand system estimation
│   ├── auxfs_clean.py          # data cleaning utilities
│   ├── network_plots.py        # Gephi / network visualizations
│   ├── plot_map.py             # choropleth map plotting
│   ├── binscatter.py           # binscatter regression plots
│   ├── centrality.py           # centrality measures
│   ├── gravity_helpers.py      # gravity model utilities
│   └── texression.py           # LaTeX regression table output
├── flows/                      # build circular flow objects
│   ├── get_circular_flow_replication.py   # main replication flow
│   ├── get_circular_flow_local.py         # municipal-level
│   ├── get_circular_flow_industry_regional.py
│   └── ...                     # variants (no finance, gravity, etc.)
├── facts/                      # generate paper tables & figures
│   ├── new_facts_dom_spending.py
│   ├── new_facts_gravity.py
│   ├── new_facts_production.py
│   ├── app_static_multipliers.py
│   ├── app_us_exportshock.py
│   ├── dynamics_individual_scatter_plots.py
│   └── ...
├── data/replication/           # input data (see README for full list)
│   ├── flows.csv.gz            # all monetary flows (Git LFS, 308 MB)
│   ├── sector_Consumers.csv    # consumer cell attributes (98 vars)
│   ├── sector_Producers.csv    # producer cell attributes
│   ├── cf_config.json          # circular flow configuration
│   └── ...
├── format_for_tableau.py       # export to Tableau CSV format
└── gephi/                      # network export for Gephi
```

---

## Adapting for another country

To apply the model to data from a different country (e.g., Canada, Germany), you need data at the **sub-national unit × industry sector** level. Here is what to provide and where.

### 1. Data you need

#### Flows matrix (`data/replication/flows.csv.gz`)

The core input is a matrix of monetary flows between every pair of sector cells. Each row represents one directed flow from a source cell to a destination cell. The Denmark model contains the following flow types — you need to provide the equivalents for your country:

| Flow | Source → Destination | Description |
|------|----------------------|-------------|
| Consumer spending on domestic goods | Consumer cell → Producer cell | Household spending on locally-produced goods and services, disaggregated by consumer municipality × industry and producer municipality × industry |
| Intermediate inputs | Producer cell → Producer cell | Firm purchases of inputs from other firms (the input-output / supply-chain layer) |
| Labor compensation | Producer cell → Consumer cell | Wages and salaries paid by firms to workers in each consumer cell |
| Dividends and capital income | Producer cell → Consumer cell | Capital income distributed from firms to household shareholders |
| Household taxes | Consumer cell → Government | Income taxes, VAT, and other taxes paid by households |
| Firm taxes | Producer cell → Government | Corporate taxes, payroll taxes, and other taxes paid by firms |
| Government transfers | Government → Consumer cell | Social benefits, pensions, and other transfers received by households |
| Government procurement | Government → Producer cell | Public spending on goods and services purchased from firms |
| Consumer imports | Consumer cell → ROW | Household spending on foreign goods and services |
| Producer exports | ROW → Producer cell | Foreign demand for domestically-produced goods |
| Financial flows (capital) | Finance/Capital → Consumer/Producer cells | Investment flows, depreciation, and capital accumulation (if modeled) |



#### Sector attribute files

| Data | Description | File to replace |
|------|-------------|----------------|
| Consumer cell attributes | Demographics, income, wealth per municipality × industry (used in gravity regressions, multiplier analysis) | `data/replication/sector_Consumers.csv` |
| Producer cell attributes | Industry characteristics per region (output, employment, trade openness) | `data/replication/sector_Producers.csv` |
| Government attributes | Government revenue and spending aggregates | `data/replication/sector_Government.csv` |
| Finance / capital attributes | Capital accumulation and investment aggregates | `data/replication/sector_Finance.csv` |
| Rest of World (ROW) | Import and export aggregates by country/region | `data/replication/sector_ROW*.csv` |

#### Reference and crosswalk files

| Data | Description | File to replace |
|------|-------------|----------------|
| Circular flow config | Sector definitions, flow structure, column mappings | `data/replication/cf_config.json` |
| Region names | Region code → human-readable name | `data/replication/region_names.csv` |
| Sector names | Sector code → human-readable name | `data/replication/sector_names.csv` |
| Shapefiles (optional) | For choropleth map figures | `data/geofiles/` |

### 2. Key configuration to update

- **`data/replication/cf_config.json`** — defines which sectors exist, how flows are structured, and which columns map to which economic concepts. This is the most important file to adapt: update sector lists and flow definitions to match your country's data.

- **`data/replication/demand_supply_config.json`** — demand system and supply function specifications. Adjust elasticities and functional forms if your country's calibration differs.

- **`data/replication/df_mpcs.csv`** — marginal propensities to consume per consumer cell. Replace with your country's MPC estimates (from household surveys or quasi-experimental estimates).

- **`data/replication/policy_shocks.csv`** — shock definitions for counterfactual experiments. Redefine shocks to match your country's policy environment.

### 3. Column naming conventions

The `sector_Consumers.csv` uses `cust_` prefixes (e.g., `cust_age`, `cust_laborinc`). The `sector_Producers.csv` uses `prod_` prefixes. Keep these conventions or update the references in `denmarkmacro/circular_flow.py` and `auxfs_clean.py` accordingly.

### 4. Cell identifier format

Consumer cells are identified as `r{region_code}_{sector_code}`. If your region or sector codes contain letters or special characters, update the ID-construction logic in `denmarkmacro/auxfs_clean.py`.

### 5. What you can skip

- The `gephi/` network export and `facts/main_plot.py` figure require a pre-computed Gephi layout file. For a new country you can skip Figure II (the circular flow network diagram) until you generate a new layout.
- In-person (offline) spending is not replicated for Denmark due to privacy restrictions. If your country's data includes it, add the relevant flows to `cf_config.json`.
