Skip to main content

flexpool_forecast/
score.rs

1//! Scoring: the pinball loss per quantile, interval coverage, and the benchmark ladder.
2
3use flexpool_core::BusinessDay;
4use flexpool_rules::RuleBook;
5use flexpool_sim::Series;
6use rust_decimal::prelude::ToPrimitive;
7use serde::Serialize;
8use time::{Date, OffsetDateTime};
9
10use crate::model::{Forecast, LEVELS, Model, builtin};
11
12/// The reference model for skill.
13pub const REFERENCE: Model = Model::NaiveWeek;
14
15/// The pinball (quantile) loss of quantile `q` at level `tau` for the outcome `y`.
16#[must_use]
17pub fn pinball(y: f64, q: f64, tau: f64) -> f64 {
18    let d = y - q;
19    (tau * d).max((tau - 1.0) * d)
20}
21
22/// One model on one day.
23#[derive(Debug, Clone, PartialEq, Serialize)]
24pub struct DayScore {
25    /// The delivery day.
26    pub day: Date,
27    /// Mean pinball loss over intervals and levels (≈ CRPS / 2), €/MWh; lower is better.
28    pub quantile_score: f64,
29    /// Share of intervals with q10 ≤ price ≤ q90.
30    pub coverage80: f64,
31    /// Share with q25 ≤ price ≤ q75.
32    pub coverage50: f64,
33    /// Mean |price − median|, €/MWh.
34    pub mae: f64,
35}
36
37/// Scores `forecast` against the prices `actual` gives per interval start.
38#[must_use]
39pub fn score(
40    forecast: &Forecast,
41    actual: &dyn Fn(OffsetDateTime) -> Option<f64>,
42) -> Option<DayScore> {
43    let (mut qs, mut c80, mut c50, mut mae, mut n) = (0.0, 0, 0, 0.0, 0_u32);
44    for i in &forecast.intervals {
45        let Some(y) = actual(i.start) else { continue };
46        n += 1;
47        qs += LEVELS
48            .iter()
49            .zip(i.q)
50            .map(|(tau, q)| pinball(y, q, *tau))
51            .sum::<f64>()
52            / LEVELS.len() as f64;
53        c80 += u32::from(i.q[0] <= y && y <= i.q[4]);
54        c50 += u32::from(i.q[1] <= y && y <= i.q[3]);
55        mae += (y - i.q[2]).abs();
56    }
57    (n > 0).then(|| {
58        let n = f64::from(n);
59        DayScore {
60            day: forecast.day,
61            quantile_score: qs / n,
62            coverage80: f64::from(c80) / n,
63            coverage50: f64::from(c50) / n,
64            mae: mae / n,
65        }
66    })
67}
68
69/// One model over the ladder's window.
70#[derive(Debug, Clone, PartialEq, Serialize)]
71pub struct LadderRow {
72    /// The model.
73    pub model: String,
74    /// Built-in or submitted.
75    pub builtin: bool,
76    /// Days scored.
77    pub days: usize,
78    /// Mean quantile score, €/MWh.
79    pub quantile_score: f64,
80    /// 1 − score / reference score over the same days; `None` without reference days.
81    pub skill: Option<f64>,
82    /// Mean 80 % coverage.
83    pub coverage80: f64,
84    /// Mean 50 % coverage.
85    pub coverage50: f64,
86    /// Mean absolute error of the median, €/MWh.
87    pub mae: f64,
88    /// Per-day scores, oldest first.
89    pub scores: Vec<DayScore>,
90}
91
92/// Models ranked by quantile score over the last delivery days with known prices.
93#[derive(Debug, Clone, PartialEq, Serialize)]
94pub struct Ladder {
95    /// The reference model.
96    pub reference: String,
97    /// The delivery days scored, oldest first.
98    pub days: Vec<Date>,
99    /// Rows, best first.
100    pub rows: Vec<LadderRow>,
101}
102
103impl Ladder {
104    /// Backtests the built-ins (each day as of its own day-ahead gate) and scores the latest
105    /// gate-valid submission of each external model, over the last `window` delivery days whose
106    /// prices are known at `now`.
107    #[must_use]
108    pub fn compute(
109        series: &Series,
110        rules: &RuleBook,
111        now: OffsetDateTime,
112        window: usize,
113        external: &[(String, Vec<Forecast>)],
114    ) -> Self {
115        let known = series.at(now);
116        let actual = |t: OffsetDateTime| {
117            known
118                .containing(t)
119                .ok()
120                .flatten()
121                .and_then(|o| o.value.value().to_f64())
122        };
123        // Delivery days with published prices, newest first, from tomorrow backwards.
124        let mut days = Vec::new();
125        let mut date = flexpool_core::calendar::to_berlin(now).date().next_day();
126        for _ in 0..(window + 10) {
127            let Some(d) = date else { break };
128            if let Ok(b) = BusinessDay::new(d)
129                && !known.range(b.start(), b.end()).is_empty()
130            {
131                days.push(b);
132                if days.len() == window {
133                    break;
134                }
135            }
136            date = d.previous_day();
137        }
138        days.reverse();
139        let gate = |d: &BusinessDay| rules.gate("da.gate", d.date()).ok().map(|(g, _)| g);
140        let mut rows: Vec<LadderRow> = Vec::new();
141        let mut reference: Vec<DayScore> = Vec::new();
142        for model in Model::ALL {
143            let scores: Vec<DayScore> = days
144                .iter()
145                .filter_map(|d| {
146                    let (minutes, _) = rules.da_mtu(d.date()).ok()?;
147                    let f = builtin(model, &series.at(gate(d)?), d, minutes).ok()?;
148                    score(&f, &actual)
149                })
150                .collect();
151            if model == REFERENCE {
152                reference.clone_from(&scores);
153            }
154            rows.push(row(model.name(), true, scores));
155        }
156        for (name, versions) in external {
157            let scores: Vec<DayScore> = days
158                .iter()
159                .filter_map(|d| {
160                    let g = gate(d)?;
161                    let f = versions
162                        .iter()
163                        .filter(|f| f.day == d.date() && f.issued_at <= g)
164                        .max_by_key(|f| f.issued_at)?;
165                    score(f, &actual)
166                })
167                .collect();
168            rows.push(row(name, false, scores));
169        }
170        for r in &mut rows {
171            let reference: Vec<&DayScore> = reference
172                .iter()
173                .filter(|s| r.scores.iter().any(|x| x.day == s.day))
174                .collect();
175            if !reference.is_empty() && r.days > 0 {
176                #[expect(clippy::cast_precision_loss, reason = "a handful of days")]
177                let ref_qs = reference.iter().map(|s| s.quantile_score).sum::<f64>()
178                    / reference.len() as f64;
179                r.skill = (ref_qs > 0.0).then(|| 1.0 - r.quantile_score / ref_qs);
180            }
181        }
182        rows.sort_by(|a, b| {
183            (a.days == 0)
184                .cmp(&(b.days == 0))
185                .then(a.quantile_score.total_cmp(&b.quantile_score))
186        });
187        Self {
188            reference: REFERENCE.name().to_owned(),
189            days: days.iter().map(BusinessDay::date).collect(),
190            rows,
191        }
192    }
193}
194
195fn row(model: &str, builtin: bool, scores: Vec<DayScore>) -> LadderRow {
196    #[expect(clippy::cast_precision_loss, reason = "a handful of days")]
197    let n = scores.len().max(1) as f64;
198    let mean = |f: fn(&DayScore) -> f64| scores.iter().map(f).sum::<f64>() / n;
199    LadderRow {
200        model: model.to_owned(),
201        builtin,
202        days: scores.len(),
203        quantile_score: mean(|s| s.quantile_score),
204        skill: None,
205        coverage80: mean(|s| s.coverage80),
206        coverage50: mean(|s| s.coverage50),
207        mae: mean(|s| s.mae),
208        scores,
209    }
210}