Personal finance aggregator: Budgets - Part 15
~9 min read
Categorised spending answers "where did it go?". A budget answers the more useful question, "am I on track?". This post covers the Budgets page, built across five commits between 1 and 5 October, and extended in mid-October with a 50/30/20 view and a richer category page. Nearly all of it reuses machinery from post 12, which is the point - the interesting new decision is about time, not categories.
A month, but whose month?
A budget needs a period, and the obvious period is the calendar month. But post 13 already showed what calendar months do to this data, and more fundamentally, I don't get paid on the 1st. If money arrives on the 28th, "the month" that matters runs from one payday to the next. Spending on the 29th is the start of the next budget, not the tail of this one.
So the only setting the Budgets page needs is a pay day, stored in a single-row user_settings table (id is constrained to 1, defaulting to the 28th when no row exists). Each category also gets an optional budget amount via a new column on categories.
The pay-period maths is a small pure module, budgets.py, in the same spirit as categorization.py - logic with no database access. The one genuinely fiddly part is that not every month has a 28th, 29th, 30th or 31st:
def _clamp_to_month(year, month, day):
"""`day` as a real date in (year, month), pulled back to the last day of
that month if it's shorter than `day` (e.g. pay_day=31 in a 30-day
month, or in February)."""
last_day_of_month = calendar.monthrange(year, month)[1]
return date(year, month, min(day, last_day_of_month))
current_pay_period(pay_day, today) returns a half-open [start, end) interval: start is the most recent occurrence of the pay day on or before today, end is the same calculation one month later, both clamped. A pay day of 31 therefore still resolves to a real date every month. The API validates 1 <= pay_day <= 31, and the clamping function is what makes 31 a valid answer rather than a crash waiting for February.
Half-open intervals are worth noting. period_end is the first day of the next period, which makes [start, end) contiguous with the next one - no gap and no overlap. It also makes it a handy reference date, which the paging below uses.
The page: spend against budget
The first commit builds GET /api/budgets, which for the current pay period returns each non-transfer category with its budget and what's been spent. It follows the same recipe as the spending-by-category endpoint, and the docstring is explicit about the ordering: categorise the full history first (subscription detection needs it), and only then restrict to the period and drop transfers - "they're excluded from spending entirely, so they don't belong on a budget page either." Restricting before categorising would break the subscription heuristic, because a monthly charge only has one occurrence inside a single pay period.
Everything on the Budgets page is derived from these pieces already written - the categorisation pipeline, the transfer flag, the colour slots. A new feature built almost entirely from existing parts is the best evidence that earlier boundaries were drawn in the right places.
Drilling in
The next adds GET /api/budgets/{category}: one category's spending per day across the pay period, plus the matching transactions. The interesting function is spending_by_day(), whose docstring says it returns "one entry per day even when nothing was spent that day - so a bar chart built from this has no gaps in its x-axis." Zero-filling is a data-shaping decision best made on the server: the chart component stays a dumb renderer, and nothing downstream has to remember that a missing date means zero. Both endpoints derive their window from the same current_pay_period() call, so the overview and the drill-down can't disagree about which days count - the docstring says that's why the category rows link straight into it.
Paging through time
A third lets the page move between periods. The mechanism is neat: both endpoints gained an optional reference_date query parameter, defaulting to today, and the frontend pages by passing another period's start as the reference. Going forward uses the current period_end (which, being exclusive, is the first day of the next period); going back uses the day before period_start. The page keeps the reference date in the URL's ?ref= query string, so a period is a linkable, refresh-safe address. There's no "current page number" state to get out of sync with the data.
Another adds the comparison: each category also returns previous_spent - its spend in the pay period before - computed by running the same function on start - 1 day. The frontend turns that into a change arrow, and the colouring is the same lesson as post 5's stat tiles: for spending, down is good (green) and up is bad (red), regardless of the arrow's direction. A previous spend of exactly £0 renders no change at all, since "went from nothing" isn't a meaningful percentage - the code comment is candid that £0 is indistinguishable from "no data for that period".
Two fixes that came from using it
The last (Improve budget window and card spending) contains one display bug and one data bug, and the data bug is the more important.
The display bug: period_end is exclusive, so the "Tracking spending from X to Y" heading was off by a day - a period starting on the 28th was labelled as ending on the 28th of the next month, when its last day is the 27th. The fix is to display dayBefore(period_end). Exclusive end dates are right for computation and wrong for humans, so convert at the display edge.
The data bug is from post 11's unfinished business. I'd normalised card balances to this app's sign convention, but card transactions had the same problem and I'd missed it: they arrive as positive magnitudes with a transaction_type saying which way the money moved. As the new docstring puts it, "without this, card spend looks like income and never reaches the spending totals or budgets." The fix:
def _signed_amount(txn, kind):
amount = txn["amount"]
if kind != "cards":
return amount
magnitude = abs(amount)
return -magnitude if txn.get("transaction_type") == "DEBIT" else magnitude
The consequence is easy to see: a card purchase silently counted as income inflates "income" and understates spending, so a budget looks healthier than it is.
There's a second half that's easy to miss. Fixing the sign at fetch time doesn't fix the rows already stored, and save_transactions() uses INSERT OR IGNORE, which never touches existing rows. So the same commit adds a follow-up UPDATE transactions SET amount = :amount ... WHERE amount != :amount, whose comment says it "heals rows stored before card amounts were sign-normalised." A normalisation fix on a de-duplicating pipeline needs two parts: the corrected write path and a way to repair old data, because the de-dup that makes re-syncing safe also makes it a poor repair tool.
Income and the 50/30/20 split
Per-category budgets answer "is groceries on track?" but not "is the whole shape of my spending sensible?". For that the page gained a 50/30/20 view: of take-home income, roughly 50% should go on needs, 30% on wants and 20% on savings.
The model is one new column. Each category has an optional bucket - needs, wants, savings or income - and the starter categories are seeded with sensible ones (Bills, Groceries and Transport are needs; Eating out, Shopping and Subscriptions are wants). Settings gained a bucket selector on the category forms. As with the earlier columns, existing databases get an ALTER TABLE behind the usual PRAGMA table_info guard.
The calculation is split_50_30_20() in budgets.py, another pure function, and its docstring holds the decisions:
- A bucket beats the transfer flag. Moving money into a savings account is a transfer as far as the rest of the app is concerned and is excluded from spending. But for this view it is the savings. So the function is given the period's transactions with transfers still in, and a category's bucket takes priority over
is_transfer. A transfer in a category with no bucket stays excluded, as everywhere else. - Debits only for spending, credits only for income. A credit landing in a savings account mustn't cancel the debit that funded it, and income counts only credits in categories bucketed
income. The targets are fixed shares of that income. - Gaps stay visible.
unallocatedis income minus the three buckets (negative when overspent), andunbucketedis the other non-transfer spending, Uncategorised included, so categories you haven't assigned don't quietly skew the percentages.
There's a small API wrinkle worth recording. A category can be given a bucket or have one cleared, so on an update null has to mean "clear it", while leaving the field out has to mean "don't touch it". The route checks "bucket" in payload.model_fields_set to tell the two apart, and the storage function uses a private _UNSET sentinel for the same reason - None can't mean both.
On the page, a donut shows the split and each bucket is a row with its percentage of income against its target. The colouring encodes the direction of each target: needs and wants are ceilings, savings is a floor, so being over is bad for the first two and good for the last. Each row expands to list its categories, and where a category has a budget it reads "£120 of £150 budget" in green or red, so the two views of the same month agree. The main spend-versus-budget list also prints each category's budget under its name.
The category page, grown up
The drill-down from earlier started as a bar chart and a transaction list. It now opens with four stat tiles - total spend, budget used, last period's spend, and budget remaining - with the same "down is good" colouring as the rest of the page. To feed them, GET /api/budgets/{category} returns the category's budget, spent and previous_spent, the last computed by running the same period maths on start - 1 day as before. The transaction table gets a total row.
A second chart, "Spend per account", breaks the category down by where the money came from. spending_by_account() has a small wrinkle: transactions only carry their account's display name, so it matches against the account list on (bank, name) to recover the account's kind and alias, labels cards as "(card)", and falls back to the raw name if the account has since been removed.
Finally, the page can now move between periods itself instead of making you go back to the overview: Previous, Next and Current period buttons, driven by the same ?ref= query parameter as the overview. Both pages needed the same dayBefore() helper, so it moved out into period.ts rather than being copied.
Previous: ← Hargreaves Lansdown, with no API · Next: Savings projections →
