A model should only see the bank transactions your rules could not categorise
A rules-first Python pipeline that categorises a year of bank transactions and sends only the leftovers to a language model.
Hakob Nahapetyan · 2026-10-27 · 10 min
Sending every bank transaction to a language model is slow, costs money every run and can change its answer between runs. Most of a bank statement repeats: the same supermarket, the same train fare, the same rent. A merchant map and a few regular expressions handle those for free and give the same answer every run.
This guide builds the whole pipeline in Python. Normalise a bank CSV export. Categorise with rules. Send only the misses to a model with a fixed category list and a confidence. Put low-confidence answers on a review list. Turn corrections into rules. Print a monthly summary with the recurring payments it found.
The data is synthetic
Every number in this post comes from a synthetic export I generated with a seeded script. It has 818 rows for 2025 on one UK current account: salary, rent, bills, five subscriptions and daily card spending at 17 merchants. No real person's data is in it. It has the mess of a real export: day-first dates, thousands separators and mixed case. Descriptions carry store numbers and references. Rows are out of date order.
Date,Description,Amount
19/05/2025,CARD PAYMENT TO TESCO STORES 8193 LONDON,-8.82
07/03/2025,Card Payment To Tesco Stores 9025 London,-38.29
10/05/2025,Zettle_*Harbour Fish,-15.42
Step 1: normalise before anything else
The first two rows are the same shop. Rules match on a clean merchant name, so first strip everything that changes between rows: bank prefixes, card reader prefixes, store numbers and references.
import csv, json, re, statistics, sys
from collections import Counter, defaultdict
from datetime import datetime
from decimal import Decimal
CATEGORIES = ["Groceries", "Eating out", "Transport", "Housing", "Utilities",
"Subscriptions", "Shopping", "Health and fitness", "Travel",
"Pets", "Personal care", "Income", "Transfers", "Other"]
MODEL = "claude-haiku-5-5"
THRESHOLD = 0.80
# ---------- 1. normalise ----------
BANK_PREFIX = r"^(CARD PAYMENT TO|DIRECT DEBIT|STANDING ORDER TO|BACS CREDIT|FASTER PAYMENT FROM)\s+"
READER_PREFIX = r"^(SQ|SUMUP|ZETTLE_?|PAYPAL) ?\*" # card readers: real name comes after the *
def clean_merchant(desc):
s = desc.upper().strip()
s = re.sub(BANK_PREFIX, "", s)
s = re.sub(READER_PREFIX, "", s)
s = re.sub(r"\*.*$", "", s) # AMZN MKTP UK*X1Y2Z3 -> AMZN MKTP UK
s = re.sub(r"\b[A-Z0-9]*\d[A-Z0-9]*\b", " ", s) # any token with a digit: store ids, refs, accounts
s = re.sub(r"[^A-Z& ]", " ", s)
return re.sub(r"\s+", " ", s).strip()
def load(path):
txs = []
with open(path, newline="") as f:
for r in csv.DictReader(f):
txs.append({
"date": datetime.strptime(r["Date"], "%d/%m/%Y").date(),
"raw": r["Description"],
"merchant": clean_merchant(r["Description"]),
"amount": Decimal(r["Amount"].replace(",", "")), # negative = money out
})
return sorted(txs, key=lambda t: t["date"])
Check the date format and the sign convention on your own export. Some banks split amounts into debit and credit columns. Some show money out as positive. Get the sign wrong and every total below is wrong.
The digit rule also does privacy work. Any token containing a digit is dropped, so account numbers, sort codes and payment references are gone before the model step.
Step 2: rules first
Rules live in rules.json, so they grow without code changes. The merchant map holds exact cleaned names and is checked before the patterns, so a correction you make always beats a broad pattern. These are the nine starting rules:
{
"merchants": {},
"patterns": [
["^(TESCO|SAINSBURYS)", "Groceries"],
["^(TFL|UBER|SHELL)", "Transport"],
["^(NETFLIX|SPOTIFY|ICLOUD)", "Subscriptions"],
["^(PRET|DELIVEROO)", "Eating out"],
["^AMZN", "Shopping"],
["PAYROLL", "Income"],
["\\bRENT\\b", "Housing"],
["ENERGY", "Utilities"],
["GYM", "Health and fitness"]
]
}
# ---------- 2. rules ----------
def apply_rules(tx, rules):
if tx["merchant"] in rules["merchants"]:
return rules["merchants"][tx["merchant"]], "merchant_map"
for pattern, category in rules["patterns"]:
if re.search(pattern, tx["merchant"]):
return category, "regex"
return None, None
Step 3: the model sees only what rules missed, once per merchant
Three choices keep this step cheap and checkable.
- Group misses by merchant. Thirty-six rows from one chemist are one question, so the model gets one line for them.
- Force a fixed category list with tool use and an
enum, then check the answer in code anyway. A model can still return an id that is outside the batch. - Ask for a confidence and use it only to sort. A model's own confidence is loosely calibrated. After a few months of corrections, set the threshold from how often the accepted answers were right.
# ---------- 3. the model, only for what rules missed ----------
TOOL = {
"name": "classify",
"description": "Assign each merchant to exactly one category.",
"input_schema": {
"type": "object",
"properties": {"results": {"type": "array", "items": {
"type": "object",
"properties": {
"id": {"type": "integer"},
"category": {"type": "string", "enum": CATEGORIES},
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
},
"required": ["id", "category", "confidence"]}}},
"required": ["results"],
},
}
PROMPT = ("Classify these card and bank merchants from a UK personal account. "
"Use only the given categories. If you cannot tell, use Other with low confidence.\n\n")
def classify_with_llm(client, merchants, batch=50):
"""merchants: list of dicts with merchant, direction, typical, count. Returns {merchant: (category, confidence)}."""
out = {}
for start in range(0, len(merchants), batch):
chunk = merchants[start:start + batch]
lines = [f'{i}. "{m["merchant"]}" {m["direction"]}, typical {m["typical"]}, seen {m["count"]} times'
for i, m in enumerate(chunk)]
resp = client.messages.create(
model=MODEL, max_tokens=4000, tools=[TOOL],
tool_choice={"type": "tool", "name": "classify"},
messages=[{"role": "user", "content": PROMPT + "\n".join(lines)}])
block = next(b for b in resp.content if b.type == "tool_use")
for r in block.input["results"]:
ok = r["category"] in CATEGORIES and 0 <= r["id"] < len(chunk)
if ok: # never trust the schema alone
out[chunk[r["id"]]["merchant"]] = (r["category"], float(r["confidence"]))
return out
def categorise(txs, rules, client):
misses = []
for t in txs:
t["category"], t["source"] = apply_rules(t, rules)
if t["category"] is None:
misses.append(t)
groups = defaultdict(list) # send each merchant once, not each row
for t in misses:
groups[t["merchant"]].append(t)
merchants = [{"merchant": m, "count": len(ts),
"direction": "money out" if ts[0]["amount"] < 0 else "money in",
"typical": f'{statistics.median(abs(t["amount"]) for t in ts):.2f}'}
for m, ts in groups.items()]
answers = classify_with_llm(client, merchants) if merchants else {}
review = []
for m in merchants:
category, conf = answers.get(m["merchant"], ("Other", 0.0))
accepted = conf >= THRESHOLD and m["direction"] == "money out" # money in: a person decides
for t in groups[m["merchant"]]:
t["category"], t["source"] = (category, "llm") if accepted else ("Other", "review")
if not accepted:
review.append({**m, "model_guess": category, "confidence": conf, "correct_category": ""})
return merchants, review
Each line in the prompt carries the merchant name, direction, median amount and row count. That is all that leaves your machine. Dates, balances and account numbers stay local. If that is still too much, run a local open-weights model instead. classify_with_llm only needs an object with a messages.create method that returns a tool_use block, so nothing else changes.
Testing without an API key
I ran this with no API key. The model call goes to a stub that returns the same response shape as a real tool_use reply. GUESSES maps 13 merchant names to hard-coded pairs such as "BOOTS": ("Health and fitness", 0.62). Treat those as an example of the format, never as model output.
class FakeClient:
def __init__(self):
self.messages = self
self.calls = []
def create(self, **kwargs):
self.calls.append(kwargs)
results = []
for line in kwargs["messages"][0]["content"].splitlines():
m = re.match(r'^(\d+)\. "(.*?)"', line)
if m:
category, conf = GUESSES.get(m[2], ("Other", 0.2))
results.append({"id": int(m[1]), "category": category, "confidence": conf})
block = SimpleNamespace(type="tool_use", name="classify", input={"results": results})
return SimpleNamespace(content=[block], stop_reason="tool_use")
Add import re, from types import SimpleNamespace and a GUESSES dict above it. Five pytest tests check the merchant cleaner, that the merchant map beats a regex, that low confidence and money in go to review and that each merchant is sent once. All pass.
Step 4: corrections become rules
review.csv has one row per merchant and an empty correct_category column. You fill it in and run learn. A merchant you correct once never reaches the model again.

