flexpool-forecast 0.5.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
//! Forecasts: the contract, the models, no look-ahead, the ladder.
#![expect(clippy::unwrap_used, reason = "tests")]

use flexpool_core::BusinessDay;
use flexpool_forecast::{LEVELS, Ladder, Model, builtin, pinball, same_local_time, score};
use flexpool_rules::RuleBook;
use flexpool_sim::{Replay, Scenario};
use time::macros::{date, datetime};

fn replay(day: &str) -> Replay {
    replay_with(day, 28)
}

fn replay_with(day: &str, history_days: u16) -> Replay {
    let text = format!(
        "name = \"t\"\nday = \"{day}\"\n[market]\nsource = \"synthetic\"\nseed = 7\nhistory_days = {history_days}\n"
    );
    Replay::new(
        Scenario::parse(&text).unwrap(),
        RuleBook::bundled().unwrap(),
        None,
    )
    .unwrap()
}

#[test]
fn the_pinball_loss_is_asymmetric_by_level() {
    assert!(
        (pinball(10.0, 8.0, 0.9) - 1.8).abs() < 1e-12,
        "under-forecast at a high level costs"
    );
    assert!((pinball(10.0, 12.0, 0.9) - 0.2).abs() < 1e-12);
    assert!((pinball(10.0, 10.0, 0.5)).abs() < 1e-12);
}

/// Edge case: "the same time yesterday" is Berlin wall-clock time, across both DST switches.
#[test]
fn same_local_time_crosses_daylight_saving() {
    // Autumn: Sunday 26 October 2025 has 25 hours.
    assert_eq!(
        same_local_time(datetime!(2025-10-26 18:15 UTC), 1),
        Some(datetime!(2025-10-25 17:15 UTC)),
        "19:15 CET ← 19:15 CEST"
    );
    assert_eq!(
        same_local_time(datetime!(2025-10-27 18:15 UTC), 1),
        Some(datetime!(2025-10-26 18:15 UTC))
    );
    // Spring: 02:15 did not exist on Sunday 30 March 2025 — one hour earlier.
    assert_eq!(
        same_local_time(datetime!(2025-03-31 00:15 UTC), 1),
        Some(datetime!(2025-03-30 00:15 UTC)),
        "02:15 CEST ← 01:15 CET"
    );
    assert_eq!(
        same_local_time(datetime!(2025-10-02 17:00 UTC), 7),
        Some(datetime!(2025-09-25 17:00 UTC))
    );
}

/// Edge case: hourly history (before the 15-minute go-live) serves a quarter-hour forecast.
#[test]
fn hourly_history_serves_a_quarter_hour_day() {
    let r = replay("2025-10-02");
    let d = BusinessDay::new(date!(2025 - 10 - 02)).unwrap();
    let view = r.series().at(datetime!(2025-10-01 08:00 UTC));
    let f = builtin(Model::NaiveWeek, &view, &d, 15).unwrap();
    assert_eq!(f.intervals.len(), 96);
    assert!(
        f.intervals
            .iter()
            .all(|i| i.q.windows(2).all(|w| w[0] <= w[1])),
        "quantiles in order"
    );
    // 19:00, 19:15, 19:30 and 19:45 take the same hourly price of a week earlier as their median's base.
    let evening: Vec<_> = f
        .intervals
        .iter()
        .filter(|i| i.start.hour() == 17)
        .map(|i| i.q[2])
        .collect();
    assert_eq!(evening.len(), 4);
}

/// forecast/SR-001: a forecast never reads the delivery day's own prices — not before their
/// publication (the view refuses) and not after it (the models do not look).
#[test]
fn sr_001_forecasts_never_look_ahead() {
    // The same history (2025-09-03 …), once with and once without the delivery day itself.
    let with_day = replay_with("2025-10-02", 29);
    let without_day = replay_with("2025-10-01", 28);
    let d = BusinessDay::new(date!(2025 - 10 - 02)).unwrap();
    for issue in [
        datetime!(2025-10-01 08:00 UTC),
        datetime!(2025-10-01 11:00 UTC),
    ] {
        for m in Model::ALL {
            let a = builtin(m, &with_day.series().at(issue), &d, 15).unwrap();
            let b = builtin(m, &without_day.series().at(issue), &d, 15).unwrap();
            assert_eq!(a, b, "{} at {issue}", m.name());
            assert_eq!(a.issued_at, issue);
        }
    }
}

