Coverage for app / services / budgets / forecast.py: 96%

51 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2What a budget will have spent when its period ends, if spending goes on as it 

3has (cost-control plan, A1.2). 

4 

5A projection, and it says so: the period's spend so far, plus the trailing 

6week's daily rate for each day left. The range around it is that rate's own 

7spread — one standard deviation of a day's spend, which for the sum of N 

8more days is the daily deviation times √N — so a steady workspace gets a 

9narrow range and a bursty one a wide one. 

10 

11Two things it will not do: 

12 

13- **Project a trailing window.** A rolling cap never ends; it frees up as 

14 old spend drops out. Only a calendar period (day, week, month) has an end 

15 to project to. 

16- **Project from too little.** Under three complete days of spending history 

17 a daily rate is a guess, and a confident figure from a guess is worse than 

18 none (``not_enough_history``). 

19 

20Pure arithmetic over figures the usage window reads, so it is pinned by 

21tests without a database (``tests/test_budgets.py``). 

22""" 

23 

24from __future__ import annotations 

25 

26import math 

27from dataclasses import dataclass 

28from datetime import date, datetime, timedelta 

29from decimal import Decimal 

30from enum import StrEnum 

31 

32#: Complete days the daily rate is taken over. 

33TRAILING_DAYS = 7 

34#: Complete days of spending history a projection needs. 

35MIN_HISTORY_DAYS = 3 

36 

37 

38class Unavailable(StrEnum): 

39 """Why a budget has no forecast.""" 

40 

41 #: A trailing window: it has no end to project to. 

42 trailing_window = "trailing_window" 

43 #: Fewer than ``MIN_HISTORY_DAYS`` complete days of spending. 

44 not_enough_history = "not_enough_history" 

45 #: The ledger could not be read. 

46 unreadable = "unreadable" 

47 

48 

49UNAVAILABLE_NOTES = { 

50 Unavailable.trailing_window: "A trailing window has no end to project to.", 

51 Unavailable.not_enough_history: ( 

52 f"Needs {MIN_HISTORY_DAYS} complete days of spending to project from." 

53 ), 

54 Unavailable.unreadable: "The spending history could not be read.", 

55} 

56 

57 

58@dataclass(frozen=True) 

59class Forecast: 

60 """A projection of a period's spend at its end, or why there is none.""" 

61 

62 unavailable: Unavailable | None = None 

63 projected_usd: Decimal | None = None 

64 low_usd: Decimal | None = None 

65 high_usd: Decimal | None = None 

66 #: The trailing days' mean spend per day. 

67 daily_rate_usd: Decimal | None = None 

68 #: How many complete days the rate was taken over. 

69 days_used: int = 0 

70 #: When the cap would be reached at that rate, if before the period ends. 

71 reaches_cap_at: datetime | None = None 

72 

73 @property 

74 def available(self) -> bool: 

75 return self.unavailable is None 

76 

77 

78def trailing_days(now: datetime, days: int = TRAILING_DAYS) -> list[date]: 

79 """The ``days`` complete UTC days before ``now``'s, oldest first.""" 

80 today = now.date() 

81 return [today - timedelta(days=n) for n in range(days, 0, -1)] 

82 

83 

84def project( 

85 *, 

86 spent: Decimal | None, 

87 daily: dict[date, Decimal] | None, 

88 first_spent_at: datetime | None, 

89 now: datetime, 

90 resets_at: datetime | None, 

91 cap: Decimal | None = None, 

92) -> Forecast: 

93 """``spent`` so far this period, projected to ``resets_at``. 

94 

95 ``daily`` is spend by UTC day over at least the trailing week (days with 

96 none absent); ``first_spent_at`` when the population first spent anything 

97 — how much history there is. 

98 """ 

99 if resets_at is None: 

100 return Forecast(unavailable=Unavailable.trailing_window) 

101 if spent is None or daily is None: 

102 return Forecast(unavailable=Unavailable.unreadable) 

103 if first_spent_at is None: 

104 return Forecast(unavailable=Unavailable.not_enough_history) 

105 history = (now.date() - first_spent_at.date()).days 

106 if history < MIN_HISTORY_DAYS: 

107 return Forecast(unavailable=Unavailable.not_enough_history) 

108 

109 used = min(TRAILING_DAYS, history) 

110 values = [daily.get(day, Decimal(0)) for day in trailing_days(now, used)] 

111 rate = sum(values, Decimal(0)) / used 

112 deviation = ( 

113 Decimal( 

114 str( 

115 math.sqrt(sum(float(v - rate) ** 2 for v in values) / (len(values) - 1)) 

116 ) 

117 ) 

118 if len(values) > 1 

119 else Decimal(0) 

120 ) 

121 days_left = Decimal(str(max((resets_at - now).total_seconds(), 0) / 86_400)) 

122 projected = spent + rate * days_left 

123 spread = deviation * Decimal(str(math.sqrt(float(days_left)))) 

124 

125 reaches = None 

126 if cap is not None and spent < cap and rate > 0: 

127 at = now + timedelta(days=float((cap - spent) / rate)) 

128 if at < resets_at: 

129 reaches = at 

130 return Forecast( 

131 projected_usd=projected, 

132 low_usd=max(spent, projected - spread), 

133 high_usd=projected + spread, 

134 daily_rate_usd=rate, 

135 days_used=used, 

136 reaches_cap_at=reaches, 

137 )