Skip to content
Python project #13Intermediate

Expense Tracker

Record expenses by category and date, set monthly budgets, get over-budget warnings and reports, and save everything to JSON safely.

Estimated time
~4 hours to build
Files
4 files · 379 lines
Technologies
Python 3, json, dataclasses, pathlib, os.replace

Introduction

This is the running example from the 'Building Real Python Applications' module turned into a complete program: validated input, a service class, budget rules, reports and JSON persistence with an atomic save.

Problem statement

Add expenses with an amount, a category from a fixed list, an ISO date and an optional note. Set monthly budgets per category and warn when spending goes over. List expenses for a month, delete by id, print a monthly report against budgets with the largest expense, show a month-by-month trend chart, and save to or load from a JSON file. Reject invalid amounts, categories and dates, and report missing or corrupt files.

Objectives

  • Validate input at the boundary
  • Persist data with JSON and an atomic save
  • Group and total data by month and category
  • Structure an application into functions and a service class

Features

  • Validated amounts, categories and dates
  • Monthly budgets with warnings
  • Monthly report and trend chart
  • Delete by id
  • Atomic JSON save and safe load

Concepts demonstrated

  • Input validation
  • Persistence
  • Aggregation
  • Application structure

System architecture

Parsing helpers validate each field and raise TrackerError. Tracker holds Expense dataclasses and budgets; spent totals by month and category. save writes a versioned JSON document to a temporary file and replaces the real file with os.replace, so a crash never leaves half a file. load rebuilds expenses with Expense(**item) and turns JSON errors into friendly messages.

Folder structure

TextProject tree
expense-tracker/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

191 lines
Pythonmain.py
"""Expense Tracker: record expenses, set budgets, see monthly reports and save to JSON.
Commands:
add <amount> <category> <YYYY-MM-DD> [note...]
list [YYYY-MM]
delete <id>
budget <category> <monthly-amount>
report <YYYY-MM> totals by category against budgets
trend total per month
save <file.json> / load <file.json>
quit
Categories: food, travel, rent, bills, shopping, health, other.
"""
import json
import os
import sys
from dataclasses import asdict, dataclass
from datetime import date
from pathlib import Path
CATEGORIES = ("food", "travel", "rent", "bills", "shopping", "health", "other")
class TrackerError(Exception):
pass
@dataclass
class Expense:
id: int
amount: float
category: str
day: str # ISO date, kept as text so it serialises to JSON directly
note: str = ""
@property
def month(self) -> str:
return self.day[:7]
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
def parse_amount(text: str) -> float:
try:
value = float(text.replace(",", ""))
except ValueError:
raise TrackerError(f"'{text}' is not an amount") from None
if value <= 0:
raise TrackerError("amount must be positive")
return round(value, 2)
def parse_category(text: str) -> str:
if text.lower() not in CATEGORIES:
raise TrackerError(f"category must be one of: {', '.join(CATEGORIES)}")
return text.lower()
def parse_day(text: str) -> str:
try:
return date.fromisoformat(text).isoformat()
except ValueError:
raise TrackerError(f"'{text}' is not a date (YYYY-MM-DD)") from None
class Tracker:
def __init__(self):
self.expenses: list[Expense] = []
self.budgets: dict[str, float] = {}
self.next_id = 1
def add(self, amount: str, category: str, day: str, note: str) -> Expense:
expense = Expense(self.next_id, parse_amount(amount), parse_category(category), parse_day(day), note)
self.expenses.append(expense)
self.next_id += 1
return expense
def spent(self, month: str, category: str | None = None) -> float:
return round(sum(e.amount for e in self.expenses if e.month == month and category in (None, e.category)), 2)
def save(self, path: Path) -> None:
data = {"version": 1, "next_id": self.next_id, "budgets": self.budgets,
"expenses": [asdict(e) for e in self.expenses]}
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
os.replace(tmp, path) # never leaves a half-written file behind
def load(self, path: Path) -> None:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
raise TrackerError(f"{path} does not exist") from None
except json.JSONDecodeError as error:
raise TrackerError(f"{path} is not valid JSON (line {error.lineno})") from None
self.expenses = [Expense(**e) for e in data["expenses"]]
self.budgets = data["budgets"]
self.next_id = data["next_id"]
def report(t: Tracker, month: str) -> None:
total = t.spent(month)
if total == 0:
print(f" No expenses in {month}.")
return
print(f" {'Category':<10}{'Spent':>10}{'Budget':>10} Status")
for category in CATEGORIES:
spent, budget = t.spent(month, category), t.budgets.get(category)
if not spent and budget is None:
continue
if budget is None:
status = ""
elif spent > budget:
status = f"OVER by {spent - budget:,.2f}"
else:
status = f"{spent / budget:.0%} used"
print(f" {category:<10}{spent:>10,.2f}{(f'{budget:,.2f}' if budget is not None else '-'):>10} {status}".rstrip())
print(f" {'total':<10}{total:>10,.2f}")
biggest = max((e for e in t.expenses if e.month == month), key=lambda e: e.amount)
print(f" Largest: {biggest.amount:,.2f} on {biggest.day} ({biggest.category}{', ' + biggest.note if biggest.note else ''})")
def run(t: Tracker, words: list[str]) -> None:
command = words[0].lower()
if command == "add":
e = t.add(words[1], words[2], words[3], " ".join(words[4:]))
print(f"Added #{e.id}: {e.amount:,.2f} {e.category} on {e.day}")
budget = t.budgets.get(e.category)
if budget is not None and t.spent(e.month, e.category) > budget:
print(f" Warning: {e.category} is over its {budget:,.2f} budget for {e.month}.")
elif command == "list":
month = words[1] if len(words) > 1 else None
shown = [e for e in t.expenses if month in (None, e.month)]
for e in sorted(shown, key=lambda e: (e.day, e.id)):
print(f" #{e.id:<3}{e.day} {e.category:<9}{e.amount:>10,.2f} {e.note}".rstrip())
print(f" {len(shown)} expense(s), total {sum(e.amount for e in shown):,.2f}")
elif command == "delete":
match = [e for e in t.expenses if str(e.id) == words[1]]
if not match:
raise TrackerError(f"no expense #{words[1]}")
t.expenses.remove(match[0])
print(f"Deleted #{match[0].id}")
elif command == "budget":
category, amount = parse_category(words[1]), parse_amount(words[2])
t.budgets[category] = amount
print(f"Budget for {category}: {amount:,.2f} per month")
elif command == "report":
report(t, words[1])
elif command == "trend":
months = sorted({e.month for e in t.expenses})
top = max((t.spent(m) for m in months), default=0)
for m in months:
print(f" {m} {t.spent(m):>10,.2f} {'#' * round(20 * t.spent(m) / top)}")
elif command == "save":
t.save(Path(words[1]))
print(f"Saved {len(t.expenses)} expenses to {words[1]}")
elif command == "load":
t.load(Path(words[1]))
print(f"Loaded {len(t.expenses)} expenses and {len(t.budgets)} budgets from {words[1]}")
else:
raise TrackerError("unknown command")
def main() -> None:
tracker = Tracker()
print("Expense Tracker")
while True:
line = ask("> ")
if line is None or line.lower() == "quit":
break
if not line:
continue
try:
run(tracker, line.split())
except TrackerError as error:
print(f"Error: {error}")
except IndexError:
print("Error: missing arguments for that command")
if __name__ == "__main__":
main()

