Ad – 728Γ—90
πŸ’° Projects

Python Expense Tracker

Track income and expenses by category, view monthly summaries, set budget limits, and export reports to CSV.

⏱️ 20 min read🎯 ProjectsπŸ“… Updated 2026

Complete Implementation

Python
import csv, json
from datetime import datetime
from pathlib import Path
from collections import defaultdict

DATA_FILE = Path("expenses.json")

class ExpenseTracker:
    def __init__(self):
        self.expenses, self.budgets = [], {}
        if DATA_FILE.exists():
            data = json.loads(DATA_FILE.read_text())
            self.expenses = data.get("expenses", [])
            self.budgets = data.get("budgets", {})

    def save(self):
        DATA_FILE.write_text(json.dumps({"expenses": self.expenses, "budgets": self.budgets}, indent=2))

    def add(self, amount, category, description, date=""):
        self.expenses.append({
            "id": len(self.expenses) + 1,
            "amount": amount, "category": category,
            "description": description,
            "date": date or datetime.now().strftime("%Y-%m-%d"),
        })
        self.save()

    def monthly_summary(self, year, month):
        totals = defaultdict(float)
        for e in self.expenses:
            y, m, _ = e["date"].split("-")
            if int(y) == year and int(m) == month:
                totals[e["category"]] += e["amount"]
        return dict(totals)

    def check_budget(self, year, month):
        summary = self.monthly_summary(year, month)
        return [
            f"OVER BUDGET {cat}: spent ${spent:.2f} / limit ${self.budgets[cat]:.2f}"
            for cat, spent in summary.items()
            if cat in self.budgets and spent > self.budgets[cat]
        ]

    def export_csv(self, filepath):
        with open(filepath, "w", newline="") as f:
            writer = csv.DictWriter(f, fieldnames=["id","date","category","amount","description"])
            writer.writeheader()
            writer.writerows(self.expenses)

# Demo
t = ExpenseTracker()
t.add(45.50, "Food", "Grocery")
t.add(120.00, "Housing", "Electricity")
t.budgets["Food"] = 300.00

now = datetime.now()
for cat, total in t.monthly_summary(now.year, now.month).items():
    print(f"{cat}: ${total:.2f}")
for alert in t.check_budget(now.year, now.month):
    print(alert)
t.export_csv("expenses.csv")
Tip: Add a matplotlib bar chart of monthly spending per category β€” turns this into a data visualization project too.