DEV Community

Murabyte
Murabyte

Posted on

Extract bank statement transactions from a PDF into Excel with Python and check the balance

Disclosure: I make BankPDF2Excel at Murabyte, which is mentioned at the end. Written with AI assistance and reviewed by Murabyte.

If your bank statement PDF contains real text (you can select it with the mouse), you can pull the transactions out with Python and write them to Excel. This post shows a small script, and the cases where it stops being enough.

Install

pip install pdfplumber pandas openpyxl
Enter fullscreen mode Exit fullscreen mode

Read the lines

import re
import pdfplumber
import pandas as pd

DATE = re.compile(r"^(\d{2}/\d{2}/\d{4})\s+(.*)$")
AMOUNT = re.compile(r"-?\d{1,3}(?:,\d{3})*\.\d{2}")

rows = []
with pdfplumber.open("statement.pdf") as pdf:
    for page in pdf.pages:
        for line in (page.extract_text() or "").splitlines():
            m = DATE.match(line.strip())
            if m:
                rows.append([m.group(1), m.group(2)])
            elif rows and not AMOUNT.search(line):
                rows[-1][1] += " " + line.strip()  # wrapped description
Enter fullscreen mode Exit fullscreen mode

Lines that start with a date begin a new transaction. A line with no amount under it is the wrapped second half of the description above.

Split description and amounts

def split(desc):
    nums = AMOUNT.findall(desc)
    text = AMOUNT.sub("", desc).strip()
    return text, [float(n.replace(",", "")) for n in nums]

data = []
for date, desc in rows:
    text, nums = split(desc)
    if len(nums) >= 2:
        data.append({"date": date, "description": text,
                     "amount": nums[-2], "balance": nums[-1]})

df = pd.DataFrame(data)
df["date"] = pd.to_datetime(df["date"], format="%d/%m/%Y")
df.to_excel("statement.xlsx", index=False)
Enter fullscreen mode Exit fullscreen mode

Here the last number on a line is the balance and the one before it is the amount. Change the date format if your bank uses month first.

Check it

diff = df["balance"].diff().round(2) - df["amount"]
print(df[diff.abs() > 0.01])
Enter fullscreen mode Exit fullscreen mode

If the amounts are signed, every row where the balance does not move by the amount shows up. Those are the rows to look at.

Where a script stops being enough

Scanned PDFs have no text, so you need OCR. Layouts with separate debit and credit columns, Dr/Cr markers, decimal commas, or Arabic numerals each need their own rules, and each bank is different.

If you would rather not maintain it

BankPDF2Excel is a Windows app that converts PDF statements to Excel, CSV, QuickBooks QBO and Tally XML on your PC, with no uploads. It shows each row next to the PDF with a confidence flag, so you verify before export. It is $149 per year, with a 15-day trial that exports the first 10 transactions per statement.

More on the problem: https://murabyte.netlify.app/en/convert-bank-statement-pdf-to-excel
Free trial: https://murabyte.gumroad.com/l/bankpdf2excel-trial
Gumroad: https://murabyte.gumroad.com/l/bankpdf2excel
Microsoft Store: https://apps.microsoft.com/detail/9N6R286B2LKP

python #pandas #excel #bookkeeping

Top comments (0)