use std::collections::BTreeMap;
use flexpool_core::BusinessDay;
use flexpool_sim::View;
use rust_decimal::prelude::ToPrimitive;
use serde::Serialize;
use time::{Date, Duration, OffsetDateTime, Time};
pub const LEVELS: [f64; 5] = [0.1, 0.25, 0.5, 0.75, 0.9];
pub const WINDOW_DAYS: i64 = 28;
const MIN_PER_HOUR: usize = 5;
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Interval {
#[serde(with = "time::serde::rfc3339")]
pub start: OffsetDateTime,
pub q: [f64; 5],
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Forecast {
pub day: Date,
pub model: String,
#[serde(with = "time::serde::rfc3339")]
pub issued_at: OffsetDateTime,
pub minutes: u16,
pub intervals: Vec<Interval>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Model {
NaiveDay,
NaiveWeek,
Blend,
}
impl Model {
pub const ALL: [Self; 3] = [Self::Blend, Self::NaiveDay, Self::NaiveWeek];
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::NaiveDay => "naive-day",
Self::NaiveWeek => "naive-week",
Self::Blend => "blend",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|m| m.name() == s)
}
fn point(self, view: &View<'_>, t: OffsetDateTime) -> Option<f64> {
let back = |days| same_local_time(t, days).and_then(|s| price(view, s));
match self {
Self::NaiveDay => back(1),
Self::NaiveWeek => back(7),
Self::Blend => Some(0.5 * (back(1)? + back(7)?)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum NoForecast {
#[error("not enough price history known at the issue time to forecast {0}")]
NoHistory(Date),
}
fn price(view: &View<'_>, t: OffsetDateTime) -> Option<f64> {
view.containing(t)
.ok()
.flatten()
.and_then(|o| o.value.value().to_f64())
}
#[must_use]
pub fn same_local_time(t: OffsetDateTime, days: i64) -> Option<OffsetDateTime> {
let local = flexpool_core::calendar::to_berlin(t);
let date = local.date().checked_sub(Duration::days(days))?;
let wanted = local.time();
let start = BusinessDay::new(date).ok()?.start();
let mut candidate = start + (wanted - Time::MIDNIGHT);
for _ in 0..2 {
let got = flexpool_core::calendar::to_berlin(candidate);
if got.date() == date && got.time() == wanted {
return Some(candidate);
}
candidate += (wanted - got.time()) + Duration::days((date - got.date()).whole_days());
}
Some(start + (wanted - Time::MIDNIGHT) - Duration::hours(1))
}
fn local_hour(t: OffsetDateTime) -> u8 {
flexpool_core::calendar::to_berlin(t).hour()
}
fn quantile(xs: &[f64], level: f64) -> f64 {
if xs.is_empty() {
return 0.0;
}
#[expect(clippy::cast_precision_loss, reason = "a few thousand errors at most")]
let pos = level * (xs.len() - 1) as f64;
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a non-negative index within the slice"
)]
let (lo, hi) = (pos.floor() as usize, pos.ceil() as usize);
xs[lo] + (xs[hi] - xs[lo]) * (pos - pos.floor())
}
#[must_use]
pub fn error_lag1(model: Model, view: &View<'_>, day: &BusinessDay, minutes: u16) -> Option<f64> {
let mut errors: Vec<(OffsetDateTime, u16, f64)> = Vec::new();
let mut date = day.date();
for _ in 0..WINDOW_DAYS {
date = date.previous_day()?;
let Ok(past) = BusinessDay::new(date) else {
break;
};
for o in view.range(past.start(), past.end()) {
if let (Some(y), Some(p)) = (o.value.value().to_f64(), model.point(view, o.start)) {
errors.push((o.start, o.minutes, y - p));
}
}
}
errors.sort_by_key(|e| e.0);
let mut pairs: BTreeMap<u16, Vec<(f64, f64)>> = BTreeMap::new();
for w in errors.windows(2) {
if w[0].0 + Duration::minutes(i64::from(w[0].1)) == w[1].0 && w[0].1 == w[1].1 {
pairs.entry(w[0].1).or_default().push((w[0].2, w[1].2));
}
}
let (step, xy) = pairs.into_iter().max_by_key(|(_, v)| v.len())?;
if xy.len() < 24 {
return None;
}
#[expect(clippy::cast_precision_loss, reason = "a few thousand pairs at most")]
let n = xy.len() as f64;
let (mx, my) = (
xy.iter().map(|p| p.0).sum::<f64>() / n,
xy.iter().map(|p| p.1).sum::<f64>() / n,
);
let cov: f64 = xy.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum();
let vx: f64 = xy.iter().map(|p| (p.0 - mx).powi(2)).sum();
let vy: f64 = xy.iter().map(|p| (p.1 - my).powi(2)).sum();
if vx <= 0.0 || vy <= 0.0 {
return None;
}
let r = (cov / (vx * vy).sqrt()).clamp(0.0, 0.99);
Some(
r.powf(f64::from(minutes) / f64::from(step))
.clamp(0.0, 0.99),
)
}
pub fn builtin(
model: Model,
view: &View<'_>,
day: &BusinessDay,
minutes: u16,
) -> Result<Forecast, NoForecast> {
let mut by_hour: BTreeMap<u8, Vec<f64>> = BTreeMap::new();
let mut date = day.date();
for _ in 0..WINDOW_DAYS {
let Some(earlier) = date.previous_day() else {
break;
};
date = earlier;
let Ok(past) = BusinessDay::new(date) else {
break;
};
for o in view.range(past.start(), past.end()) {
let (Some(y), Some(p)) = (o.value.value().to_f64(), model.point(view, o.start)) else {
continue;
};
by_hour.entry(local_hour(o.start)).or_default().push(y - p);
}
}
let mut pooled: Vec<f64> = by_hour.values().flatten().copied().collect();
if pooled.len() < 24 {
return Err(NoForecast::NoHistory(day.date()));
}
pooled.sort_by(f64::total_cmp);
for errors in by_hour.values_mut() {
errors.sort_by(f64::total_cmp);
}
let step = Duration::minutes(i64::from(minutes));
let mut intervals = Vec::new();
let mut start = day.start();
while start < day.end() {
let point = model
.point(view, start)
.ok_or(NoForecast::NoHistory(day.date()))?;
let errors = by_hour
.get(&local_hour(start))
.filter(|e| e.len() >= MIN_PER_HOUR)
.map_or(pooled.as_slice(), Vec::as_slice);
let q = LEVELS.map(|level| point + quantile(errors, level));
intervals.push(Interval { start, q });
start += step;
}
Ok(Forecast {
day: day.date(),
model: model.name().to_owned(),
issued_at: view.instant(),
minutes,
intervals,
})
}