Skip to main content

flexpool_forecast/
model.rs

1//! Built-in models: conformalized seasonal naive forecasts.
2
3use 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
11/// The quantile levels every forecast carries.
12pub const LEVELS: [f64; 5] = [0.1, 0.25, 0.5, 0.75, 0.9];
13/// Days of errors the intervals are calibrated on.
14pub const WINDOW_DAYS: i64 = 28;
15/// Below this many errors in an hour, the hour borrows all hours' errors.
16const MIN_PER_HOUR: usize = 5;
17
18/// One market time unit's quantiles.
19#[derive(Debug, Clone, PartialEq, Serialize)]
20pub struct Interval {
21    /// Start (UTC).
22    #[serde(with = "time::serde::rfc3339")]
23    pub start: OffsetDateTime,
24    /// The 10, 25, 50, 75 and 90 % quantiles, €/MWh, non-decreasing.
25    pub q: [f64; 5],
26}
27
28/// A probabilistic forecast for one delivery day.
29#[derive(Debug, Clone, PartialEq, Serialize)]
30pub struct Forecast {
31    /// The delivery day.
32    pub day: Date,
33    /// The model.
34    pub model: String,
35    /// When it was issued — the instant of the view it read (or the server clock for submissions).
36    #[serde(with = "time::serde::rfc3339")]
37    pub issued_at: OffsetDateTime,
38    /// The market time unit, minutes.
39    pub minutes: u16,
40    /// One entry per market time unit of the day.
41    pub intervals: Vec<Interval>,
42}
43
44/// A built-in model.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
46pub enum Model {
47    /// The price at the same Berlin time one day earlier.
48    NaiveDay,
49    /// … seven days earlier — the reference.
50    NaiveWeek,
51    /// The mean of the two.
52    Blend,
53}
54
55impl Model {
56    /// Every built-in model.
57    pub const ALL: [Self; 3] = [Self::Blend, Self::NaiveDay, Self::NaiveWeek];
58
59    /// Its name.
60    #[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    /// Parses a built-in model name.
70    #[must_use]
71    pub fn parse(s: &str) -> Option<Self> {
72        Self::ALL.into_iter().find(|m| m.name() == s)
73    }
74
75    /// The point forecast for `t`, from prices known in `view`.
76    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/// Why no forecast can be made.
87#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
88pub enum NoForecast {
89    /// The prices it needs are not known at the issue time.
90    #[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/// The instant `days` days before `t` at the same Berlin wall-clock time. Across a DST switch the
102/// elapsed offset is corrected; a local time that does not exist (the skipped spring hour) falls
103/// back one hour.
104#[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    // The skipped hour: one hour earlier exists.
119    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
126/// The empirical `level` quantile of sorted `xs` (linear interpolation, type 7).
127fn 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/// The lag-1 autocorrelation of `model`'s errors over its calibration window before `day`, as known
143/// in `view`, converted to a step of `minutes` (for an AR(1) process ρ per step scales as ρ^(step ÷
144/// observed step), so hourly history serves quarter-hour days). Clipped to [0, 0.99]; `None` without
145/// enough history.
146#[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    // Adjacent pairs only, grouped by their step so that hourly and quarter-hourly history mix.
163    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
192/// The built-in `model`'s forecast for `day` with market time unit `minutes`, from prices known in
193/// `view` (its instant is the issue time).
194///
195/// # Errors
196/// [`NoForecast::NoHistory`] when the prices a point or the calibration needs are not known.
197pub fn builtin(
198    model: Model,
199    view: &View<'_>,
200    day: &BusinessDay,
201    minutes: u16,
202) -> Result<Forecast, NoForecast> {
203    // Errors of the model over the previous days, as known at the issue time, per local hour.
204    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}