# Parse bank statements in Python: scripts and outputs
Checked 2026-11-07. Every script ran as shown; the lines under # $ are what it printed, cut only where you see ....
Contents
- banksia-statement-2026-09.pdf is a made-up 3-page AUD statement (59 transactions) built with reportlab 5.1.0 by make_statement.py below.
- Two transactions run across a page break: 12 Sep (page 1 to 2) and 28 Sep (page 2 to 3).
# TABLES_PY
import pdfplumber
with pdfplumber.open("banksia-statement-2026-09.pdf") as pdf:
for page in pdf.pages:
print(f"page {page.page_number}: {len(page.extract_tables())} tables")
print(pdf.pages[1].extract_text().splitlines()[:4])
# $ python statement_tables.py
# page 1: 0 tables
# page 2: 0 tables
# page 3: 0 tables
# ['Banksia Ridge Bank, statement continued 01 Sep 2026 to 30 Sep 2026', 'DATE TRANSACTION DETAILS DEBIT CREDIT BALANCE', 'Terminal 2 and online orders', 'Card purchase, Northside Office Supplies 46.90 3,870.55 CR']
# PARSE_PY
import json
import re
import sys
from decimal import Decimal
import pdfplumber
from pdfplumber.utils import cluster_objects
MONEY = re.compile(r"^-?\(?[\d,]+\.\d{2}\)?-?$")
def amount(text):
text = text.replace(",", "").strip()
negative = text.endswith(("DR", "-")) or text.startswith(("-", "("))
number = Decimal(text.removesuffix("CR").removesuffix("DR").strip(" ()-"))
return -number if negative else number
def table_lines(page):
words = page.extract_words()
debit = next(w for w in words if w["text"] == "DEBIT")
head = {w["text"]: w for w in words if abs(w["top"] - debit["top"]) < 2}
footer = max(w["top"] for w in words if w["text"] == "Page")
body = [w for w in words if head["DEBIT"]["bottom"] < w["top"] < footer]
columns = {name: head[name]["x1"] for name in ("DEBIT", "CREDIT", "BALANCE")}
for line in cluster_objects(body, "top", 3):
line.sort(key=lambda w: w["x0"])
date = " ".join(w["text"] for w in line if w["x1"] < head["TRANSACTION"]["x0"])
text = " ".join(w["text"] for w in line if w["x0"] >= head["TRANSACTION"]["x0"] and not MONEY.match(w["text"]) and w["text"] not in ("CR", "DR"))
money = {}
for w in line:
if MONEY.match(w["text"]):
column = min(columns, key=lambda name: abs(columns[name] - w["x1"]))
money[column] = w["text"]
elif w["text"] in ("CR", "DR") and "BALANCE" in money:
money["BALANCE"] += " " + w["text"]
yield date, text, money
def parse(path):
rows, opening, closing, day = [], None, None, None
with pdfplumber.open(path) as pdf:
for page in pdf.pages:
for date, text, money in table_lines(page):
if closing is not None:
break
day = date or day
if text == "OPENING BALANCE":
opening = amount(money["BALANCE"])
elif text == "CLOSING BALANCE":
closing = amount(money["BALANCE"])
elif "BALANCE" in money:
rows.append({
"date": day,
"description": text,
"debit": amount(money.get("DEBIT", "0")),
"credit": amount(money.get("CREDIT", "0")),
"balance": amount(money["BALANCE"]),
})
elif text and rows:
rows[-1]["description"] += " / " + text
return opening, rows, closing
if __name__ == "__main__":
opening, rows, closing = parse(sys.argv[1])
print(f"{len(rows)} rows, opening {opening}, closing {closing}")
for row in (rows[21], rows[53]):
print(json.dumps(row, default=str))
# $ python parse_statement.py banksia-statement-2026-09.pdf
# 59 rows, opening 1842.35, closing 10112.19
# {"date": "12 Sep", "description": "Card settlement, Corella Street counter / Terminal 2 and online orders", "debit": "0", "credit": "1312.70", "balance": "3917.45"}
# {"date": "28 Sep", "description": "BPAY, Queensland Revenue Office / Payroll tax 2026-08", "debit": "486.00", "credit": "0", "balance": "9570.90"}
# AMOUNTS_PY
from parse_statement import amount
for printed in ["535.05 DR", "1,204.00 CR", "-86.40", "(86.40)", "86.40-"]:
print(f"{printed:>12} -> {amount(printed)}")
# $ python amounts.py
# 535.05 DR -> -535.05
# 1,204.00 CR -> 1204.00
# -86.40 -> -86.40
# (86.40) -> -86.40
# 86.40- -> -86.40
# CHECK_PY
from parse_statement import parse
def check(opening, rows, closing):
problems = []
balance = opening
for row in rows:
balance += row["credit"] - row["debit"]
if balance != row["balance"]:
problems.append(f"{row['date']} {row['description']}: expected {balance}, printed {row['balance']}")
balance = row["balance"]
if balance != closing:
problems.append(f"closing balance: expected {balance}, printed {closing}")
return problems
opening, rows, closing = parse("banksia-statement-2026-09.pdf")
print(check(opening, rows, closing) or "OK: every running balance and the closing balance add up")
del rows[30]
for problem in check(opening, rows, closing):
print(problem)
# $ python check_balances.py
# OK: every running balance and the closing balance add up
# 17 Sep Transfer to Paddington Packaging / Ref PP-77188: expected 3381.20, printed 3196.60
# VERSIONS_PY
import platform
import subprocess
import sys
from importlib.metadata import version
TOOLS = {
"tesseract": lambda: subprocess.run(["tesseract", "--version"], capture_output=True, text=True).stdout.split()[1],
"ollama": lambda: subprocess.run(["ollama", "--version"], capture_output=True, text=True).stdout.split()[-1],
"libreoffice": lambda: subprocess.run(["soffice", "--version"], capture_output=True, text=True).stdout.split()[1],
}
print("Python", platform.python_version())
for name in sys.argv[1:]:
print(name, TOOLS[name]() if name in TOOLS else version(name))
# $ python versions.py pdfplumber
# Python 3.12.14
# pdfplumber 0.11.10
# make_statement.py
from decimal import Decimal
from reportlab.lib.colors import HexColor
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
D = Decimal
OPENING = D("1842.35")
# (day, details lines, debit, credit)
TX = [
("01 Sep", ["Card settlement, Corella Street counter"], None, "1186.40"),
("01 Sep", ["Direct debit, Brisbane Water", "Account 4471-0932"], "96.20", None),
("02 Sep", ["Transfer to Sunbake Flour Mills", "Ref INV-30417"], "1640.00", None),
("02 Sep", ["Card purchase, Laneway Hardware"], "38.95", None),
("03 Sep", ["Card settlement, Corella Street counter"], None, "934.15"),
("03 Sep", ["Direct debit, Riverbend Dairy Co-op"], "412.80", None),
("04 Sep", ["Payroll, 3 staff", "Batch PAY-0904"], "2310.00", None),
("04 Sep", ["Card settlement, Corella Street counter"], None, "1022.60"),
("05 Sep", ["Transfer to Paddington Packaging", "Ref PP-77120"], "286.50", None),
("05 Sep", ["Card settlement, Corella Street counter"], None, "742.85"),
("06 Sep", ["Card purchase, Fortitude Valley Fuel"], "64.10", None),
("06 Sep", ["Card settlement, Corella Street counter"], None, "655.20"),
("07 Sep", ["Card settlement, Corella Street counter"], None, "1208.35"),
("08 Sep", ["BPAY, Moreton Energy", "Biller 20431 ref 88104772"], "348.75", None),
("08 Sep", ["Transfer to Sunbake Flour Mills", "Ref INV-30502"], "1985.00", None),
("09 Sep", ["Overdrawn fee"], "15.00", None),
("09 Sep", ["Card settlement, Corella Street counter"], None, "876.90"),
("10 Sep", ["Card settlement, Corella Street counter"], None, "1104.25"),
("10 Sep", ["Card purchase, Laneway Hardware"], "22.40", None),
("11 Sep", ["Transfer from Wattle Catering", "Order WC-1182 deposit"], None, "650.00"),
("11 Sep", ["Direct debit, Riverbend Dairy Co-op"], "398.60", None),
("12 Sep", ["Card settlement, Corella Street counter", "Terminal 2 and online orders"], None, "1312.70"),
("12 Sep", ["Card purchase, Northside Office Supplies"], "46.90", None),
("13 Sep", ["Card settlement, Corella Street counter"], None, "822.40"),
("13 Sep", ["Card purchase, Laneway Hardware"], "12.60", None),
("14 Sep", ["Card settlement, Corella Street counter"], None, "964.05"),
("14 Sep", ["Transfer to Paddington Packaging", "Ref PP-77161"], "194.30", None),
("15 Sep", ["Rent, Corella Street Holdings", "Lease CSH-12"], "2750.00", None),
("15 Sep", ["Card purchase, Fortitude Valley Fuel"], "58.30", None),
("16 Sep", ["Card settlement, Corella Street counter"], None, "1051.80"),
("16 Sep", ["Direct debit, Halcyon Insurance", "Policy HB-55120"], "184.60", None),
("17 Sep", ["Transfer to Paddington Packaging", "Ref PP-77188"], "312.40", None),
("17 Sep", ["Card settlement, Corella Street counter"], None, "903.75"),
("18 Sep", ["Payroll, 3 staff", "Batch PAY-0918"], "2310.00", None),
("18 Sep", ["Card settlement, Corella Street counter"], None, "1187.45"),
("19 Sep", ["Card settlement, Corella Street counter"], None, "1243.10"),
("19 Sep", ["Card purchase, Fortitude Valley Fuel"], "61.45", None),
("20 Sep", ["Card settlement, Corella Street counter"], None, "870.35"),
("20 Sep", ["Direct debit, Brightwire Internet"], "89.00", None),
("21 Sep", ["Card settlement, Corella Street counter"], None, "998.65"),
("21 Sep", ["Card purchase, Laneway Hardware"], "31.20", None),
("22 Sep", ["Transfer to Sunbake Flour Mills", "Ref INV-30611"], "1720.00", None),
("22 Sep", ["Direct debit, Riverbend Dairy Co-op"], "405.25", None),
("23 Sep", ["Transfer from Wattle Catering", "Order WC-1182 balance"], None, "1480.00"),
("23 Sep", ["Card settlement, Corella Street counter"], None, "1016.80"),
("24 Sep", ["Card settlement, Corella Street counter"], None, "1129.30"),
("24 Sep", ["Card purchase, Northside Office Supplies"], "23.75", None),
("25 Sep", ["Card purchase, Laneway Hardware"], "17.85", None),
("25 Sep", ["Card settlement, Corella Street counter"], None, "948.10"),
("26 Sep", ["Card settlement, Corella Street counter"], None, "1302.20"),
("26 Sep", ["Card purchase, Fortitude Valley Fuel"], "57.10", None),
("27 Sep", ["Card settlement, Corella Street counter"], None, "887.60"),
("27 Sep", ["Direct debit, Riverbend Dairy Co-op"], "391.40", None),
("28 Sep", ["BPAY, Queensland Revenue Office", "Payroll tax 2026-08"], "486.00", None),
("28 Sep", ["Card settlement, Corella Street counter"], None, "1034.90"),
("29 Sep", ["Card settlement, Corella Street counter"], None, "1076.55"),
("29 Sep", ["Transfer to Sunbake Flour Mills", "Ref INV-30688"], "1560.00", None),
("30 Sep", ["Account fee"], "12.00", None),
("30 Sep", ["Interest"], None, "1.84"),
]
# How many transactions start on each page; a 2-line row at a page end spills its second line over
PAGE_ROWS = [22, 32, 5]
W, H = A4
INK = HexColor("#1f2a37")
MUTED = HexColor("#5b6675")
RULE = HexColor("#c9d3dc")
X_DATE, X_DETAILS, X_DEBIT, X_CREDIT, X_BALANCE = 48, 108, 355, 430, 547
def money(value):
return f"{abs(value):,.2f}"
def balance_text(value):
return f"{money(value)} {'DR' if value < 0 else 'CR'}"
def header_row(c, y):
c.setFont("Helvetica-Bold", 8)
c.setFillColor(MUTED)
c.drawString(X_DATE, y, "DATE")
c.drawString(X_DETAILS, y, "TRANSACTION DETAILS")
c.drawRightString(X_DEBIT + 40, y, "DEBIT")
c.drawRightString(X_CREDIT + 40, y, "CREDIT")
c.drawRightString(X_BALANCE, y, "BALANCE")
c.setStrokeColor(RULE)
c.line(X_DATE, y - 5, X_BALANCE, y - 5)
return y - 19
def footer(c, page, pages):
c.setFont("Helvetica", 7.5)
c.setFillColor(MUTED)
c.drawString(X_DATE, 36, "Corella Street Bakery Pty Ltd, BSB 484-199, account 1029 4471")
c.drawRightString(X_BALANCE, 36, f"Page {page} of {pages}")
def first_page_header(c, totals):
debits, credits, closing = totals
c.setFillColor(INK)
c.setFont("Helvetica-Bold", 15)
c.drawString(X_DATE, H - 60, "Banksia Ridge Bank")
c.setFont("Helvetica", 8.5)
c.setFillColor(MUTED)
c.drawString(X_DATE, H - 74, "120 Ann Street, Brisbane QLD 4000 13 22 41 banksiaridge.example")
c.setFillColor(INK)
c.setFont("Helvetica-Bold", 11)
c.drawString(X_DATE, H - 108, "Business transaction account statement")
c.setFont("Helvetica", 9)
lines = [
("Account name", "Corella Street Bakery Pty Ltd"),
("BSB", "484-199"),
("Account number", "1029 4471"),
("Statement period", "01 Sep 2026 to 30 Sep 2026"),
("Currency", "AUD"),
]
y = H - 128
for label, value in lines:
c.setFillColor(MUTED)
c.drawString(X_DATE, y, label)
c.setFillColor(INK)
c.drawString(X_DATE + 92, y, value)
y -= 13
summary = [
("Opening balance", balance_text(OPENING)),
("Total debits", money(debits)),
("Total credits", money(credits)),
("Closing balance", balance_text(closing)),
]
y = H - 128
for label, value in summary:
c.setFillColor(MUTED)
c.drawString(360, y, label)
c.setFillColor(INK)
c.drawRightString(X_BALANCE, y, value)
y -= 13
return H - 222
def build(path):
rows = []
balance = OPENING
debits = credits = D("0")
for day, details, debit, credit in TX:
if debit:
balance -= D(debit)
debits += D(debit)
if credit:
balance += D(credit)
credits += D(credit)
rows.append((day, details, debit, credit, balance))
c = canvas.Canvas(path, pagesize=A4)
c.setTitle("Banksia Ridge Bank statement, September 2026")
c.setAuthor("Banksia Ridge Bank")
pages = len(PAGE_ROWS)
index = 0
spill = None
last_day = None
for page, count in enumerate(PAGE_ROWS, start=1):
if page == 1:
y = first_page_header(c, (debits, credits, balance))
else:
c.setFont("Helvetica", 8.5)
c.setFillColor(MUTED)
c.drawString(X_DATE, H - 52, "Banksia Ridge Bank, statement continued")
c.drawRightString(X_BALANCE, H - 52, "01 Sep 2026 to 30 Sep 2026")
y = H - 80
y = header_row(c, y)
if spill:
c.setFont("Helvetica", 8)
c.setFillColor(MUTED)
c.drawString(X_DETAILS, y + 4, spill)
y -= 13
spill = None
if page == 1:
c.setFont("Helvetica", 9)
c.setFillColor(INK)
c.drawString(X_DATE, y, "01 Sep")
c.drawString(X_DETAILS, y, "OPENING BALANCE")
c.drawRightString(X_BALANCE, y, balance_text(OPENING))
y -= 18
for n in range(count):
day, details, debit, credit, running = rows[index]
index += 1
c.setFont("Helvetica", 9)
c.setFillColor(INK)
if day != last_day:
c.drawString(X_DATE, y, day)
last_day = day
c.drawString(X_DETAILS, y, details[0])
if debit:
c.drawRightString(X_DEBIT + 40, y, money(D(debit)))
if credit:
c.drawRightString(X_CREDIT + 40, y, money(D(credit)))
c.drawRightString(X_BALANCE, y, balance_text(running))
last_of_page = n == count - 1 and page < pages
if len(details) > 1:
if last_of_page:
spill = details[1]
else:
c.setFont("Helvetica", 8)
c.setFillColor(MUTED)
c.drawString(X_DETAILS, y - 11, details[1])
y -= 11
y -= 7
c.setStrokeColor(RULE)
c.setLineWidth(0.4)
c.line(X_DATE, y + 1, X_BALANCE, y + 1)
y -= 11
if page == pages:
c.setFont("Helvetica-Bold", 9)
c.setFillColor(INK)
c.drawString(X_DETAILS, y, "CLOSING BALANCE")
c.drawRightString(X_BALANCE, y, balance_text(balance))
y -= 30
c.setFont("Helvetica", 7.5)
c.setFillColor(MUTED)
c.drawString(X_DATE, y, "DR means the account is overdrawn. Please check this statement and tell us about any entry you do not recognise.")
footer(c, page, pages)
c.showPage()
c.save()
assert index == len(rows)
return rows, debits, credits, balance
if __name__ == "__main__":
rows, debits, credits, closing = build("banksia-statement-2026-09.pdf")
low = min(r[4] for r in rows)
print(f"{len(rows)} rows, debits {debits}, credits {credits}, closing {closing}, lowest {low}")
End