flexpool-forecast 0.3.0

flexpool probabilistic day-ahead price forecasts: the quantile contract, conformalized seasonal baselines, pinball-loss scoring and a rolling-origin benchmark ladder. No I/O; reads history only through the bitemporal view.
Documentation
//! Built-in models: conformalized seasonal naive forecasts.

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};

/// The quantile levels every forecast carries.
pub const LEVELS: [f64; 5] = [0.1, 0.25, 0.5, 0.75, 0.9];
/// Days of errors the intervals are calibrated on.
pub const WINDOW_DAYS: i64 = 28;
/// Below this many errors in an hour, the hour borrows all hours' errors.
const MIN_PER_HOUR: usize = 5;

/// One market time unit's quantiles.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Interval {
    /// Start (UTC).
    #[serde(with = "time::serde::rfc3339")]
    pub start: OffsetDateTime,
    /// The 10, 25, 50, 75 and 90 % quantiles, €/MWh, non-decreasing.
    pub q: [f64; 5],
}

/// A probabilistic forecast for one delivery day.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Forecast {
    /// The delivery day.
    pub day: Date,
    /// The model.
    pub model: String,
    /// When it was issued — the instant of the view it read (or the server clock for submissions).
    #[serde(with = "time::serde::rfc3339")]
    pub issued_at: OffsetDateTime,
    /// The market time unit, minutes.
    pub minutes: u16,
    /// One entry per market time unit of the day.
    pub intervals: Vec<Interval>,
}

/// A built-in model.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Model {
    /// The price at the same Berlin time one day earlier.
    NaiveDay,
    /// … seven days earlier — the reference.
    NaiveWeek,
    /// The mean of the two.
    Blend,
}

impl Model {
    /// Every built-in model.
    pub const ALL: [Self; 3] = [Self::Blend, Self::NaiveDay, Self::NaiveWeek];

    /// Its name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::NaiveDay => "naive-day",
            Self::NaiveWeek => "naive-week",
            Self::Blend => "blend",
        }
    }

    /// Parses a built-in model name.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|m| m.name() == s)
    }

    /// The point forecast for `t`, from prices known in `view`.
    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)?)),
        }
    }
}

/// Why no forecast can be made.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum NoForecast {
    /// The prices it needs are not known at the issue time.
    #[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())
}

/// The instant `days` days before `t` at the same Berlin wall-clock time. Across a DST switch the
/// elapsed offset is corrected; a local time that does not exist (the skipped spring hour) falls
/// back one hour.
#[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());
    }
    // The skipped hour: one hour earlier exists.
    Some(start + (wanted - Time::MIDNIGHT) - Duration::hours(1))
}

fn local_hour(t: OffsetDateTime) -> u8 {
    flexpool_core::calendar::to_berlin(t).hour()
}

/// The empirical `level` quantile of sorted `xs` (linear interpolation, type 7).
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())
}

/// The lag-1 autocorrelation of `model`'s errors over its calibration window before `day`, as known
/// in `view`, converted to a step of `minutes` (for an AR(1) process ρ per step scales as ρ^(step ÷
/// observed step), so hourly history serves quarter-hour days). Clipped to [0, 0.99]; `None` without
/// enough history.
#[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);
    // Adjacent pairs only, grouped by their step so that hourly and quarter-hourly history mix.
    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),
    )
}

/// The built-in `model`'s forecast for `day` with market time unit `minutes`, from prices known in
/// `view` (its instant is the issue time).
///
/// # Errors
/// [`NoForecast::NoHistory`] when the prices a point or the calibration needs are not known.
pub fn builtin(
    model: Model,
    view: &View<'_>,
    day: &BusinessDay,
    minutes: u16,
) -> Result<Forecast, NoForecast> {
    // Errors of the model over the previous days, as known at the issue time, per local hour.
    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,
    })
}