flexpool-forecast 0.2.1

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
//! Scoring: the pinball loss per quantile, interval coverage, and the benchmark ladder.

use flexpool_core::BusinessDay;
use flexpool_rules::RuleBook;
use flexpool_sim::Series;
use rust_decimal::prelude::ToPrimitive;
use serde::Serialize;
use time::{Date, OffsetDateTime};

use crate::model::{Forecast, LEVELS, Model, builtin};

/// The reference model for skill.
pub const REFERENCE: Model = Model::NaiveWeek;

/// The pinball (quantile) loss of quantile `q` at level `tau` for the outcome `y`.
#[must_use]
pub fn pinball(y: f64, q: f64, tau: f64) -> f64 {
    let d = y - q;
    (tau * d).max((tau - 1.0) * d)
}

/// One model on one day.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DayScore {
    /// The delivery day.
    pub day: Date,
    /// Mean pinball loss over intervals and levels (≈ CRPS / 2), €/MWh; lower is better.
    pub quantile_score: f64,
    /// Share of intervals with q10 ≤ price ≤ q90.
    pub coverage80: f64,
    /// Share with q25 ≤ price ≤ q75.
    pub coverage50: f64,
    /// Mean |price − median|, €/MWh.
    pub mae: f64,
}

/// Scores `forecast` against the prices `actual` gives per interval start.
#[must_use]
pub fn score(
    forecast: &Forecast,
    actual: &dyn Fn(OffsetDateTime) -> Option<f64>,
) -> Option<DayScore> {
    let (mut qs, mut c80, mut c50, mut mae, mut n) = (0.0, 0, 0, 0.0, 0_u32);
    for i in &forecast.intervals {
        let Some(y) = actual(i.start) else { continue };
        n += 1;
        qs += LEVELS
            .iter()
            .zip(i.q)
            .map(|(tau, q)| pinball(y, q, *tau))
            .sum::<f64>()
            / LEVELS.len() as f64;
        c80 += u32::from(i.q[0] <= y && y <= i.q[4]);
        c50 += u32::from(i.q[1] <= y && y <= i.q[3]);
        mae += (y - i.q[2]).abs();
    }
    (n > 0).then(|| {
        let n = f64::from(n);
        DayScore {
            day: forecast.day,
            quantile_score: qs / n,
            coverage80: f64::from(c80) / n,
            coverage50: f64::from(c50) / n,
            mae: mae / n,
        }
    })
}

/// One model over the ladder's window.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct LadderRow {
    /// The model.
    pub model: String,
    /// Built-in or submitted.
    pub builtin: bool,
    /// Days scored.
    pub days: usize,
    /// Mean quantile score, €/MWh.
    pub quantile_score: f64,
    /// 1 − score / reference score over the same days; `None` without reference days.
    pub skill: Option<f64>,
    /// Mean 80 % coverage.
    pub coverage80: f64,
    /// Mean 50 % coverage.
    pub coverage50: f64,
    /// Mean absolute error of the median, €/MWh.
    pub mae: f64,
    /// Per-day scores, oldest first.
    pub scores: Vec<DayScore>,
}

/// Models ranked by quantile score over the last delivery days with known prices.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Ladder {
    /// The reference model.
    pub reference: String,
    /// The delivery days scored, oldest first.
    pub days: Vec<Date>,
    /// Rows, best first.
    pub rows: Vec<LadderRow>,
}

impl Ladder {
    /// Backtests the built-ins (each day as of its own day-ahead gate) and scores the latest
    /// gate-valid submission of each external model, over the last `window` delivery days whose
    /// prices are known at `now`.
    #[must_use]
    pub fn compute(
        series: &Series,
        rules: &RuleBook,
        now: OffsetDateTime,
        window: usize,
        external: &[(String, Vec<Forecast>)],
    ) -> Self {
        let known = series.at(now);
        let actual = |t: OffsetDateTime| {
            known
                .containing(t)
                .ok()
                .flatten()
                .and_then(|o| o.value.value().to_f64())
        };
        // Delivery days with published prices, newest first, from tomorrow backwards.
        let mut days = Vec::new();
        let mut date = flexpool_core::calendar::to_berlin(now).date().next_day();
        for _ in 0..(window + 10) {
            let Some(d) = date else { break };
            if let Ok(b) = BusinessDay::new(d)
                && !known.range(b.start(), b.end()).is_empty()
            {
                days.push(b);
                if days.len() == window {
                    break;
                }
            }
            date = d.previous_day();
        }
        days.reverse();
        let gate = |d: &BusinessDay| rules.gate("da.gate", d.date()).ok().map(|(g, _)| g);
        let mut rows: Vec<LadderRow> = Vec::new();
        let mut reference: Vec<DayScore> = Vec::new();
        for model in Model::ALL {
            let scores: Vec<DayScore> = days
                .iter()
                .filter_map(|d| {
                    let (minutes, _) = rules.da_mtu(d.date()).ok()?;
                    let f = builtin(model, &series.at(gate(d)?), d, minutes).ok()?;
                    score(&f, &actual)
                })
                .collect();
            if model == REFERENCE {
                reference.clone_from(&scores);
            }
            rows.push(row(model.name(), true, scores));
        }
        for (name, versions) in external {
            let scores: Vec<DayScore> = days
                .iter()
                .filter_map(|d| {
                    let g = gate(d)?;
                    let f = versions
                        .iter()
                        .filter(|f| f.day == d.date() && f.issued_at <= g)
                        .max_by_key(|f| f.issued_at)?;
                    score(f, &actual)
                })
                .collect();
            rows.push(row(name, false, scores));
        }
        for r in &mut rows {
            let reference: Vec<&DayScore> = reference
                .iter()
                .filter(|s| r.scores.iter().any(|x| x.day == s.day))
                .collect();
            if !reference.is_empty() && r.days > 0 {
                #[expect(clippy::cast_precision_loss, reason = "a handful of days")]
                let ref_qs = reference.iter().map(|s| s.quantile_score).sum::<f64>()
                    / reference.len() as f64;
                r.skill = (ref_qs > 0.0).then(|| 1.0 - r.quantile_score / ref_qs);
            }
        }
        rows.sort_by(|a, b| {
            (a.days == 0)
                .cmp(&(b.days == 0))
                .then(a.quantile_score.total_cmp(&b.quantile_score))
        });
        Self {
            reference: REFERENCE.name().to_owned(),
            days: days.iter().map(BusinessDay::date).collect(),
            rows,
        }
    }
}

fn row(model: &str, builtin: bool, scores: Vec<DayScore>) -> LadderRow {
    #[expect(clippy::cast_precision_loss, reason = "a handful of days")]
    let n = scores.len().max(1) as f64;
    let mean = |f: fn(&DayScore) -> f64| scores.iter().map(f).sum::<f64>() / n;
    LadderRow {
        model: model.to_owned(),
        builtin,
        days: scores.len(),
        quantile_score: mean(|s| s.quantile_score),
        skill: None,
        coverage80: mean(|s| s.coverage80),
        coverage50: mean(|s| s.coverage50),
        mae: mean(|s| s.mae),
        scores,
    }
}