1use std::collections::BTreeMap;
4
5use flexpool_core::BusinessDay;
6use flexpool_sim::View;
7use rust_decimal::prelude::ToPrimitive;
8use serde::Serialize;
9use time::{Date, Duration, OffsetDateTime, Time};
10
11pub const LEVELS: [f64; 5] = [0.1, 0.25, 0.5, 0.75, 0.9];
13pub const WINDOW_DAYS: i64 = 28;
15const MIN_PER_HOUR: usize = 5;
17
18#[derive(Debug, Clone, PartialEq, Serialize)]
20pub struct Interval {
21 #[serde(with = "time::serde::rfc3339")]
23 pub start: OffsetDateTime,
24 pub q: [f64; 5],
26}
27
28#[derive(Debug, Clone, PartialEq, Serialize)]
30pub struct Forecast {
31 pub day: Date,
33 pub model: String,
35 #[serde(with = "time::serde::rfc3339")]
37 pub issued_at: OffsetDateTime,
38 pub minutes: u16,
40 pub intervals: Vec<Interval>,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
46pub enum Model {
47 NaiveDay,
49 NaiveWeek,
51 Blend,
53}
54
55impl Model {
56 pub const ALL: [Self; 3] = [Self::Blend, Self::NaiveDay, Self::NaiveWeek];
58
59 #[must_use]
61 pub const fn name(self) -> &'static str {
62 match self {
63 Self::NaiveDay => "naive-day",
64 Self::NaiveWeek => "naive-week",
65 Self::Blend => "blend",
66 }
67 }
68
69 #[must_use]
71 pub fn parse(s: &str) -> Option<Self> {
72 Self::ALL.into_iter().find(|m| m.name() == s)
73 }
74
75 fn point(self, view: &View<'_>, t: OffsetDateTime) -> Option<f64> {
77 let back = |days| same_local_time(t, days).and_then(|s| price(view, s));
78 match self {
79 Self::NaiveDay => back(1),
80 Self::NaiveWeek => back(7),
81 Self::Blend => Some(0.5 * (back(1)? + back(7)?)),
82 }
83 }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
88pub enum NoForecast {
89 #[error("not enough price history known at the issue time to forecast {0}")]
91 NoHistory(Date),
92}
93
94fn price(view: &View<'_>, t: OffsetDateTime) -> Option<f64> {
95 view.containing(t)
96 .ok()
97 .flatten()
98 .and_then(|o| o.value.value().to_f64())
99}
100
101#[must_use]
105pub fn same_local_time(t: OffsetDateTime, days: i64) -> Option<OffsetDateTime> {
106 let local = flexpool_core::calendar::to_berlin(t);
107 let date = local.date().checked_sub(Duration::days(days))?;
108 let wanted = local.time();
109 let start = BusinessDay::new(date).ok()?.start();
110 let mut candidate = start + (wanted - Time::MIDNIGHT);
111 for _ in 0..2 {
112 let got = flexpool_core::calendar::to_berlin(candidate);
113 if got.date() == date && got.time() == wanted {
114 return Some(candidate);
115 }
116 candidate += (wanted - got.time()) + Duration::days((date - got.date()).whole_days());
117 }
118 Some(start + (wanted - Time::MIDNIGHT) - Duration::hours(1))
120}
121
122fn local_hour(t: OffsetDateTime) -> u8 {
123 flexpool_core::calendar::to_berlin(t).hour()
124}
125
126fn quantile(xs: &[f64], level: f64) -> f64 {
128 if xs.is_empty() {
129 return 0.0;
130 }
131 #[expect(clippy::cast_precision_loss, reason = "a few thousand errors at most")]
132 let pos = level * (xs.len() - 1) as f64;
133 #[expect(
134 clippy::cast_possible_truncation,
135 clippy::cast_sign_loss,
136 reason = "a non-negative index within the slice"
137 )]
138 let (lo, hi) = (pos.floor() as usize, pos.ceil() as usize);
139 xs[lo] + (xs[hi] - xs[lo]) * (pos - pos.floor())
140}
141
142#[must_use]
147pub fn error_lag1(model: Model, view: &View<'_>, day: &BusinessDay, minutes: u16) -> Option<f64> {
148 let mut errors: Vec<(OffsetDateTime, u16, f64)> = Vec::new();
149 let mut date = day.date();
150 for _ in 0..WINDOW_DAYS {
151 date = date.previous_day()?;
152 let Ok(past) = BusinessDay::new(date) else {
153 break;
154 };
155 for o in view.range(past.start(), past.end()) {
156 if let (Some(y), Some(p)) = (o.value.value().to_f64(), model.point(view, o.start)) {
157 errors.push((o.start, o.minutes, y - p));
158 }
159 }
160 }
161 errors.sort_by_key(|e| e.0);
162 let mut pairs: BTreeMap<u16, Vec<(f64, f64)>> = BTreeMap::new();
164 for w in errors.windows(2) {
165 if w[0].0 + Duration::minutes(i64::from(w[0].1)) == w[1].0 && w[0].1 == w[1].1 {
166 pairs.entry(w[0].1).or_default().push((w[0].2, w[1].2));
167 }
168 }
169 let (step, xy) = pairs.into_iter().max_by_key(|(_, v)| v.len())?;
170 if xy.len() < 24 {
171 return None;
172 }
173 #[expect(clippy::cast_precision_loss, reason = "a few thousand pairs at most")]
174 let n = xy.len() as f64;
175 let (mx, my) = (
176 xy.iter().map(|p| p.0).sum::<f64>() / n,
177 xy.iter().map(|p| p.1).sum::<f64>() / n,
178 );
179 let cov: f64 = xy.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum();
180 let vx: f64 = xy.iter().map(|p| (p.0 - mx).powi(2)).sum();
181 let vy: f64 = xy.iter().map(|p| (p.1 - my).powi(2)).sum();
182 if vx <= 0.0 || vy <= 0.0 {
183 return None;
184 }
185 let r = (cov / (vx * vy).sqrt()).clamp(0.0, 0.99);
186 Some(
187 r.powf(f64::from(minutes) / f64::from(step))
188 .clamp(0.0, 0.99),
189 )
190}
191
192pub fn builtin(
198 model: Model,
199 view: &View<'_>,
200 day: &BusinessDay,
201 minutes: u16,
202) -> Result<Forecast, NoForecast> {
203 let mut by_hour: BTreeMap<u8, Vec<f64>> = BTreeMap::new();
205 let mut date = day.date();
206 for _ in 0..WINDOW_DAYS {
207 let Some(earlier) = date.previous_day() else {
208 break;
209 };
210 date = earlier;
211 let Ok(past) = BusinessDay::new(date) else {
212 break;
213 };
214 for o in view.range(past.start(), past.end()) {
215 let (Some(y), Some(p)) = (o.value.value().to_f64(), model.point(view, o.start)) else {
216 continue;
217 };
218 by_hour.entry(local_hour(o.start)).or_default().push(y - p);
219 }
220 }
221 let mut pooled: Vec<f64> = by_hour.values().flatten().copied().collect();
222 if pooled.len() < 24 {
223 return Err(NoForecast::NoHistory(day.date()));
224 }
225 pooled.sort_by(f64::total_cmp);
226 for errors in by_hour.values_mut() {
227 errors.sort_by(f64::total_cmp);
228 }
229 let step = Duration::minutes(i64::from(minutes));
230 let mut intervals = Vec::new();
231 let mut start = day.start();
232 while start < day.end() {
233 let point = model
234 .point(view, start)
235 .ok_or(NoForecast::NoHistory(day.date()))?;
236 let errors = by_hour
237 .get(&local_hour(start))
238 .filter(|e| e.len() >= MIN_PER_HOUR)
239 .map_or(pooled.as_slice(), Vec::as_slice);
240 let q = LEVELS.map(|level| point + quantile(errors, level));
241 intervals.push(Interval { start, q });
242 start += step;
243 }
244 Ok(Forecast {
245 day: day.date(),
246 model: model.name().to_owned(),
247 issued_at: view.instant(),
248 minutes,
249 intervals,
250 })
251}