review.csv from the first run, as a reviewer opens it. The model guesses and confidences come from the stub client and are an example of the format.
# ---------- 4. corrections become rules ----------
def learn(review_path, rules_path):
rules = json.load(open(rules_path))
added = 0
for r in csv.DictReader(open(review_path)):
if r["correct_category"] in CATEGORIES:
rules["merchants"][r["merchant"]] = r["correct_category"]
added += 1
json.dump(rules, open(rules_path, "w"), indent=2)
return added
Step 5: monthly summary and recurring payments
# ---------- 5. monthly summary and recurring payments ----------
def monthly_spend(txs):
table = defaultdict(Decimal)
for t in txs:
if t["amount"] < 0 and t["category"] not in ("Transfers",):
table[(t["date"].strftime("%Y-%m"), t["category"])] += -t["amount"]
return table
def recurring(txs, min_count=3):
by_key = defaultdict(list) # same merchant AND same amount
for t in txs:
if t["amount"] < 0:
by_key[(t["merchant"], t["amount"])].append(t["date"])
found = []
for (merchant, amount), dates in by_key.items():
if len(dates) < min_count:
continue
gaps = [(b - a).days for a, b in zip(dates, dates[1:])]
med = statistics.median(gaps)
for label, lo, hi in (("weekly", 6, 8), ("monthly", 27, 33), ("yearly", 360, 370)):
if lo <= med <= hi and max(gaps) - min(gaps) <= 6:
found.append((merchant, -amount, label, len(dates)))
return sorted(found, key=lambda r: -r[1])
A recurring payment here means the same merchant, the same amount and a regular gap. The energy direct debit is monthly but its amount changes, so it does not appear. That is deliberate: a subscription you forgot about is usually a fixed amount. Loosen the amount match if you want variable bills too.
The command line wrapper prints the counts and writes the review file:
def main():
mode = sys.argv[1]
if mode == "learn":
print("rules added:", learn("review.csv", "rules.json"))
return
if "--fake" in sys.argv:
from fake_client import FakeClient
client = FakeClient()
else:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
txs = load("bank_export.csv")
rules = json.load(open("rules.json"))
merchants, review = categorise(txs, rules, client)
src = Counter(t["source"] for t in txs)
n = len(txs)
print(f"rows: {n}")
for s in ("merchant_map", "regex", "llm", "review"):
print(f" {s:13} {src[s]:4} {src[s] / n:6.1%}")
print(f"unique merchants sent to model: {len(merchants)}, to review: {len(review)}")
with open("review.csv", "w", newline="") as f:
cols = ["merchant", "count", "direction", "typical", "model_guess", "confidence", "correct_category"]
w = csv.DictWriter(f, fieldnames=cols)
w.writeheader()
w.writerows(review)
spend = monthly_spend(txs)
totals = defaultdict(Decimal)
for (_, cat), v in spend.items():
totals[cat] += v
print("\nspend by category, 2025 (monthly average)")
for cat, v in sorted(totals.items(), key=lambda kv: -kv[1]):
print(f" {cat:20} {v:10.2f} {v / 12:8.2f}")
print("\nrecurring payments (same amount, regular interval)")
for merchant, amount, label, count in recurring(txs):
print(f" {merchant:28} {amount:8.2f} {label:8} x{count}")
if __name__ == "__main__":
main()
What the run produced
First run, with the nine starting rules:
| Where the category came from | Rows | Share |
|---|---|---|
| Merchant map | 0 | 0.0% |
| Regex rules | 661 | 80.8% |
| Model, accepted (stub answers) | 84 | 10.3% |
| Review list | 73 | 8.9% |
Rules caught 661 of 818 rows. The other 157 came from 12 merchants, so the model step was one API call with 12 lines in it. Those counts come from the real pipeline. The split between accepted and review depends on the stub's hard-coded confidences, so a real model will split them differently. In my run 5 merchants, covering 73 rows, went to review.
A small script then played the reviewer and filled in those 5 rows. After learn, the second run looked like this:
rows: 818
merchant_map 73 8.9%
regex 661 80.8%
llm 84 10.3%
review 0 0.0%
unique merchants sent to model: 7, to review: 0
Rules now covered 734 rows (89.7%) and only 7 merchants went to the model. Those 7 were accepted in the first run, so a sensible next step is saving spot-checked answers as rules.

