CodeForFinance
PythonBeginner

Build a Budget App with Python

Track your personal finances with a Python budget tracker. Add income and expenses, categorise spending, and generate visual reports. All data saved to JSON so nothing is lost.

Install Dependencies

pip install pandas matplotlib

The BudgetTracker Class

We build a class that saves transactions to a JSON file, supports income and expenses with categories, and generates summaries.

import pandas as pd
from datetime import datetime
import json

class BudgetTracker:
    def __init__(self, filename="budget.json"):
        self.filename = filename
        self.transactions = self._load()

    def _load(self):
        try:
            with open(self.filename, "r") as f:
                return json.load(f)
        except FileNotFoundError:
            return []

    def _save(self):
        with open(self.filename, "w") as f:
            json.dump(self.transactions, f, indent=2)

    def add_income(self, amount: float, description: str, category: str = "Salary"):
        self.transactions.append({
            "date": datetime.now().strftime("%Y-%m-%d"),
            "type": "income",
            "amount": amount,
            "description": description,
            "category": category
        })
        self._save()
        print(f"Added income: £{amount:.2f} ({description})")

    def add_expense(self, amount: float, description: str, category: str):
        self.transactions.append({
            "date": datetime.now().strftime("%Y-%m-%d"),
            "type": "expense",
            "amount": amount,
            "description": description,
            "category": category
        })
        self._save()
        print(f"Added expense: £{amount:.2f} ({description})")

Summary and Usage

    def summary(self) -> dict:
        df = pd.DataFrame(self.transactions)
        if df.empty:
            return {"income": 0, "expenses": 0, "balance": 0}

        income = df[df["type"] == "income"]["amount"].sum()
        expenses = df[df["type"] == "expense"]["amount"].sum()

        return {
            "income": income,
            "expenses": expenses,
            "balance": income - expenses,
            "by_category": df[df["type"] == "expense"].groupby("category")["amount"].sum().to_dict()
        }

# Usage
budget = BudgetTracker()
budget.add_income(3500, "Monthly salary")
budget.add_expense(1200, "Rent", "Housing")
budget.add_expense(300, "Groceries", "Food")
budget.add_expense(80, "Electric bill", "Utilities")
budget.add_expense(50, "Netflix + Spotify", "Entertainment")
budget.add_expense(150, "Petrol", "Transport")

report = budget.summary()
print(f"\nIncome: £{report['income']:.2f}")
print(f"Expenses: £{report['expenses']:.2f}")
print(f"Balance: £{report['balance']:.2f}")
print(f"\nSpending by category:")
for cat, amount in report['by_category'].items():
    print(f"  {cat}: £{amount:.2f}")

Visualise Your Budget

# Visualise spending
import matplotlib.pyplot as plt

categories = list(report["by_category"].keys())
amounts = list(report["by_category"].values())

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# Pie chart
ax1.pie(amounts, labels=categories, autopct="%1.0f%%", startangle=90)
ax1.set_title("Spending Breakdown")

# Income vs Expenses bar
ax2.bar(["Income", "Expenses", "Savings"],
        [report["income"], report["expenses"], report["balance"]],
        color=["green", "red", "blue"])
ax2.set_title("Monthly Summary")
ax2.set_ylabel("£")

plt.tight_layout()
plt.savefig("budget_report.png", dpi=150)
plt.show()

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.