CodeForFinance
Excel

Automated Budget Tracker with Python and Excel

Manual budgeting in spreadsheets is tedious. In this tutorial, we build an automated budget tracker that reads bank transaction CSVs, categorises spending using keyword matching, and generates a formatted Excel report with charts and summaries.

Prerequisites

  • Basic Python
  • Basic Excel knowledge

Step 1.Install dependencies

pandas for data processing, openpyxl for Excel generation.

pip install pandas openpyxl matplotlib

Step 2.Create sample transaction data

In real use, you would import your bank CSV. Here we generate realistic test data.

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

np.random.seed(42)
num_transactions = 100

categories = {
    "Groceries": ["TESCO", "SAINSBURYS", "ALDI", "LIDL", "ASDA"],
    "Transport": ["TFL", "UBER", "SHELL", "BP FUEL"],
    "Dining": ["NANDOS", "MCDONALDS", "PRET", "COSTA", "STARBUCKS"],
    "Bills": ["NETFLIX", "SPOTIFY", "EE MOBILE", "BT BROADBAND", "COUNCIL TAX"],
    "Shopping": ["AMAZON", "ASOS", "JOHN LEWIS", "ARGOS"],
}

transactions = []
start = datetime(2024, 1, 1)
for _ in range(num_transactions):
    cat = np.random.choice(list(categories.keys()))
    merchant = np.random.choice(categories[cat])
    amount = round(np.random.uniform(3, 150), 2)
    date = start + timedelta(days=np.random.randint(0, 180))
    transactions.append({"Date": date, "Merchant": merchant, "Amount": amount})

df = pd.DataFrame(transactions).sort_values("Date").reset_index(drop=True)
df.to_csv("transactions.csv", index=False)
print(f"Created {len(df)} transactions")

Step 3.Auto-categorise transactions

Keyword matching is simple but effective. You can expand the mapping over time.

CATEGORY_MAP = {}
for cat, merchants in categories.items():
    for m in merchants:
        CATEGORY_MAP[m] = cat

def categorise(merchant: str) -> str:
    merchant_upper = merchant.upper()
    for key, cat in CATEGORY_MAP.items():
        if key in merchant_upper:
            return cat
    return "Other"

df["Category"] = df["Merchant"].apply(categorise)
df["Month"] = df["Date"].dt.strftime("%Y-%m")

summary = df.groupby("Category")["Amount"].agg(["sum", "count", "mean"]).round(2)
summary.columns = ["Total", "Count", "Average"]
print(summary.sort_values("Total", ascending=False))

Step 4.Generate monthly breakdown

A pivot table gives you spending by category for each month.

monthly = df.pivot_table(
    index="Month", columns="Category",
    values="Amount", aggfunc="sum", fill_value=0
).round(2)

monthly["Total"] = monthly.sum(axis=1)
print("Monthly spending by category:")
print(monthly.to_string())
print(f"Total spending: pounds {df['Amount'].sum():,.2f}")

Step 5.Export to formatted Excel

The final Excel file has raw transactions, category summary, and monthly breakdown.

from openpyxl.styles import Font, PatternFill

with pd.ExcelWriter("budget_report.xlsx", engine="openpyxl") as writer:
    df.to_excel(writer, sheet_name="Transactions", index=False)
    summary.to_excel(writer, sheet_name="Summary")
    monthly.to_excel(writer, sheet_name="Monthly")

    for sheet_name in writer.sheets:
        ws = writer.sheets[sheet_name]
        for cell in ws[1]:
            cell.font = Font(bold=True, color="FFFFFF")
            cell.fill = PatternFill("solid", fgColor="1a1a2e")

print("Saved budget_report.xlsx with 3 sheets")

Expected Output

Created 100 transactions
             Total  Count  Average
Groceries  1245.30     22    56.60
Bills       982.15     18    54.56
Dining      876.40     21    41.73

Saved budget_report.xlsx with 3 sheets

Next Steps

  • Connect to your bank API (Plaid, TrueLayer)
  • Add budget targets and overspend alerts
  • Build a Streamlit dashboard for real-time tracking

Recommended Reading

Personal Finance Book

As an Amazon Associate we may earn from qualifying purchases.

Browse All Tutorials →

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.