Both runs on the synthetic export. The row counts are real pipeline output. The split between model and review depends on the stub answers.
The first run also found these recurring payments:
recurring payments (same amount, regular interval)
J HARRIS RENT 1250.00 monthly x12
PUREGYM LTD 34.99 monthly x12
SPOTIFY STOCKHOLM 11.99 monthly x12
NETFLIX COM 10.99 monthly x12
ICLOUD STORAGE APPLE COM BILL 2.99 monthly x12
Its category summary showed 1,870.76 in Other: the 72 money-out rows still on the review list. A large Other means the review list is not done yet.
Where the model helps and where it must not decide
The model is useful on the long tail: small local shops, card reader names and one-off purchases, where no pattern exists to write down.
It should not decide transfers between your own accounts, money from other people or anything that feeds a tax return. The synthetic export has a 40.00 payment in from "M CHEN". A loan repayment, a split dinner bill and a gift all look the same in a bank line. Only you know which it was. So categorise sends every money-in merchant the rules miss to review, whatever the confidence.
Run it yourself
python3 -m venv venv && . venv/bin/activate
pip install anthropic
python categorise.py run --fake # full run with the stub client
export ANTHROPIC_API_KEY=your-key
python categorise.py run # same run, real model on the misses
python categorise.py learn # after you fill correct_category in review.csv
Save your export as bank_export.csv and adjust the column names and date format in load(). Any CSV with Date, Description and Amount columns works.
If your finance team wants this built on its own bank data, write to me.



