//! The month-end forecast: a seeded bootstrap Monte Carlo over past daily spending, integers only. //! Same inputs and seed → the same output, on every machine. use crate::subscriptions::{Insight, Status}; use fiscus_ledger::{Date, Haler, State}; use serde::{Deserialize, Serialize}; /// Days of history the forecast draws from. pub const HISTORY_DAYS: i32 = 90; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ForecastInput { /// Spending (positive) on each past day; a day with nothing is a zero. pub history: Vec, /// Spent so far this month. pub spent: Haler, /// Days after today until the month ends. pub days_left: u32, pub limit: Haler, /// Known charges still due this month (subscriptions). pub known: Haler, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Forecast { /// The chance to stay at or under the limit, in basis points (10 000 = certain). pub chance_bp: u32, pub p10: Haler, pub p50: Haler, pub p90: Haler, pub runs: u32, pub history_days: u32, } /// xoshiro256** seeded through SplitMix64: small, fast, and fixed here so no dependency can change it. struct Rng([u64; 4]); impl Rng { fn new(seed: u64) -> Rng { let mut x = seed; let mut next = || { x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); let mut z = x; z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); z ^ (z >> 31) }; Rng([next(), next(), next(), next()]) } fn next(&mut self) -> u64 { let s = &mut self.0; let result = s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9); let t = s[1] << 17; s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3]; s[2] ^= t; s[3] = s[3].rotate_left(45); result } /// Uniform in `0..n` without modulo bias (Lemire). fn below(&mut self, n: u64) -> u64 { let threshold = n.wrapping_neg() % n; loop { let m = (self.next() as u128) * (n as u128); if (m as u64) >= threshold { return (m >> 64) as u64; } } } } pub fn forecast(input: &ForecastInput, seed: u64, runs: u32) -> Forecast { let runs = runs.max(1); let base = input.spent.0.saturating_add(input.known.0); let mut rng = Rng::new(seed); let mut ends: Vec = (0..runs) .map(|_| { let mut total = base; if !input.history.is_empty() { for _ in 0..input.days_left { let i = rng.below(input.history.len() as u64) as usize; total = total.saturating_add(input.history[i].0); } } total }) .collect(); ends.sort_unstable(); let under = ends.iter().filter(|e| **e <= input.limit.0).count() as u64; let at = |pct: usize| Haler(ends[(ends.len() - 1) * pct / 100]); Forecast { chance_bp: (under * 10_000 / runs as u64) as u32, p10: at(10), p50: at(50), p90: at(90), runs, history_days: input.history.len() as u32, } } /// The forecast for one budget this month. Subscription charges are taken out of the history and added back /// as known charges on their due dates, so they are neither missed nor counted twice. pub fn budget_forecast(state: &State, insight: &Insight, budget: &str, today: Date, seed: u64, runs: u32) -> Option { let limit = state.budgets.get(budget)?.limit; let subscription_payments: std::collections::BTreeSet<&str> = insight.subscriptions.iter().flat_map(|s| s.charges.iter().map(|c| c.payment.as_str())).collect(); let mine: Vec<_> = state .effective_payments() .into_iter() .filter(|p| p.budget.as_deref() == Some(budget) && p.amount.0 < 0) .collect(); let cost = |p: &fiscus_ledger::EffectivePayment| -p.amount.0; let month_start = today.month_start(); let spent = Haler(mine.iter().filter(|p| p.date >= month_start && p.date <= today).map(cost).sum()); let first = mine.iter().map(|p| p.date).min(); let window_start = match first { Some(f) if f > today.add_days(-HISTORY_DAYS) => f, _ => today.add_days(-HISTORY_DAYS), }; let days = window_start.days_until(today).max(0) as usize; // days before today let mut history = vec![0i64; days]; for p in mine.iter().filter(|p| !subscription_payments.contains(p.id.as_str())) { let i = window_start.days_until(p.date); if i >= 0 && (i as usize) < days { history[i as usize] += cost(p); } } let month_end = today.month_end(); let known = Haler( insight .subscriptions .iter() .filter(|s| s.status == Status::Active && s.budget.as_deref() == Some(budget)) .filter(|s| s.next_charge > today && s.next_charge <= month_end) .map(|s| s.cost.0) .sum(), ); let input = ForecastInput { history: history.into_iter().map(Haler).collect(), spent, days_left: today.days_until(month_end).max(0) as u32, limit, known, }; Some(forecast(&input, seed, runs)) }