What each file does

main.py
Validation helpers, the Expense dataclass, the Tracker service with JSON persistence, reports and the command loop.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Expense Tracker
> budget food 3000
Budget for food: 3,000.00 per month
> budget travel 1500
Budget for travel: 1,500.00 per month
> add 250 food 2026-10-03 lunch
Added #1: 250.00 food on 2026-10-03
> add 9000 rent 2026-10-01
Added #2: 9,000.00 rent on 2026-10-01
> add 1200 travel 2026-10-12 train
Added #3: 1,200.00 travel on 2026-10-12
> add 450.75 food 2026-11-02 groceries
Added #4: 450.75 food on 2026-11-02
> add 1800 travel 2026-11-05 flight top-up
Added #5: 1,800.00 travel on 2026-11-05
Warning: travel is over its 1,500.00 budget for 2026-11.
> add 2600 food 2026-11-18 party
Added #6: 2,600.00 food on 2026-11-18
Warning: food is over its 3,000.00 budget for 2026-11.
> add 300 games 2026-11-19
Error: category must be one of: food, travel, rent, bills, shopping, health, other
> add -40 food 2026-11-20
Error: amount must be positive
> add 99 food 27/11/2026
Error: '27/11/2026' is not a date (YYYY-MM-DD)
> add 9000 rent 2026-11-01
Added #7: 9,000.00 rent on 2026-11-01
> list 2026-11
#7 2026-11-01 rent 9,000.00
#4 2026-11-02 food 450.75 groceries
#5 2026-11-05 travel 1,800.00 flight top-up
#6 2026-11-18 food 2,600.00 party
4 expense(s), total 13,850.75
> report 2026-11
Category Spent Budget Status
food 3,050.75 3,000.00 OVER by 50.75
travel 1,800.00 1,500.00 OVER by 300.00
rent 9,000.00 -
total 13,850.75
Largest: 9,000.00 on 2026-11-01 (rent)
> delete 2
Deleted #2
> delete 42
Error: no expense #42
> trend
2026-10 1,450.00 ##
2026-11 13,850.75 ####################
> save expenses.json
Saved 6 expenses to expenses.json
> load expenses.json
Loaded 6 expenses and 2 budgets from expenses.json
> load missing.json
Error: missing.json does not exist
> report 2026-10
Category Spent Budget Status
food 250.00 3,000.00 8% used
travel 1,200.00 1,500.00 80% used
total 1,450.00
Largest: 1,200.00 on 2026-10-12 (travel, train)
> quit
Input
budget food 3000
budget travel 1500
add 250 food 2026-10-03 lunch
add 9000 rent 2026-10-01
add 1200 travel 2026-10-12 train
add 450.75 food 2026-11-02 groceries
add 1800 travel 2026-11-05 flight top-up
add 2600 food 2026-11-18 party
add 300 games 2026-11-19
add -40 food 2026-11-20
add 99 food 27/11/2026
add 9000 rent 2026-11-01
list 2026-11
report 2026-11
delete 2
delete 42
trend
save expenses.json
load expenses.json
load missing.json
report 2026-10
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • The ₹1,800 flight puts November travel over its ₹1,500 budget, and the party puts food over ₹3,000.
  • An unknown category, a negative amount and a date in DD/MM/YYYY format are rejected.
  • After saving and reloading, the October report shows food at 8% and travel at 80% of budget.

Common errors

A crash during save corrupts the data file

Write to a temporary file and os.replace() it over the original.

TypeError: Object of type date is not JSON serializable

Store dates as ISO strings, as the Expense.day field does.

Possible improvements

  • Load the data file automatically on start-up
  • Export a month to CSV
  • Add recurring expenses such as rent

Additional challenges

  1. 1Add an 'edit <id> amount|category|note <value>' command.
  2. 2Show the average daily spending for a month.
  3. 3Predict end-of-month spending from the days so far.

Built and tested it yourself? Mark it to update your dashboard.