/// US1/AC3: the same scenario gives the same forecast.
#[test]
fn forecasts_are_deterministic() {
    let r = replay("2025-10-02");
    let d = BusinessDay::new(date!(2025 - 10 - 02)).unwrap();
    let at = datetime!(2025-10-01 08:00 UTC);
    assert_eq!(
        builtin(Model::Blend, &r.series().at(at), &d, 15),
        builtin(Model::Blend, &replay("2025-10-02").series().at(at), &d, 15)
    );
}

#[test]
fn without_history_there_is_no_guess() {
    let text = "name = \"t\"\nday = \"2025-10-02\"\n[market]\nsource = \"synthetic\"\nseed = 7\nhistory_days = 0\n";
    let r = Replay::new(
        Scenario::parse(text).unwrap(),
        RuleBook::bundled().unwrap(),
        None,
    )
    .unwrap();
    let d = BusinessDay::new(date!(2025 - 10 - 02)).unwrap();
    assert!(
        builtin(
            Model::Blend,
            &r.series().at(datetime!(2025-10-01 08:00 UTC)),
            &d,
            15
        )
        .is_err()
    );
}

/// SC-001, SC-002, SC-003, US3/AC1: over 14 days the blend beats both naive models, the 80 % bands
/// hold between 65 % and 95 % of prices, and forecast plus ladder take under a second.
#[test]
fn sc_001_to_003_the_ladder_on_the_demo() {
    let r = replay("2025-10-02");
    let rules = RuleBook::bundled().unwrap();
    let started = std::time::Instant::now();
    let now = datetime!(2025-10-01 08:00 UTC);
    let ladder = Ladder::compute(r.series(), &rules, now, 14, &[]);
    let d = BusinessDay::new(date!(2025 - 10 - 02)).unwrap();
    let _ = builtin(Model::Blend, &r.series().at(now), &d, 15).unwrap();
    let elapsed = started.elapsed();
    assert_eq!(ladder.days.len(), 14);
    assert_eq!(
        *ladder.days.last().unwrap(),
        date!(2025 - 10 - 01),
        "the newest day with known prices"
    );
    for row in &ladder.rows {
        eprintln!(
            "{:<11} qs {:6.2}  skill {:+.3}  c80 {:.2}  c50 {:.2}  mae {:6.2}",
            row.model,
            row.quantile_score,
            row.skill.unwrap_or(f64::NAN),
            row.coverage80,
            row.coverage50,
            row.mae
        );
        assert_eq!(row.days, 14, "{}", row.model);
        assert!(
            (0.65..=0.95).contains(&row.coverage80),
            "{} covers {}",
            row.model,
            row.coverage80
        );
    }
    let qs = |m: &str| {
        ladder
            .rows
            .iter()
            .find(|r| r.model == m)
            .unwrap()
            .quantile_score
    };
    assert!(
        qs("blend") < qs("naive-day") && qs("blend") < qs("naive-week"),
        "the blend beats both naive models"
    );
    assert_eq!(ladder.rows[0].model, "blend");
    assert!(
        ladder
            .rows
            .iter()
            .find(|r| r.model == "naive-week")
            .unwrap()
            .skill
            .unwrap()
            .abs()
            < 1e-12,
        "the reference has no skill over itself"
    );
    assert!(elapsed < std::time::Duration::from_secs(1), "{elapsed:?}");
}

#[test]
fn a_score_counts_coverage_and_median_error() {
    let f = flexpool_forecast::Forecast {
        day: date!(2025 - 10 - 02),
        model: "x".into(),
        issued_at: datetime!(2025-10-01 08:00 UTC),
        minutes: 60,
        intervals: vec![
            flexpool_forecast::Interval {
                start: datetime!(2025-10-01 22:00 UTC),
                q: [0.0, 5.0, 10.0, 15.0, 20.0],
            },
            flexpool_forecast::Interval {
                start: datetime!(2025-10-01 23:00 UTC),
                q: [0.0, 5.0, 10.0, 15.0, 20.0],
            },
        ],
    };
    let s = score(&f, &|t| Some(if t.hour() == 22 { 12.0 } else { 30.0 })).unwrap();
    assert!((s.coverage80 - 0.5).abs() < 1e-12 && (s.coverage50 - 0.5).abs() < 1e-12);
    assert!((s.mae - 11.0).abs() < 1e-12);
    assert_eq!(LEVELS.len(), 5);
}