This project builds a small expense tracker that you run from the terminal. You add expenses with a category, see a monthly report with a simple bar chart, and list your largest spending. It brings together several modules from this series: sqlite3 for storage, dataclasses and enum for clean data, Decimal for exact money, datetime for dates and argparse for commands.
In this project you will
- Model an expense with a frozen dataclass and a
StrEnum - Store money safely as whole paisa in SQLite
- Group and total expenses by month and category with SQL
- Build
add,reportandtopsubcommands with argparse - Reject bad input with validation
This project uses sqlite3, dataclasses, Enum, Decimal, datetime and argparse.
The Complete Program
"""Expense tracker: sqlite3 + dataclasses + enum + Decimal + argparse."""
import argparse
import sqlite3
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from enum import StrEnum
class Category(StrEnum):
FOOD = "food"
TRANSPORT = "transport"
BILLS = "bills"
EDUCATION = "education"
OTHER = "other"
@dataclass(frozen=True)
class Expense:
day: date
category: Category
amount: Decimal # taka, two decimal places
note: str = ""
def __post_init__(self):
if self.amount <= 0:
raise ValueError("amount must be positive")
class Tracker:
def __init__(self, path=":memory:"):
self.con = sqlite3.connect(path)
self.con.execute("""CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY, day TEXT, category TEXT,
paisa INTEGER, note TEXT)""")
def add(self, e: Expense) -> int:
paisa = int(e.amount * 100) # store money as whole paisa
with self.con:
cur = self.con.execute(
"INSERT INTO expenses (day, category, paisa, note) VALUES (?, ?, ?, ?)",
(e.day.isoformat(), e.category, paisa, e.note))
return cur.lastrowid
def month_total(self, year, month):
prefix = f"{year:04d}-{month:02d}-%"
rows = self.con.execute("""SELECT category, SUM(paisa) FROM expenses
WHERE day LIKE ? GROUP BY category
ORDER BY SUM(paisa) DESC""", (prefix,)).fetchall()
return [(Category(c), Decimal(p) / 100) for c, p in rows]
def largest(self, n=3):
rows = self.con.execute("""SELECT day, category, paisa, note FROM expenses
ORDER BY paisa DESC LIMIT ?""", (n,))
return [Expense(date.fromisoformat(d), Category(c), Decimal(p) / 100, note)
for d, c, p, note in rows]
def build_parser():
p = argparse.ArgumentParser(prog="expense")
sub = p.add_subparsers(dest="command", required=True)
add = sub.add_parser("add")
add.add_argument("amount", type=Decimal)
add.add_argument("category", choices=[c.value for c in Category])
add.add_argument("--day", type=date.fromisoformat, default=date(2026, 11, 1))
add.add_argument("--note", default="")
rep = sub.add_parser("report")
rep.add_argument("month", help="YYYY-MM")
sub.add_parser("top")
return p
def run(tracker, argv):
args = build_parser().parse_args(argv)
if args.command == "add":
e = Expense(args.day, Category(args.category), args.amount, args.note)
new_id = tracker.add(e)
print(f"#{new_id} {e.day} {e.category:<9} {e.amount:>9,.2f} {e.note}")
elif args.command == "report":
year, month = map(int, args.month.split("-"))
rows = tracker.month_total(year, month)
total = sum((amt for _, amt in rows), Decimal(0))
print(f"Report for {args.month}")
for cat, amt in rows:
bar = "#" * round(amt / total * 20)
print(f" {cat:<9} {amt:>9,.2f} {bar}")
print(f" {'TOTAL':<9} {total:>9,.2f}")
elif args.command == "top":
for e in tracker.largest():
print(f" {e.amount:>9,.2f} {e.category} {e.note}")
if __name__ == "__main__":
t = Tracker()
commands = [
"add 4500 bills --day 2026-11-02 --note electricity+gas",
"add 120.50 food --day 2026-11-02 --note lunch",
"add 60 transport --day 2026-11-03 --note rickshaw",
"add 2500 education --day 2026-11-05 --note coaching",
"add 845.75 food --day 2026-11-08 --note groceries",
"add 300 transport --day 2026-11-10 --note bus-pass",
"add 999 food --day 2026-10-28 --note last-month",
"report 2026-11",
"top",
]
for line in commands:
print("$ expense", line)
run(t, line.split())
try:
run(t, "add -50 food".split())
except ValueError as e:
print("rejected negative amount:", type(e).__name__)
Output
$ expense add 4500 bills --day 2026-11-02 --note electricity+gas
#1 2026-11-02 bills 4,500.00 electricity+gas
$ expense add 120.50 food --day 2026-11-02 --note lunch
#2 2026-11-02 food 120.50 lunch
$ expense add 60 transport --day 2026-11-03 --note rickshaw
#3 2026-11-03 transport 60.00 rickshaw
$ expense add 2500 education --day 2026-11-05 --note coaching
#4 2026-11-05 education 2,500.00 coaching
$ expense add 845.75 food --day 2026-11-08 --note groceries
#5 2026-11-08 food 845.75 groceries
$ expense add 300 transport --day 2026-11-10 --note bus-pass
#6 2026-11-10 transport 300.00 bus-pass
$ expense add 999 food --day 2026-10-28 --note last-month
#7 2026-10-28 food 999.00 last-month
$ expense report 2026-11
Report for 2026-11
bills 4,500.00 ###########
education 2,500.00 ######
food 966.25 ##
transport 360.00 #
TOTAL 8,326.25
$ expense top
4,500.00 bills electricity+gas
2,500.00 education coaching
999.00 food last-month
rejected negative amount: ValueError
So that the example always gives the same output, the program feeds a list of commands to run and uses an in-memory database. The next sections explain each part, and the end of the lesson shows how to turn it into a real command-line tool.
How It Works
1. The data model
Category is a StrEnum, so each category is a fixed choice, but its value is plain text that can go straight into the database. Expense is a frozen dataclass: its fields cannot change after creation, and __post_init__ refuses an amount that is zero or negative. That is why the last command, add -50 food, is rejected with a ValueError.
2. Storing money
Amounts arrive as Decimal, because argparse uses type=Decimal. Before saving, int(e.amount * 100) turns 120.50 taka into 12,050 paisa. Integers are exact in every database, so totals never drift. When reading back, Decimal(p) / 100 turns paisa into taka again.
3. Queries
Dates are stored as ISO text such as 2026-11-02, which sorts correctly as text. The monthly report uses WHERE day LIKE '2026-11-%' to select one month, then GROUP BY category with SUM(paisa) to total each category, largest first. The October expense of 999 taka is correctly left out of the November report. Every value is passed through a ? placeholder.
4. Commands
build_parser creates three subcommands. add takes an amount and a category, limited by choices to the enum’s values, plus optional --day and --note. type=date.fromisoformat turns text into a date and rejects impossible dates. run branches on args.command.
5. The report
Each category gets a bar of # characters proportional to its share of the month’s total, up to 20 characters. Bills are 4,500 of 8,326.25 taka, about 54%, so they get 11 characters. Format specs such as {amt:>9,.2f} right-align the numbers with thousands separators and two decimal places.
Making It a Real Tool
To use the tracker every day, change the bottom of the file so it reads the real command line and keeps its data in a file:
if __name__ == "__main__":
import sys
run(Tracker("expenses.db"), sys.argv[1:])
Also remove the fixed default date in build_parser and use default=date.today(). Then run commands such as python expense.py add 250 food --note dinner and python expense.py report 2026-11.
Taking It Further
- Add a
budgetcommand that warns when a category goes over a monthly limit. - Add
exportto write a month’s expenses to a CSV file with thecsvmodule. - Add a
delete IDcommand inside a transaction. - Write unit tests for
Trackerusing an in-memory database.
Common Mistakes in Projects Like This
- Storing money as float in the database. Use whole paisa (integers) or Decimal text.
- Storing dates as “02/11/2026”. That text does not sort by date; ISO format does.
- Keeping categories as free text, so “Food”, “food” and “fod” become three categories. An enum with
choicesprevents this. - Using
int(amount * 100)on more than two decimal places. It cuts off extra digits; round withquantizefirst if users may type 10.505.
Practice Exercises
Exercise 1. Add a Tracker.count() method that returns how many expenses are stored.
Show answer
def count(self):
return self.con.execute("SELECT COUNT(*) FROM expenses").fetchone()[0]
Exercise 2. Add a --category option to the top command so it lists the largest expenses in one category only.
Show answer
# in build_parser
top = sub.add_parser("top")
top.add_argument("--category", choices=[c.value for c in Category])
# in Tracker.largest(self, n=3, category=None)
sql = "SELECT day, category, paisa, note FROM expenses"
params = []
if category:
sql += " WHERE category = ?"
params.append(category)
sql += " ORDER BY paisa DESC LIMIT ?"
params.append(n)
rows = self.con.execute(sql, params)
# in run(), for the "top" command
for e in tracker.largest(category=args.category):
...
Frequently Asked Questions
Why not save the expenses in a JSON file?
JSON works for a few hundred records, but you must load and rewrite the whole file every time. SQLite updates only what changed, survives crashes better, and can total and group data with SQL.
Can I add a graphical window or a website later?
Yes. The Tracker class knows nothing about the command line, so a Tkinter window, a Flask website or a Telegram bot can call the same add and month_total methods.
Summary
- Keep data rules in the model: a frozen dataclass with validation and an enum for categories.
- Store money as integer paisa and dates as ISO text.
- Let SQL do the grouping and totals, always with placeholders.
- Keep the storage class separate from the command-line code so it can be reused.
