AI and data
statement-extract
Turn PDF bank statements into exact, reconciled transaction data with Claude, with an eval suite that measures it.
- GitHub ↗
- MIT
Turn a PDF bank statement into transaction data you can post to a ledger, and check every figure against the statement's own arithmetic before you trust it.
statement-extract march.pdf --out tx.json
The problem
Back-office teams still get statements as PDFs: from customers applying for a
loan, from banks without an API, and from accounts opened years before anyone
thought about feeds. Template-based parsers break whenever a bank moves a
column. A language model copes with layout changes, but it can also drop a row
at a page break, flip a sign or misread 1.234,56. In a ledger that is worse
than no data, because it looks right.
This tool uses Claude to read the statement and then checks the result with plain arithmetic, which does not depend on trusting the model:
- The money has to add up. The opening balance plus every amount must equal the closing balance exactly. Every running balance printed on a row must equal the previous balance plus that row's amount.
- The dates have to fit. Every transaction must fall inside the statement period, in order.
- The format has to be exact. Amounts are decimal strings (
"-1234.56") with no more decimal places than the currency allows (0 for JPY, 3 for KWD). No floats are involved at any point.
If any check fails, the tool asks Claude once more and shows it the exact errors ("row 14: previous balance plus amount is 2,310.55, but the row's balance is 2,301.55"). If the second answer still fails, you get the result marked as failed, with the reasons, and the exit code says so.
Quick start
Requires Node 24.2 or later and an Anthropic API key.
git clone https://github.com/aranshayan/statement-extract.git && cd statement-extract
npm ci
npm run build
export ANTHROPIC_API_KEY=sk-ant-...
node dist/cli.js eval/fixtures/03-de-soll-haben.pdf --out tx.json
npm link puts statement-extract on your PATH.
Usage: statement-extract <statement.pdf> [options]
-o, --out <file> Write JSON here instead of stdout
-m, --model <id> Claude model (default: $STATEMENT_EXTRACT_MODEL or claude-opus-5-5)
-e, --effort <level> low | medium | high | xhigh | max (default: medium)
--max-tokens <n> Reply token limit (default: 64000)
--no-fallback Do not let the API retry a refused request on another model
Exit codes: 0 reconciled, 2 extracted but failed validation, 1 error.
Output, shortened:
{
"ok": true,
"statement": {
"currency": "EUR",
"period_start": "2026-02-01",
"period_end": "2026-02-28",
"opening_balance": "3507.90",
"closing_balance": "4890.97",
"transactions": [
{
"date": "2026-02-01",
"description": "Lastschrift Mobilfunk Nordnetz",
"amount": "-46.41",
"currency": "EUR",
"balance": "3461.49"
}
]
},
"issues": [],
"attempts": 1,
"models": ["claude-opus-5-5"],
"usage": { "input_tokens": 0, "output_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0 },
"cost_usd": 0
}
(usage and cost_usd hold real numbers on a real run.)
As a library
import { readFile } from "node:fs/promises";
import { extractStatement } from "statement-extract";
const result = await extractStatement(await readFile("march.pdf"), {
model: "claude-opus-5-5",
effort: "medium",
});
if (!result.ok) throw new Error(result.issues.map((i) => i.message).join("\n"));
for (const tx of result.statement!.transactions) {
// tx.amount is a string; use a decimal library or integer minor units, never parseFloat.
}
validateStatement and parseStatement are exported too, if you only want
the checks for data that came from somewhere else.
How it works
- One request to the Messages API, with the PDF as a
documentblock and a JSON schema as the structured output format. The schema keeps to what structured outputs support (types,required,additionalProperties: false). The stricter rules, such as canonical decimals, real calendar dates and ISO currency codes, are checked locally with zod. - Sign convention. The prompt defines the sign by the statement itself:
amounts must make the printed balance work. On a bank account money out is
negative. On a card statement, where the balance is what you owe, purchases
are positive. One rule covers
-, trailing minus, parentheses,CR, Soll/Haben and Af/Bij. - Local checks (
src/validate.ts): totals, running balances, period, order, currency and decimal places. When a running balance breaks, the check reports that row and continues from the printed figure, so one misread gives one error, not twenty. - One retry. The first reply goes back unchanged as the assistant turn,
with the list of errors as the next user turn. A refusal or a reply cut off
at
max_tokensis not retried. Those raiseExtractionError, because asking again would not help. - Fallback. By default the request opts into the API's server-side
fallback (
fallbacks: "default"). If the model declines a request, the API re-runs it on another model in the same call. The models that served each attempt are recorded in the output. Pass--no-fallback(orfallback: false) to require the named model.
The default model is claude-opus-5-5 at medium effort. Both can be
changed. The eval below is how to decide whether a cheaper model is good
enough for your statements.
Eval
eval/fixtures/ holds 16 synthetic statements with exact ground truth. Each
one exists to catch a specific way extraction goes wrong:
| Fixture | Currency | Rows | What it tests |
|---|---|---|---|
01-us-signed | USD | 18 | Baseline: US dates and numbers, one signed amount column, running balance on every row. |
02-gb-paid-in-out | GBP | 22 | Separate Paid out / Paid in columns, written-out dates, a totals box that is not a transaction. |
03-de-soll-haben | EUR | 20 | German numbers (1.234,56) and dates, Soll/Haben columns. |
04-fr-debit-credit | EUR | 18 | French numbers with a space as thousands separator, Débit/Crédit columns. |
05-us-multipage | USD | 95 | Long statement over several pages; tests that no rows are dropped or repeated at page breaks. |
06-de-multipage-uebertrag | EUR | 70 | German multi-page with Übertrag lines, trailing minus signs, two-line entries, row dates without a year, balance only at end of day. |
07-ch-apostrophe | CHF | 16 | Swiss numbers (1'234.50) and two-digit years. |
08-jp-zero-decimal | JPY | 20 | Yen has no minor unit: amounts must come back without decimals. |
09-in-lakh-grouping | INR | 20 | Indian digit grouping (12,34,567.89) and dd-mm-yyyy dates. |
10-card-cr-suffix | USD | 25 | Card statement: purchases raise the balance owed, payments are marked CR, no running balance. |
11-us-parentheses | USD | 18 | Accounting style: money out in parentheses, month-name dates. |
12-gb-newest-first | GBP | 20 | Rows printed newest first; output must be reversed exactly. |
13-us-wrapped-descriptions | USD | 16 | Descriptions wrapped over two or three lines, with reference numbers that look like amounts. |
14-nl-af-bij | EUR | 20 | Dutch statement: unsigned amounts with an Af/Bij column, Dutch month names, end-of-day balances. |
15-gb-fx-notes | GBP | 18 | Foreign card purchases with the foreign amount and fee printed under the row; only the GBP amount counts. |
16-kw-three-decimals | KWD | 16 | Kuwaiti dinar uses three decimal places. |
The generator (eval/generator/) builds each statement from a seeded random
source using integer minor units, then draws it with pdfkit. On the same Node
version, regenerating gives byte-identical files (npm run fixtures). A unit
test checks that every ground-truth file passes the same validator the model
output has to pass, and that the committed ground-truth files match what the
generator produces.
Metrics
Predicted rows are paired with ground-truth rows by what agrees (amount, date, balance, description), so a dropped or duplicated row costs one row and does not shift everything after it.
- Field-level precision and recall for date, description, amount and balance. Precision is correct values over values returned. Recall is correct values over values in the statement. Descriptions count as correct when they match after normalising case, punctuation and spacing, or share at least 80% of their words. Money fields must match exactly.
- Exact amount match: the share of real transactions whose amount came back exactly right.
- Rows fully correct: every field on the row right, including returning
nullwhere the statement prints no balance. - Reconciliation pass rate, on the first request and after the one retry.
- Cost per statement from the token usage the API reports, priced with
the table in
src/pricing.ts.
Running it
export ANTHROPIC_API_KEY=sk-ant-...
npm run eval # all 16, default model
npm run eval -- --model claude-sonnet-5-5 --effort low
npm run eval -- --only 06,10 # a subset
npm run eval -- --self-test # no API calls; checks the harness
A run writes eval/report.md with the summary, field table and per-statement
results, and puts the raw model output in eval/runs/ (not committed).
--self-test answers every request with the ground truth. It costs nothing,
must score 100%, and writes its report into eval/runs/ so it never replaces
a real one.
Results
Not run yet. The numbers in this section will come from
eval/report.md once the eval has been run with an API key. They are
deliberately left empty rather than estimated.
| Model | Effort | Exact amount match | Rows fully correct (recall) | Reconciled, first try | Reconciled, after retry | Mean cost per statement |
|---|---|---|---|---|---|---|
claude-opus-5-5 | medium | – | – | – | – | – |
Cost per statement
Cost is tokens times list price (src/pricing.ts, prices as of
2026-11-23, in USD per million tokens):
| Model | Input | Output |
|---|---|---|
claude-opus-5-5 | 4.00 | 20.00 |
claude-sonnet-5-5 | 2.00 | 10.00 |
claude-haiku-5-5 | 0.10 | 0.50 |
A PDF is billed both as extracted text and as page images, so input grows with page count. Output grows with the number of rows, and thinking tokens are billed as output. A retry roughly doubles the cost of that statement. The eval report gives mean, median and maximum cost per statement for the model you ran.
Limitations
- Reconciling is not the same as being correct. Two errors can cancel out, for example a misread digit in one row offset by another, or a wrong opening balance offset by a wrong closing balance. A model could also invent a row that makes the totals work. On statements with a running balance on every row this is hard to do by accident. On card statements and end-of-day layouts there are fewer checks. That gap is the reason for the eval.
- The fixtures are clean, text-layer PDFs. Scanned or photographed statements, rotated pages, stamps and handwriting are not covered. Expect lower accuracy on those, and add fixtures before relying on it.
- Synthetic layouts are tidier than real ones. Real statements add marketing inserts, interest summaries, pending-transaction sections and multiple accounts in one PDF. The tool currently assumes one account and one currency per statement.
- Descriptions are scored loosely on purpose. If you match on exact description text downstream, measure that separately.
- Value dates are not extracted, only the booking date.
- Large statements are limited by
--max-tokens. A truncated reply fails loudly instead of returning a partial list.
Privacy
There is no real customer data in this repository. Every statement in
eval/fixtures/ is generated by code in eval/generator/. The banks, the
account holder ("Jordan Example") and the account numbers are made up, and
each page says so. Don't commit real statements to a fork: eval/runs/ is
git-ignored, but fixtures are not.
Running the tool sends the PDF to the Anthropic API. Check that this is allowed for the data you process. Nothing is stored or sent anywhere else.
Development
npm test # unit tests, no API key needed (the client is mocked)
npm run lint
npm run typecheck
npm run build
npm run fixtures # regenerate eval/fixtures
CI runs lint, typecheck, tests and build on every push and pull request.
License
MIT
From the README on GitHub, commit 80ab274, . Found a mistake? Open an issue.