1"""Expense Tracker: record expenses, set budgets, see monthly reports and save to JSON.
2
3Commands:
4 add <amount> <category> <YYYY-MM-DD> [note...]
5 list [YYYY-MM]
6 delete <id>
7 budget <category> <monthly-amount>
8 report <YYYY-MM> totals by category against budgets
9 trend total per month
10 save <file.json> / load <file.json>
11 quit
12Categories: food, travel, rent, bills, shopping, health, other.
13"""
14import json
15import os
16import sys
17from dataclasses import asdict, dataclass
18from datetime import date
19from pathlib import Path
20
21CATEGORIES = ("food", "travel", "rent", "bills", "shopping", "health", "other")
22
23
24class TrackerError(Exception):
25 pass
26
27
28@dataclass
29class Expense:
30 id: int
31 amount: float
32 category: str
33 day: str
34 note: str = ""
35
36 @property
37 def month(self) -> str:
38 return self.day[:7]
39
40
41def ask(prompt: str) -> str | None:
42 try:
43 line = input(prompt)
44 except EOFError:
45 print()
46 return None
47 if not sys.stdin.isatty():
48 print(line)
49 return line.strip()
50
51
52def parse_amount(text: str) -> float:
53 try:
54 value = float(text.replace(",", ""))
55 except ValueError:
56 raise TrackerError(f"'{text}' is not an amount") from None
57 if value <= 0:
58 raise TrackerError("amount must be positive")
59 return round(value, 2)
60
61
62def parse_category(text: str) -> str:
63 if text.lower() not in CATEGORIES:
64 raise TrackerError(f"category must be one of: {', '.join(CATEGORIES)}")
65 return text.lower()
66
67
68def parse_day(text: str) -> str:
69 try:
70 return date.fromisoformat(text).isoformat()
71 except ValueError:
72 raise TrackerError(f"'{text}' is not a date (YYYY-MM-DD)") from None
73
74
75class Tracker:
76 def __init__(self):
77 self.expenses: list[Expense] = []
78 self.budgets: dict[str, float] = {}
79 self.next_id = 1
80
81 def add(self, amount: str, category: str, day: str, note: str) -> Expense:
82 expense = Expense(self.next_id, parse_amount(amount), parse_category(category), parse_day(day), note)
83 self.expenses.append(expense)
84 self.next_id += 1
85 return expense
86
87 def spent(self, month: str, category: str | None = None) -> float:
88 return round(sum(e.amount for e in self.expenses if e.month == month and category in (None, e.category)), 2)
89
90 def save(self, path: Path) -> None:
91 data = {"version": 1, "next_id": self.next_id, "budgets": self.budgets,
92 "expenses": [asdict(e) for e in self.expenses]}
93 tmp = path.with_suffix(".tmp")
94 tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
95 os.replace(tmp, path)
96
97 def load(self, path: Path) -> None:
98 try:
99 data = json.loads(path.read_text(encoding="utf-8"))
100 except FileNotFoundError:
101 raise TrackerError(f"{path} does not exist") from None
102 except json.JSONDecodeError as error:
103 raise TrackerError(f"{path} is not valid JSON (line {error.lineno})") from None
104 self.expenses = [Expense(**e) for e in data["expenses"]]
105 self.budgets = data["budgets"]
106 self.next_id = data["next_id"]
107
108
109def report(t: Tracker, month: str) -> None:
110 total = t.spent(month)
111 if total == 0:
112 print(f" No expenses in {month}.")
113 return
114 print(f" {'Category':<10}{'Spent':>10}{'Budget':>10} Status")
115 for category in CATEGORIES:
116 spent, budget = t.spent(month, category), t.budgets.get(category)
117 if not spent and budget is None:
118 continue
119 if budget is None:
120 status = ""
121 elif spent > budget:
122 status = f"OVER by {spent - budget:,.2f}"
123 else:
124 status = f"{spent / budget:.0%} used"
125 print(f" {category:<10}{spent:>10,.2f}{(f'{budget:,.2f}' if budget is not None else '-'):>10} {status}".rstrip())
126 print(f" {'total':<10}{total:>10,.2f}")
127 biggest = max((e for e in t.expenses if e.month == month), key=lambda e: e.amount)
128 print(f" Largest: {biggest.amount:,.2f} on {biggest.day} ({biggest.category}{', ' + biggest.note if biggest.note else ''})")
129
130
131def run(t: Tracker, words: list[str]) -> None:
132 command = words[0].lower()
133 if command == "add":
134 e = t.add(words[1], words[2], words[3], " ".join(words[4:]))
135 print(f"Added #{e.id}: {e.amount:,.2f} {e.category} on {e.day}")
136 budget = t.budgets.get(e.category)
137 if budget is not None and t.spent(e.month, e.category) > budget:
138 print(f" Warning: {e.category} is over its {budget:,.2f} budget for {e.month}.")
139 elif command == "list":
140 month = words[1] if len(words) > 1 else None
141 shown = [e for e in t.expenses if month in (None, e.month)]
142 for e in sorted(shown, key=lambda e: (e.day, e.id)):
143 print(f" #{e.id:<3}{e.day} {e.category:<9}{e.amount:>10,.2f} {e.note}".rstrip())
144 print(f" {len(shown)} expense(s), total {sum(e.amount for e in shown):,.2f}")
145 elif command == "delete":
146 match = [e for e in t.expenses if str(e.id) == words[1]]
147 if not match:
148 raise TrackerError(f"no expense #{words[1]}")
149 t.expenses.remove(match[0])
150 print(f"Deleted #{match[0].id}")
151 elif command == "budget":
152 category, amount = parse_category(words[1]), parse_amount(words[2])
153 t.budgets[category] = amount
154 print(f"Budget for {category}: {amount:,.2f} per month")
155 elif command == "report":
156 report(t, words[1])
157 elif command == "trend":
158 months = sorted({e.month for e in t.expenses})
159 top = max((t.spent(m) for m in months), default=0)
160 for m in months:
161 print(f" {m} {t.spent(m):>10,.2f} {'#' * round(20 * t.spent(m) / top)}")
162 elif command == "save":
163 t.save(Path(words[1]))
164 print(f"Saved {len(t.expenses)} expenses to {words[1]}")
165 elif command == "load":
166 t.load(Path(words[1]))
167 print(f"Loaded {len(t.expenses)} expenses and {len(t.budgets)} budgets from {words[1]}")
168 else:
169 raise TrackerError("unknown command")
170
171
172def main() -> None:
173 tracker = Tracker()
174 print("Expense Tracker")
175 while True:
176 line = ask("> ")
177 if line is None or line.lower() == "quit":
178 break
179 if not line:
180 continue
181 try:
182 run(tracker, line.split())
183 except TrackerError as error:
184 print(f"Error: {error}")
185 except IndexError:
186 print("Error: missing arguments for that command")
187
188
189if __name__ == "__main__":
190 main()