Skip to main content

flexpool_plan/
scenarios.rs

1//! Price scenarios from forecast quantiles: a Gaussian copula with the errors' own time correlation.
2
3use flexpool_forecast::Forecast;
4
5/// Scenarios drawn per day.
6pub const SCENARIOS: usize = 200;
7
8/// Φ⁻¹ at the forecast levels 0.1, 0.25, 0.5, 0.75, 0.9.
9const KNOTS: [f64; 5] = [
10    -1.281_551_565_544_600_4,
11    -0.674_489_750_196_081_7,
12    0.0,
13    0.674_489_750_196_081_7,
14    1.281_551_565_544_600_4,
15];
16
17/// SplitMix64 (Steele, Lea & Flood 2014): small, fast and fully deterministic.
18struct SplitMix64(u64);
19
20impl SplitMix64 {
21    const fn next(&mut self) -> u64 {
22        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
23        let mut z = self.0;
24        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
25        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
26        z ^ (z >> 31)
27    }
28
29    /// Uniform in (0, 1), never 0 or 1.
30    fn uniform(&mut self) -> f64 {
31        #[expect(clippy::cast_precision_loss, reason = "53 random bits")]
32        let bits = (self.next() >> 11) as f64;
33        (bits + 0.5) / 9_007_199_254_740_992.0
34    }
35
36    fn normal(&mut self) -> f64 {
37        inverse_normal(self.uniform())
38    }
39}
40
41/// Φ⁻¹(p) by Acklam's rational approximation (relative error < 1.2e-9), for p in (0, 1).
42#[must_use]
43pub fn inverse_normal(p: f64) -> f64 {
44    const A: [f64; 6] = [
45        -3.969_683_028_665_376e1,
46        2.209_460_984_245_205e2,
47        -2.759_285_104_469_687e2,
48        1.383_577_518_672_69e2,
49        -3.066_479_806_614_716e1,
50        2.506_628_277_459_239,
51    ];
52    const B: [f64; 5] = [
53        -5.447_609_879_822_406e1,
54        1.615_858_368_580_409e2,
55        -1.556_989_798_598_866e2,
56        6.680_131_188_771_972e1,
57        -1.328_068_155_288_572e1,
58    ];
59    const C: [f64; 6] = [
60        -7.784_894_002_430_293e-3,
61        -3.223_964_580_411_365e-1,
62        -2.400_758_277_161_838,
63        -2.549_732_539_343_734,
64        4.374_664_141_464_968,
65        2.938_163_982_698_783,
66    ];
67    const D: [f64; 4] = [
68        7.784_695_709_041_462e-3,
69        3.224_671_290_700_398e-1,
70        2.445_134_137_142_996,
71        3.754_408_661_907_416,
72    ];
73    let tail = |q: f64| {
74        (((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5])
75            / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0)
76    };
77    if p < 0.024_25 {
78        tail((-2.0 * p.ln()).sqrt())
79    } else if p > 1.0 - 0.024_25 {
80        -tail((-2.0 * (1.0 - p).ln()).sqrt())
81    } else {
82        let q = p - 0.5;
83        let r = q * q;
84        (((((A[0] * r + A[1]) * r + A[2]) * r + A[3]) * r + A[4]) * r + A[5]) * q
85            / (((((B[0] * r + B[1]) * r + B[2]) * r + B[3]) * r + B[4]) * r + 1.0)
86    }
87}
88
89/// The price at normal score `z` for quantiles `q`: piecewise linear between the knots, linear
90/// beyond them with the outer slopes. At the knots it returns the quantiles exactly.
91#[must_use]
92pub fn price_at(q: &[f64; 5], z: f64) -> f64 {
93    let seg = KNOTS.windows(2).position(|w| z <= w[1]).unwrap_or(3);
94    let (z0, z1, q0, q1) = (KNOTS[seg], KNOTS[seg + 1], q[seg], q[seg + 1]);
95    q0 + (q1 - q0) * (z - z0) / (z1 - z0)
96}
97
98/// `SCENARIOS` price paths for `forecast` (one value per interval), latent AR(1) with `rho` per
99/// step, clamped to `[lo, hi]`, deterministic for `seed`.
100#[must_use]
101pub fn draw(forecast: &Forecast, rho: f64, seed: u64, lo: f64, hi: f64) -> Vec<Vec<f64>> {
102    let rho = rho.clamp(0.0, 0.99);
103    let innovation = (1.0 - rho * rho).sqrt();
104    let mut rng = SplitMix64(seed);
105    (0..SCENARIOS)
106        .map(|_| {
107            let mut z = rng.normal();
108            forecast
109                .intervals
110                .iter()
111                .enumerate()
112                .map(|(t, i)| {
113                    if t > 0 {
114                        z = rho * z + innovation * rng.normal();
115                    }
116                    price_at(&i.q, z).clamp(lo, hi)
117                })
118                .collect()
119        })
120        .collect()
121}