Skip to main content

reserving_kernels/
reserve_distribution.rs

1//! Shared summary math and coherent risk measures for reserve-simulation output.
2//!
3//! Includes both the legacy upper-rank empirical quantile / TCE helpers
4//! ([`quantile`], [`tvar`]) and the exact subadditive discrete risk-measure
5//! algorithms from CAS Monograph No. 15 (Mildenhall & Major, *Introduction to
6//! Capital Modeling and Portfolio Management*, §3.2–§3.4):
7//!
8//! * [`var_least`] — Algorithm 3.4.2 (least quantile `F^-(p)`).
9//! * [`tvar_coherent`] — Algorithm 3.4.3 (exact integral Tail Value at Risk
10//!   `TVaR_p(X) = (1 / (1 - p)) ∫_p^1 F^-(s) ds`, guaranteed subadditive even
11//!   on discrete / tied empirical distributions).
12//! * [`rvar`] — Range Value at Risk `RVaR_{p_low, p_high}(X)` (Cont et al.
13//!   2010; CAS Monograph No. 15, §3.3).
14
15use crate::validate::{ValidationError, validate_finite_slice};
16
17/// Summary statistics for a reserve sample distribution.
18#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
19pub struct ReserveDistributionSummary {
20    /// Arithmetic mean.
21    pub mean: f64,
22    /// Sample variance.
23    pub variance: f64,
24    /// Sample standard deviation.
25    pub std_dev: f64,
26    /// 50th percentile.
27    pub p50: f64,
28    /// 75th percentile.
29    pub p75: f64,
30    /// 90th percentile.
31    pub p90: f64,
32    /// 95th percentile.
33    pub p95: f64,
34    /// 99th percentile.
35    pub p99: f64,
36}
37
38fn validate_prob(p: f64) -> Result<(), ValidationError> {
39    if !p.is_finite() {
40        return Err(ValidationError::NotFinite);
41    }
42    if !(0.0..=1.0).contains(&p) {
43        return Err(ValidationError::InvalidMaturity { index: 0, value: p });
44    }
45    Ok(())
46}
47
48fn sorted(values: &[f64]) -> Result<Vec<f64>, ValidationError> {
49    if values.is_empty() {
50        return Err(ValidationError::ShapeMismatch);
51    }
52    validate_finite_slice(values)?;
53    let mut out = values.to_vec();
54    out.sort_unstable_by(f64::total_cmp);
55    Ok(out)
56}
57
58#[inline]
59fn quantile_rank_index(len: usize, p: f64) -> usize {
60    if p <= 0.0 {
61        return 0;
62    }
63    if p >= 1.0 {
64        return len - 1;
65    }
66    // Snap near-integer p * N within 1e-12 to avoid IEEE-754 representation jumps
67    // (e.g. 0.07 * 100.0 == 7.000000000000001).
68    let pn = p * len as f64;
69    let rounded = pn.round();
70    let rank = if (pn - rounded).abs() <= 1e-12 {
71        rounded as usize
72    } else {
73        pn.ceil() as usize
74    };
75    rank.saturating_sub(1).min(len - 1)
76}
77
78#[inline]
79fn select_quantile_in_place(buf: &mut [f64], p: f64) -> f64 {
80    let idx = quantile_rank_index(buf.len(), p);
81    let (_, nth, _) = buf.select_nth_unstable_by(idx, f64::total_cmp);
82    *nth
83}
84
85/// Arithmetic mean of a reserve sample (`O(n)` without sorting).
86pub fn mean(values: &[f64]) -> Result<f64, ValidationError> {
87    if values.is_empty() {
88        return Err(ValidationError::ShapeMismatch);
89    }
90    validate_finite_slice(values)?;
91    Ok(values.iter().sum::<f64>() / values.len() as f64)
92}
93
94/// Sample variance of a reserve sample.
95pub fn variance(values: &[f64]) -> Result<f64, ValidationError> {
96    let avg = mean(values)?;
97    if values.len() <= 1 {
98        return Ok(0.0);
99    }
100    Ok(values
101        .iter()
102        .map(|value| (value - avg).powi(2))
103        .sum::<f64>()
104        / (values.len() as f64 - 1.0))
105}
106
107/// Sample standard deviation of a reserve sample.
108pub fn std_dev(values: &[f64]) -> Result<f64, ValidationError> {
109    Ok(variance(values)?.sqrt())
110}
111
112/// Empirical quantile with upper-rank selection (`ceil(p * N) - 1`) in `O(n)`.
113pub fn quantile(values: &[f64], p: f64) -> Result<f64, ValidationError> {
114    validate_prob(p)?;
115    if values.is_empty() {
116        return Err(ValidationError::ShapeMismatch);
117    }
118    validate_finite_slice(values)?;
119    let mut buf = values.to_vec();
120    Ok(select_quantile_in_place(&mut buf, p))
121}
122
123/// Discrete least-quantile Value at Risk `VaR_p(X) = F^-(p) = inf { x : F(x) >= p }`
124/// (CAS Monograph No. 15, Algorithm 3.4.2): returns `ordered[ceil(p * N) - 1]`
125/// with IEEE-754 near-integer boundary snapping in `O(n)`.
126pub fn var_least(values: &[f64], p: f64) -> Result<f64, ValidationError> {
127    quantile(values, p)
128}
129
130/// Tail Conditional Expectation (average of observations `>= quantile(values, p)`).
131///
132/// Note: on discrete distributions with ties or non-integer `(1 - p) * N`,
133/// this TCE convention can differ from the exact subadditive integral TVaR.
134/// Use [`tvar_coherent`] for the CAS Monograph No. 15 coherent TVaR.
135pub fn tvar(values: &[f64], p: f64) -> Result<f64, ValidationError> {
136    let threshold = quantile(values, p)?;
137    let mut sum = 0.0;
138    let mut count = 0usize;
139    for &value in values {
140        if value >= threshold {
141            sum += value;
142            count += 1;
143        }
144    }
145    if count == 0 {
146        return Ok(threshold);
147    }
148    Ok(sum / count as f64)
149}
150
151/// Exact coherent Tail Value at Risk `TVaR_p(X) = (1 / (1 - p)) ∫_p^1 F^-(s) ds`
152/// for equally likely discrete outcomes (CAS Monograph No. 15, Algorithm 3.4.3).
153///
154/// Guaranteed subadditive on all finite discrete distributions, including
155/// distributions with ties or non-integer tail counts `N · (1 - p)`.
156pub fn tvar_coherent(values: &[f64], p: f64) -> Result<f64, ValidationError> {
157    validate_prob(p)?;
158    if values.is_empty() {
159        return Err(ValidationError::ShapeMismatch);
160    }
161    validate_finite_slice(values)?;
162    let n_len = values.len();
163    if p <= 0.0 {
164        return Ok(values.iter().sum::<f64>() / n_len as f64);
165    }
166    if p >= 1.0 {
167        return Ok(values.iter().copied().fold(f64::NEG_INFINITY, f64::max));
168    }
169    let pn = p * n_len as f64;
170    let n_idx = (pn.floor() as usize).min(n_len - 1);
171    if n_idx + 1 >= n_len {
172        return Ok(values.iter().copied().fold(f64::NEG_INFINITY, f64::max));
173    }
174    // O(n) partial selection: buf[n_idx] == ordered[n_idx] and buf[n_idx+1..] is
175    // the exact upper-tail multiset (sum is order-invariant).
176    let mut buf = values.to_vec();
177    let (_, nth, upper) = buf.select_nth_unstable_by(n_idx, f64::total_cmp);
178    let t1: f64 = upper.iter().sum();
179    let t2 = ((n_idx + 1) as f64 - pn) * *nth;
180    Ok((t1 + t2) / ((1.0 - p) * n_len as f64))
181}
182
183/// Range Value at Risk `RVaR_{p_low, p_high}(X)` (Cont et al. 2010; CAS
184/// Monograph No. 15, §3.3): exact average of the quantile function `F^-(s)`
185/// between `p_low` and `p_high` (`0 <= p_low < p_high <= 1`).
186pub fn rvar(values: &[f64], p_low: f64, p_high: f64) -> Result<f64, ValidationError> {
187    validate_prob(p_low)?;
188    validate_prob(p_high)?;
189    if !(p_low < p_high) {
190        return Err(ValidationError::InvalidParameter(
191            "rvar requires p_low < p_high",
192        ));
193    }
194    let ordered = sorted(values)?;
195    let n = ordered.len() as f64;
196    // Exact integral ∫_{p_low}^{p_high} F^-(s) ds over piecewise-constant step function
197    // where F^-(s) = ordered[j] on [j/N, (j+1)/N).
198    let mut integral = 0.0;
199    for (j, &x) in ordered.iter().enumerate() {
200        let lo = (j as f64 / n).max(p_low);
201        let hi = ((j + 1) as f64 / n).min(p_high);
202        if hi > lo {
203            integral += (hi - lo) * x;
204        }
205    }
206    Ok(integral / (p_high - p_low))
207}
208
209/// Empirical probability that reserve exceeds `threshold`.
210pub fn probability_exceeding(values: &[f64], threshold: f64) -> Result<f64, ValidationError> {
211    if !threshold.is_finite() {
212        return Err(ValidationError::NotFinite);
213    }
214    validate_finite_slice(values)?;
215    if values.is_empty() {
216        return Err(ValidationError::ShapeMismatch);
217    }
218    let count = values.iter().filter(|value| **value > threshold).count();
219    Ok(count as f64 / values.len() as f64)
220}
221
222/// Build a standard reserve-distribution summary bundle in `O(n)` via cascading
223/// partial selection (no full `O(n log n)` sort required).
224pub fn summarize(values: &[f64]) -> Result<ReserveDistributionSummary, ValidationError> {
225    let mut scratch = Vec::with_capacity(values.len());
226    summarize_with_scratch(values, &mut scratch, false)
227}
228
229/// Allocation-reusing internal variant of [`summarize`] that shares a caller-
230/// provided scratch buffer across repeated summary calls (e.g., portfolio total
231/// plus every origin year) and optionally skips redundant finiteness validation
232/// when the caller has already enforced finiteness on every element.
233pub(crate) fn summarize_with_scratch(
234    values: &[f64],
235    buf: &mut Vec<f64>,
236    already_finite: bool,
237) -> Result<ReserveDistributionSummary, ValidationError> {
238    if values.is_empty() {
239        return Err(ValidationError::ShapeMismatch);
240    }
241    let len = values.len();
242    let first = values[0];
243
244    // Fast O(1)-probed constant-series shortcut (e.g., fully developed origin 0
245    // when tail == 1.0, or zero-dispersion fixtures): skips variance, copy, and
246    // all five partial selections.
247    if first.is_finite()
248        && first == values[len - 1]
249        && first == values[len / 2]
250        && values.iter().all(|&v| v == first)
251    {
252        return Ok(ReserveDistributionSummary {
253            mean: first,
254            variance: 0.0,
255            std_dev: 0.0,
256            p50: first,
257            p75: first,
258            p90: first,
259            p95: first,
260            p99: first,
261        });
262    }
263
264    // 4-way unrolled sum (auto-vectorizes cleanly). By IEEE-754 arithmetic, any
265    // NaN or ±inf element poisons the accumulator irreversibly to non-finite, so
266    // a single post-loop check validates finiteness with zero per-element branches.
267    let mut s0 = 0.0;
268    let mut s1 = 0.0;
269    let mut s2 = 0.0;
270    let mut s3 = 0.0;
271    let (chunks, rem) = values.as_chunks::<4>();
272    for chunk in chunks {
273        s0 += chunk[0];
274        s1 += chunk[1];
275        s2 += chunk[2];
276        s3 += chunk[3];
277    }
278    for &v in rem {
279        s0 += v;
280    }
281    let total_sum = (s0 + s1) + (s2 + s3);
282    if !already_finite && !total_sum.is_finite() {
283        return Err(ValidationError::NotFinite);
284    }
285
286    let n = len as f64;
287    let avg = total_sum / n;
288    let var = if len <= 1 {
289        0.0
290    } else {
291        let mut v0 = 0.0;
292        let mut v1 = 0.0;
293        let mut v2 = 0.0;
294        let mut v3 = 0.0;
295        let (chunks, rem) = values.as_chunks::<4>();
296        for chunk in chunks {
297            let d0 = chunk[0] - avg;
298            let d1 = chunk[1] - avg;
299            let d2 = chunk[2] - avg;
300            let d3 = chunk[3] - avg;
301            v0 += d0 * d0;
302            v1 += d1 * d1;
303            v2 += d2 * d2;
304            v3 += d3 * d3;
305        }
306        for &val in rem {
307            let d = val - avg;
308            v0 += d * d;
309        }
310        ((v0 + v1) + (v2 + v3)) / (n - 1.0)
311    };
312
313    buf.clear();
314    buf.extend_from_slice(values);
315    let i50 = quantile_rank_index(len, 0.50);
316    let i75 = quantile_rank_index(len, 0.75);
317    let i90 = quantile_rank_index(len, 0.90);
318    let i95 = quantile_rank_index(len, 0.95);
319    let i99 = quantile_rank_index(len, 0.99);
320
321    let (_, p50_ref, rest) = buf.select_nth_unstable_by(i50, f64::total_cmp);
322    let p50 = *p50_ref;
323    let (p75, rest) = if i75 == i50 {
324        (p50, rest)
325    } else {
326        let (_, r, next) = rest.select_nth_unstable_by(i75 - i50 - 1, f64::total_cmp);
327        (*r, next)
328    };
329    let (p90, rest) = if i90 == i75 {
330        (p75, rest)
331    } else {
332        let (_, r, next) = rest.select_nth_unstable_by(i90 - i75 - 1, f64::total_cmp);
333        (*r, next)
334    };
335    let (p95, rest) = if i95 == i90 {
336        (p90, rest)
337    } else {
338        let (_, r, next) = rest.select_nth_unstable_by(i95 - i90 - 1, f64::total_cmp);
339        (*r, next)
340    };
341    let p99 = if i99 == i95 {
342        p95
343    } else {
344        let (_, r, _) = rest.select_nth_unstable_by(i99 - i95 - 1, f64::total_cmp);
345        *r
346    };
347
348    Ok(ReserveDistributionSummary {
349        mean: avg,
350        variance: var,
351        std_dev: var.sqrt(),
352        p50,
353        p75,
354        p90,
355        p95,
356        p99,
357    })
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363
364    fn close(a: f64, b: f64) -> bool {
365        (a - b).abs() <= 1e-12 * (1.0 + b.abs())
366    }
367
368    #[test]
369    fn computes_moments_and_quantiles() {
370        let values = [10.0, 20.0, 30.0, 40.0, 50.0];
371        let summary = summarize(&values).expect("summary");
372
373        assert!(close(summary.mean, 30.0));
374        assert!(close(summary.variance, 250.0));
375        assert!(close(summary.std_dev, 250.0_f64.sqrt()));
376        assert!(close(summary.p50, 30.0));
377        assert!(close(summary.p95, 50.0));
378    }
379
380    #[test]
381    fn computes_tvar_and_probability_exceeding() {
382        let values = [10.0, 20.0, 30.0, 40.0, 50.0];
383
384        assert!(close(tvar(&values, 0.8).expect("tvar"), 45.0));
385        assert!(close(
386            probability_exceeding(&values, 25.0).expect("probability"),
387            3.0 / 5.0
388        ));
389    }
390
391    #[test]
392    fn cas_monograph_15_coherent_tvar_is_subadditive_on_discrete_example() {
393        // CAS Monograph 15 §3.2 discrete example (20 equiprobable slots representing
394        // probs 0.90, 0.05, 0.05): Unit 1 = (0x18, 0, 10), Unit 2 = (0x18, 10, 0),
395        // Total = (0x18, 10, 10).
396        let mut u1 = vec![0.0; 20];
397        u1[19] = 10.0;
398        let mut u2 = vec![0.0; 20];
399        u2[18] = 10.0;
400        let tot: Vec<f64> = u1.iter().zip(u2.iter()).map(|(a, b)| a + b).collect();
401
402        // At p = 0.90: VaR fails subadditivity (0 + 0 < 10), while coherent TVaR
403        // satisfies subadditivity (5 + 5 = 10 == TVaR(total)).
404        assert!(close(tvar_coherent(&u1, 0.90).unwrap(), 5.0));
405        assert!(close(tvar_coherent(&u2, 0.90).unwrap(), 5.0));
406        assert!(close(tvar_coherent(&tot, 0.90).unwrap(), 10.0));
407
408        // Coherent TVaR matches RVaR(p, 1.0) identically.
409        let sample = [10.0, 20.0, 30.0, 40.0, 50.0];
410        assert!(close(
411            tvar_coherent(&sample, 0.75).unwrap(),
412            rvar(&sample, 0.75, 1.0).unwrap()
413        ));
414        assert!(close(tvar_coherent(&sample, 0.0).unwrap(), 30.0));
415        assert!(close(tvar_coherent(&sample, 1.0).unwrap(), 50.0));
416    }
417
418    #[test]
419    fn rejects_invalid_quantile_probability() {
420        let values = [1.0, 2.0, 3.0];
421        assert_eq!(
422            quantile(&values, 1.1),
423            Err(ValidationError::InvalidMaturity {
424                index: 0,
425                value: 1.1
426            })
427        );
428    }
429}