Skip to main content

reserving_kernels/selection/
scoring.rs

1//! Numeric scoring helpers for deterministic factor selectors.
2
3use crate::diagnostics::link_ratio_diagnostics::{LinkRatioDiagnostics, diagnose_all};
4use crate::ldf;
5use crate::selection::CandidateSelector;
6use crate::selection::backtest::BacktestScore;
7use crate::types::TriangleView;
8
9/// Scored selector candidate with its factor vector.
10#[derive(Debug, Clone, PartialEq)]
11pub struct SelectorScore {
12    /// Candidate selector being scored.
13    pub selector: CandidateSelector,
14    /// Weighted total score.
15    pub total_score: f64,
16    /// Stability contribution from link-ratio CV.
17    pub stability_score: f64,
18    /// Holdout prediction accuracy contribution.
19    pub backtest_score: f64,
20    /// Smoothness contribution from adjacent-factor continuity.
21    pub smoothness_score: f64,
22    /// Outlier-sensitivity penalty from leave-one-out deltas.
23    pub outlier_penalty: f64,
24    /// Selected factor vector.
25    pub selected_factors: Vec<f64>,
26}
27
28fn selector_ldfs(t: &TriangleView<'_>, selector: &CandidateSelector) -> Vec<f64> {
29    match selector {
30        CandidateSelector::VolumeWeighted => ldf::volume_weighted(t),
31        CandidateSelector::SimpleAverage => ldf::simple_average(t),
32        CandidateSelector::Median => ldf::median(t),
33        CandidateSelector::ExHiLo => ldf::ex_hi_lo(t),
34        CandidateSelector::VolumeWeightedLastN(n) => ldf::volume_weighted_last_n(t, *n),
35        CandidateSelector::SimpleAverageLastN(n) => ldf::simple_average_last_n(t, *n),
36        CandidateSelector::Manual(values) => values.clone(),
37    }
38}
39
40fn stability_score(diagnostics: &[LinkRatioDiagnostics]) -> f64 {
41    let finite: Vec<f64> = diagnostics
42        .iter()
43        .map(|diag| diag.coeff_var)
44        .filter(|value| value.is_finite())
45        .collect();
46    if finite.is_empty() {
47        return 0.0;
48    }
49    let avg_cv = finite.iter().sum::<f64>() / finite.len() as f64;
50    1.0 / (1.0 + avg_cv)
51}
52
53fn smoothness_score(ldfs: &[f64]) -> f64 {
54    if ldfs.len() <= 1 {
55        return 1.0;
56    }
57    let mut sum = 0.0;
58    let mut count = 0usize;
59    for pair in ldfs.windows(2) {
60        if pair[0].is_finite() && pair[1].is_finite() {
61            sum += (pair[1] - pair[0]).abs();
62            count += 1;
63        }
64    }
65    if count == 0 {
66        return 0.0;
67    }
68    1.0 / (1.0 + sum / count as f64)
69}
70
71fn outlier_penalty(diagnostics: &[LinkRatioDiagnostics]) -> f64 {
72    let mut deltas = Vec::new();
73    for diag in diagnostics {
74        for loo in &diag.leave_one_out_factors {
75            if loo.is_finite() && diag.selected_factor.is_finite() {
76                deltas.push((diag.selected_factor - loo).abs());
77            }
78        }
79    }
80    if deltas.is_empty() {
81        return 0.0;
82    }
83    deltas.iter().sum::<f64>() / deltas.len() as f64
84}
85
86fn backtest_component(score: &BacktestScore) -> f64 {
87    if !score.mape.is_finite() {
88        return 0.0;
89    }
90    1.0 / (1.0 + score.mape)
91}
92
93fn to_ldf_method(selector: &CandidateSelector) -> crate::ldf::LdfSelectionMethod {
94    match selector {
95        CandidateSelector::VolumeWeighted => crate::ldf::LdfSelectionMethod::VolumeWeighted,
96        CandidateSelector::SimpleAverage => crate::ldf::LdfSelectionMethod::SimpleAverage,
97        CandidateSelector::Median => crate::ldf::LdfSelectionMethod::Median,
98        CandidateSelector::ExHiLo => crate::ldf::LdfSelectionMethod::ExHiLo,
99        CandidateSelector::VolumeWeightedLastN(last_n) => {
100            crate::ldf::LdfSelectionMethod::LastNVolumeWeighted { last_n: *last_n }
101        }
102        CandidateSelector::SimpleAverageLastN(last_n) => {
103            crate::ldf::LdfSelectionMethod::LastNSimpleAverage { last_n: *last_n }
104        }
105        CandidateSelector::Manual(_) => crate::ldf::LdfSelectionMethod::Selected,
106    }
107}
108
109/// Score one selector using stability, holdout accuracy, smoothness, and leave-one-out sensitivity.
110pub fn score_selector(
111    t: &TriangleView<'_>,
112    selector: CandidateSelector,
113    tail: f64,
114) -> SelectorScore {
115    let holdout = crate::selection::backtest::holdout_latest_diagonal(t);
116    score_selector_with_holdout(t, selector, tail, &holdout)
117}
118
119fn score_selector_with_holdout(
120    t: &TriangleView<'_>,
121    selector: CandidateSelector,
122    tail: f64,
123    holdout: &crate::selection::backtest::HoldoutSet,
124) -> SelectorScore {
125    let ldfs = selector_ldfs(t, &selector);
126    let diagnostics = diagnose_all(t, to_ldf_method(&selector));
127    let backtest = crate::selection::backtest::fit_predict_score(holdout, selector.clone(), tail);
128
129    let stability = stability_score(&diagnostics);
130    let backtest_score = backtest_component(&backtest);
131    let smoothness = smoothness_score(&ldfs);
132    // Manual factors are fixed by the actuary and have zero leave-one-out sensitivity.
133    let outlier_penalty = if matches!(selector, CandidateSelector::Manual(_)) {
134        0.0
135    } else {
136        outlier_penalty(&diagnostics)
137    };
138    let total_score = stability + backtest_score + smoothness - outlier_penalty;
139
140    SelectorScore {
141        selector,
142        total_score,
143        stability_score: stability,
144        backtest_score,
145        smoothness_score: smoothness,
146        outlier_penalty,
147        selected_factors: ldfs,
148    }
149}
150
151/// Score a family of selector candidates (reusing a single holdout split).
152pub fn score_selector_family(
153    t: &TriangleView<'_>,
154    selectors: &[CandidateSelector],
155    tail: f64,
156) -> Vec<SelectorScore> {
157    let holdout = crate::selection::backtest::holdout_latest_diagonal(t);
158    selectors
159        .iter()
160        .cloned()
161        .map(|selector| score_selector_with_holdout(t, selector, tail, &holdout))
162        .collect()
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use crate::types::Triangle;
169
170    fn triangle_4x4() -> Triangle {
171        #[rustfmt::skip]
172        let data = vec![
173            1000.0, 1500.0, 1700.0, 1800.0,
174            1200.0, 1800.0, 2000.0, f64::NAN,
175            1500.0, 2100.0, f64::NAN, f64::NAN,
176            1800.0, f64::NAN, f64::NAN, f64::NAN,
177        ];
178        Triangle::new(4, 4, data)
179    }
180
181    #[test]
182    fn score_selector_returns_component_scores() {
183        let tri = triangle_4x4();
184        let score = score_selector(&tri.view(), CandidateSelector::VolumeWeighted, 1.0);
185
186        assert_eq!(score.selected_factors.len(), 3);
187        assert!(score.stability_score.is_finite());
188        assert!(score.backtest_score.is_finite());
189        assert!(score.smoothness_score.is_finite());
190        assert!(score.outlier_penalty.is_finite());
191        assert!(score.total_score.is_finite());
192    }
193
194    #[test]
195    fn score_selector_family_scores_each_candidate() {
196        let tri = triangle_4x4();
197        let scores = score_selector_family(
198            &tri.view(),
199            &[
200                CandidateSelector::VolumeWeighted,
201                CandidateSelector::SimpleAverage,
202                CandidateSelector::ExHiLo,
203            ],
204            1.0,
205        );
206
207        assert_eq!(scores.len(), 3);
208        assert!(scores.iter().all(|score| score.total_score.is_finite()));
209    }
210}