Branchwell

Bucksley / app · bucksley.ai / Sources / BucksleyKit / SmartBudget.swift

Raw 9.1 KB on 07e410940d4dd3ce1e1e51286babef75b272eb4f
1import Foundation
2
3/// A whole budget plan built from your own recent spending and income: one recommended amount for each
4/// category you spend in. Fixed spending you can't easily change (rent, insurance, utilities and the like)
5/// is budgeted at what you actually spend and never cut. Flexible spending is set a little under what you
6/// spend now, and trimmed a bit more when the plan runs past your savings goal.
7public struct SmartBudgetPlan: Sendable, Hashable {
8 public struct Item: Identifiable, Sendable, Hashable {
9 public let categoryID: String
10 public let name: String
11 public let fixed: Bool
12 /// The average of the last few full months.
13 public let typical: Decimal
14 public let recommended: Decimal
15 /// The budget already set for this category, if any.
16 public let current: Decimal?
17 public let reason: String
18 public var id: String { categoryID }
19 }
20
21 public let months: Int
22 /// A typical month of income, or zero when there's none on record.
23 public let income: Decimal
24 /// A typical month of spending across the categories in the plan.
25 public let typicalSpending: Decimal
26 public let savingsRate: Int
27 public let items: [Item]
28
29 public var total: Decimal { items.reduce(0) { $0 + $1.recommended } }
30 public var savingsGoal: Decimal { (income * Decimal(savingsRate) / 100).rounded(0) }
31 /// What's left each month if every budget is met.
32 public var leftOver: Decimal { income - total }
33 public var fixedItems: [Item] { items.filter(\.fixed) }
34 public var flexible: [Item] { items.filter { !$0.fixed } }
35
36 /// Plain-language coaching for the plan, a few sentences.
37 public var summary: String {
38 guard !items.isEmpty else { return "There isn't a full month of spending yet, so there's nothing to base budgets on." }
39 var lines: [String] = []
40 if income > 0 {
41 lines.append("You bring in about \(Money.format(income, cents: false)) a month and have recently spent \(Money.format(typicalSpending, cents: false)) a month across these categories.")
42 lines.append("This plan budgets \(Money.format(total, cents: false)) a month, which leaves \(Money.format(leftOver, cents: false)) against a \(savingsRate)% savings goal of \(Money.format(savingsGoal, cents: false)).")
43 if leftOver < savingsGoal {
44 lines.append("Even with flexible spending trimmed, the goal is out of reach. The biggest lever is \(biggestFlexible?.name ?? "your largest category").")
45 }
46 } else {
47 lines.append("There's no income on record yet, so the plan follows your recent spending without a savings goal.")
48 }
49 if !fixedItems.isEmpty {
50 lines.append("Fixed bills (" + fixedItems.map(\.name).joined(separator: ", ") + ") are budgeted at what you spend.")
51 }
52 return lines.joined(separator: " ")
53 }
54
55 var biggestFlexible: Item? { flexible.max { $0.typical < $1.typical } }
56
57 /// Saves the chosen items as budgets. Other budgets stay, and a category's rollover setting is kept.
58 public static func apply(_ items: [Item], amounts: [String: Decimal] = [:], to workspace: inout Workspace, month: String = MonthKey.current) {
59 for item in items {
60 let amount = amounts[item.categoryID] ?? item.recommended
61 guard amount > 0 else { continue }
62 let rollover = workspace.budgets.first { $0.categoryID == item.categoryID }?.rollover ?? false
63 workspace.budgets.removeAll { $0.categoryID == item.categoryID }
64 workspace.budgets.append(Budget(categoryID: item.categoryID, amount: amount, rollover: rollover, startMonth: month))
65 }
66 }
67}
68
69public extension Ledger {
70 /// How many recent full months a plan averages: enough to smooth one odd month, recent enough to
71 /// follow how you spend now.
72 static let recentMonths = 3
73
74 /// Average spending in a category over the last few full months, and how many months that covers.
75 func recentSpending(_ categoryID: String, today: String = DayKey.today) -> (average: Decimal, months: Int) {
76 let months = recentFullMonths(today: today)
77 guard !months.isEmpty else { return (0, 0) }
78 let total = months.reduce(Decimal(0)) { $0 + spent(categoryID, month: $1) }
79 return ((total / Decimal(months.count)).rounded(0), months.count)
80 }
81
82 func recentFullMonths(today: String = DayKey.today) -> [String] {
83 let thisMonth = MonthKey.of(today)
84 let earliest = entries.map(\.day).min().map(MonthKey.of) ?? thisMonth
85 return (1...Self.recentMonths).map { MonthKey.adding(-$0, to: thisMonth) }.filter { $0 >= earliest }
86 }
87
88 /// The starting budget for a category: fixed spending at what you spend, flexible spending about 8%
89 /// under, rounded to a friendly number that stays below what you spend.
90 static func startingBudget(_ average: Decimal, fixed: Bool) -> Decimal {
91 if fixed { return friendly(average) }
92 let nearest = friendlyNearest(average * Decimal(string: "0.92")!)
93 return Swift.max(nearest < average ? nearest : friendlyDown(average * Decimal(string: "0.92")!), 5)
94 }
95
96 static func friendlyNearest(_ value: Decimal) -> Decimal {
97 let v = value.double
98 guard v > 0 else { return 0 }
99 let step: Double = v < 50 ? 5 : v < 200 ? 10 : v < 1000 ? 25 : 50
100 return Decimal((v / step).rounded() * step)
101 }
102
103 /// Builds a plan from the last full months. `savingsRate` is the share of income to keep free.
104 func smartBudgetPlan(savingsRate: Int = 20, today: String = DayKey.today) -> SmartBudgetPlan {
105 let months = recentFullMonths(today: today)
106 let rate = Swift.min(Swift.max(savingsRate, 0), 60)
107 guard !months.isEmpty else { return SmartBudgetPlan(months: 0, income: 0, typicalSpending: 0, savingsRate: rate, items: []) }
108 let income = (months.reduce(Decimal(0)) { $0 + self.income(month: $1) } / Decimal(months.count)).rounded(0)
109
110 struct Draft { let category: Category; let fixed: Bool; let typical: Decimal; var amount: Decimal }
111 var drafts: [Draft] = workspace.categories.filter { $0.kind == .expense && !isCoveredByGroupBudget($0.id) }.compactMap { category in
112 let typical = recentSpending(category.id, today: today).average
113 // Under $10 a month isn't worth a budget.
114 guard typical >= 10 else { return nil }
115 return Draft(category: category, fixed: category.isFixed, typical: typical, amount: Ledger.startingBudget(typical, fixed: category.isFixed))
116 }
117
118 // Past the savings goal, trim the big flexible categories a little more, largest first, never below
119 // 80% of what's spent now. Small categories barely move the goal, so they stay just under what's
120 // spent, and fixed spending is never cut.
121 var trimmed: Set<String> = []
122 if income > 0 {
123 let room = income - (income * Decimal(rate) / 100)
124 var over = drafts.reduce(Decimal(0)) { $0 + $1.amount } - room
125 for i in drafts.indices.sorted(by: { drafts[$0].typical > drafts[$1].typical }) where over > 0 && !drafts[i].fixed && drafts[i].typical >= 200 {
126 let floor = Swift.max(Ledger.friendly(drafts[i].typical * Decimal(string: "0.8")!), 5)
127 let target = Swift.max(Ledger.friendlyDown(drafts[i].amount - over), floor)
128 guard target < drafts[i].amount else { continue }
129 over -= drafts[i].amount - target
130 trimmed.insert(drafts[i].category.id)
131 drafts[i].amount = target
132 }
133 }
134
135 let span = months.count == 1 ? "Last month" : "The last \(months.count) months averaged"
136 let items = drafts.map { d -> SmartBudgetPlan.Item in
137 let current = workspace.budgets.first { $0.categoryID == d.category.id }?.amount
138 let typical = Money.format(d.typical, cents: false)
139 let reason: String
140 if d.fixed {
141 reason = "\(span) \(typical). This is a bill you can't easily change, so the budget matches it."
142 } else if trimmed.contains(d.category.id) {
143 reason = "\(span) \(typical). Set to \(Money.format(d.amount, cents: false)) to make room for your savings goal."
144 } else {
145 reason = "\(span) \(typical). Set a little under that so it nudges you to spend less."
146 }
147 return .init(categoryID: d.category.id, name: d.category.name, fixed: d.fixed, typical: d.typical,
148 recommended: d.amount, current: current, reason: reason)
149 }
150 .sorted { ($0.fixed ? 0 : 1, -$0.typical.double) < ($1.fixed ? 0 : 1, -$1.typical.double) }
151
152 return SmartBudgetPlan(months: months.count, income: income, typicalSpending: drafts.reduce(0) { $0 + $1.typical },
153 savingsRate: rate, items: items)
154 }
155
156 /// Like `friendly`, but rounds down so a trim stays a trim.
157 static func friendlyDown(_ value: Decimal) -> Decimal {
158 let v = value.double
159 guard v > 0 else { return 0 }
160 let step: Double = v < 50 ? 5 : v < 200 ? 10 : v < 1000 ? 25 : 50
161 return Decimal((v / step).rounded(.down) * step)
162 }
163}