Skip to main content

reserving_kernels/diagnostics/
mack_tests.rs

1//! Formal non-parametric statistical tests for Mack (1993) chain-ladder
2//! model assumptions.
3//!
4//! Implements both diagnostic tests from Mack (1994), *Measuring the
5//! Variability of Chain Ladder Reserve Estimates*, Casualty Actuarial Society
6//! Spring Forum 1994, pp. 101–182:
7//!
8//! * **Appendix G — Adjacent Development Factor Correlation Test**:
9//!   Tests whether subsequent individual age-to-age factors `F_{i,k}` and
10//!   `F_{i,k+1}` are uncorrelated via weighted Spearman rank correlations `T_k`.
11//! * **Appendix H — Calendar-Year (Diagonal) Effect Test**:
12//!   Classifies individual age-to-age factors within each column as Small (`S`)
13//!   or Large (`L`) relative to the column median and tests whether diagonals
14//!   exhibit systematic high/low clustering using exact binomial moments of
15//!   `Z_d = min(S_d, L_d)`.
16
17use crate::dependence::spearman_correlation;
18use crate::severity::normal_cdf_exact;
19use crate::triangle::age_to_age;
20use crate::types::TriangleView;
21
22/// Spearman rank-correlation record for one adjacent development-link pair `(k, k + 1)`.
23#[derive(Debug, Clone, Copy, PartialEq)]
24pub struct AdjacentLinkCorrelation {
25    /// Leading development link index `k` (correlating link `k -> k+1` with `k+1 -> k+2`).
26    pub link: usize,
27    /// Number of common origin years observed across both links (`m_k`).
28    pub n_pairs: usize,
29    /// Spearman rank correlation `T_k`.
30    pub spearman_t: f64,
31    /// Mack weight `w_k = m_k - 1` (inverse null variance of `T_k`).
32    pub weight: f64,
33}
34
35/// Result of Mack (1994, Appendix G) adjacent development-factor correlation test.
36#[derive(Debug, Clone, PartialEq)]
37pub struct MackCorrelationTest {
38    /// Per-pair Spearman rank correlation records.
39    pub by_link: Vec<AdjacentLinkCorrelation>,
40    /// Weighted aggregate test statistic `T = Σ w_k T_k / Σ w_k`.
41    pub statistic_t: f64,
42    /// Null variance `Var(T) = 1 / Σ w_k`.
43    pub null_variance: f64,
44    /// Standardized normal test score `z = T / sqrt(Var(T))`.
45    pub z_score: f64,
46    /// Two-sided normal p-value `2 · (1 - Φ(|z|))`.
47    pub two_sided_p_value: f64,
48    /// Mack's 50% confidence half-width `0.6745 · sqrt(Var(T))`.
49    pub bound_50_pct: f64,
50    /// 95% confidence half-width `1.96 · sqrt(Var(T))`.
51    pub bound_95_pct: f64,
52}
53
54/// Per-calendar-diagonal counts and binomial moments for Mack (1994, Appendix H).
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct CalendarDiagonalTestRow {
57    /// Calendar diagonal index `d = origin + dev + 1` (target cell calendar period).
58    pub calendar_diagonal: usize,
59    /// Count of individual link ratios strictly below their column median (`S_d`).
60    pub small_count: usize,
61    /// Count of individual link ratios strictly above their column median (`L_d`).
62    pub large_count: usize,
63    /// Test contribution `Z_d = min(S_d, L_d)`.
64    pub z_d: f64,
65    /// Exact null expectation `E[Z_d]` under `Binomial(S_d + L_d, 1/2)`.
66    pub expected_z_d: f64,
67    /// Exact null variance `Var(Z_d)` under `Binomial(S_d + L_d, 1/2)`.
68    pub variance_z_d: f64,
69}
70
71/// Result of Mack (1994, Appendix H) calendar-year effect test.
72#[derive(Debug, Clone, PartialEq)]
73pub struct MackCalendarYearTest {
74    /// Per-diagonal Small/Large counts and exact binomial moments.
75    pub diagonals: Vec<CalendarDiagonalTestRow>,
76    /// Aggregate statistic `Z = Σ Z_d`.
77    pub statistic_z: f64,
78    /// Exact null expectation `E[Z] = Σ E[Z_d]`.
79    pub expected_z: f64,
80    /// Exact null variance `Var(Z) = Σ Var(Z_d)`.
81    pub variance_z: f64,
82    /// Standardized score `(Z - E[Z]) / sqrt(Var(Z))`. Negative values indicate
83    /// diagonal clustering (calendar-year effects).
84    pub z_score: f64,
85    /// Lower-tail p-value `Φ(z)` (small values indicate significant calendar-year effect).
86    pub lower_tail_p_value: f64,
87    /// Two-sided p-value `2 · (1 - Φ(|z|))`.
88    pub two_sided_p_value: f64,
89}
90
91/// Run Mack (1994, Appendix G) Spearman rank correlation test for independence
92/// of adjacent development factors.
93pub fn adjacent_factor_correlation_test(t: &TriangleView<'_>) -> MackCorrelationTest {
94    let n = t.n_origins.min(t.n_devs);
95    let mut by_link = Vec::new();
96    let mut weighted_sum = 0.0;
97    let mut total_weight = 0.0;
98
99    if n >= 4 {
100        for k in 0..(n - 3) {
101            let mut left = Vec::new();
102            let mut right = Vec::new();
103            for i in 0..(n - k - 2) {
104                let r1 = age_to_age(t, i, k);
105                let r2 = age_to_age(t, i, k + 1);
106                if r1.is_finite() && r2.is_finite() {
107                    left.push(r1);
108                    right.push(r2);
109                }
110            }
111            let m = left.len();
112            if m >= 2 {
113                let tk = spearman_correlation(&left, &right);
114                if tk.is_finite() {
115                    let w = (m - 1) as f64;
116                    weighted_sum += w * tk;
117                    total_weight += w;
118                    by_link.push(AdjacentLinkCorrelation {
119                        link: k,
120                        n_pairs: m,
121                        spearman_t: tk,
122                        weight: w,
123                    });
124                }
125            }
126        }
127    }
128
129    if total_weight <= 0.0 {
130        return MackCorrelationTest {
131            by_link,
132            statistic_t: f64::NAN,
133            null_variance: f64::NAN,
134            z_score: f64::NAN,
135            two_sided_p_value: f64::NAN,
136            bound_50_pct: f64::NAN,
137            bound_95_pct: f64::NAN,
138        };
139    }
140
141    let statistic_t = weighted_sum / total_weight;
142    let null_variance = 1.0 / total_weight;
143    let sd = null_variance.sqrt();
144    let z_score = statistic_t / sd;
145    let two_sided_p_value = (2.0 * normal_cdf_exact(-z_score.abs())).clamp(0.0, 1.0);
146
147    MackCorrelationTest {
148        by_link,
149        statistic_t,
150        null_variance,
151        z_score,
152        two_sided_p_value,
153        bound_50_pct: 0.674_489_750_196_081_7 * sd,
154        bound_95_pct: 1.959_963_984_540_054 * sd,
155    }
156}
157
158/// Exact expectation and variance of `Z = min(S, n - S)` for `S ~ Binomial(n, 1/2)`
159/// (Mack 1994, Appendix H).
160fn exact_min_binomial_moments(n: usize) -> (f64, f64) {
161    if n <= 1 {
162        return (0.0, 0.0);
163    }
164    let nf = n as f64;
165    let m = (n - 1) / 2;
166    // Compute C(n - 1, m) / 2^n safely in log space to avoid overflow for large triangles.
167    let log_comb = crate::bootstrap_odp::ln_gamma(nf)
168        - crate::bootstrap_odp::ln_gamma((m + 1) as f64)
169        - crate::bootstrap_odp::ln_gamma((n - m) as f64);
170    let comb_over_2n = (log_comb - nf * std::f64::consts::LN_2).exp();
171    let expected = 0.5 * nf - comb_over_2n * nf;
172    let variance = (0.25 * nf * (nf - 1.0) - comb_over_2n * nf * (nf - 1.0) + expected
173        - expected * expected)
174        .max(0.0);
175    (expected, variance)
176}
177
178/// Run Mack (1994, Appendix H) calendar-year (diagonal) effect test.
179pub fn calendar_year_effect_test(t: &TriangleView<'_>) -> MackCalendarYearTest {
180    let n = t.n_origins.min(t.n_devs);
181    if n < 3 {
182        return MackCalendarYearTest {
183            diagonals: Vec::new(),
184            statistic_z: f64::NAN,
185            expected_z: f64::NAN,
186            variance_z: f64::NAN,
187            z_score: f64::NAN,
188            lower_tail_p_value: f64::NAN,
189            two_sided_p_value: f64::NAN,
190        };
191    }
192
193    let mut small_by_diag = vec![0usize; n];
194    let mut large_by_diag = vec![0usize; n];
195
196    for k in 0..(n - 1) {
197        let mut pairs: Vec<(usize, f64)> = Vec::new();
198        for i in 0..(n - k - 1) {
199            let r = age_to_age(t, i, k);
200            if r.is_finite() {
201                pairs.push((i, r));
202            }
203        }
204        if pairs.len() < 2 {
205            continue;
206        }
207        let mut sorted_vals: Vec<f64> = pairs.iter().map(|&(_, r)| r).collect();
208        sorted_vals.sort_by(f64::total_cmp);
209        let len = sorted_vals.len();
210        let median = if len % 2 == 1 {
211            sorted_vals[len / 2]
212        } else {
213            f64::midpoint(sorted_vals[len / 2 - 1], sorted_vals[len / 2])
214        };
215
216        for (i, r) in pairs {
217            let diag = i + k + 1;
218            if diag < n {
219                if r < median {
220                    small_by_diag[diag] += 1;
221                } else if r > median {
222                    large_by_diag[diag] += 1;
223                }
224            }
225        }
226    }
227
228    let mut diagonals = Vec::new();
229    let mut statistic_z = 0.0;
230    let mut expected_z = 0.0;
231    let mut variance_z = 0.0;
232
233    for diag in 1..n {
234        let s = small_by_diag[diag];
235        let l = large_by_diag[diag];
236        let nd = s + l;
237        if nd == 0 {
238            continue;
239        }
240        let z_d = s.min(l) as f64;
241        let (e_d, v_d) = exact_min_binomial_moments(nd);
242        statistic_z += z_d;
243        expected_z += e_d;
244        variance_z += v_d;
245        diagonals.push(CalendarDiagonalTestRow {
246            calendar_diagonal: diag,
247            small_count: s,
248            large_count: l,
249            z_d,
250            expected_z_d: e_d,
251            variance_z_d: v_d,
252        });
253    }
254
255    if !(variance_z > 0.0) {
256        return MackCalendarYearTest {
257            diagonals,
258            statistic_z,
259            expected_z,
260            variance_z,
261            z_score: f64::NAN,
262            lower_tail_p_value: f64::NAN,
263            two_sided_p_value: f64::NAN,
264        };
265    }
266
267    let z_score = (statistic_z - expected_z) / variance_z.sqrt();
268    let lower_tail_p_value = normal_cdf_exact(z_score).clamp(0.0, 1.0);
269    let two_sided_p_value = (2.0 * normal_cdf_exact(-z_score.abs())).clamp(0.0, 1.0);
270
271    MackCalendarYearTest {
272        diagonals,
273        statistic_z,
274        expected_z,
275        variance_z,
276        z_score,
277        lower_tail_p_value,
278        two_sided_p_value,
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285    use crate::types::Triangle;
286
287    #[test]
288    fn exact_min_binomial_moments_match_hand_calculations() {
289        assert_eq!(exact_min_binomial_moments(1), (0.0, 0.0));
290        let (e2, v2) = exact_min_binomial_moments(2);
291        assert!((e2 - 0.5).abs() < 1e-12 && (v2 - 0.25).abs() < 1e-12);
292        let (e3, v3) = exact_min_binomial_moments(3);
293        assert!((e3 - 0.75).abs() < 1e-12 && (v3 - 0.1875).abs() < 1e-12);
294        let (e4, v4) = exact_min_binomial_moments(4);
295        assert!((e4 - 1.25).abs() < 1e-12 && (v4 - 0.4375).abs() < 1e-12);
296    }
297
298    #[test]
299    fn calendar_test_detects_strong_calendar_year_inflation_shock() {
300        // Construct an 8x8 triangle with a strong calendar-year inflation shock
301        // on the latest two diagonals (every factor on those diagonals is high).
302        let n = 8usize;
303        let base_ldfs = [2.0, 1.5, 1.25, 1.15, 1.10, 1.05, 1.02];
304        let mut data = vec![f64::NAN; n * n];
305        for i in 0..n {
306            let mut c = 1000.0 + 50.0 * i as f64;
307            data[i * n] = c;
308            for j in 1..(n - i) {
309                let cal = i + j;
310                let shock = if cal >= n - 2 {
311                    1.25
312                } else if cal <= 3 {
313                    0.90
314                } else {
315                    1.0
316                };
317                c *= base_ldfs[j - 1] * shock;
318                data[i * n + j] = c;
319            }
320        }
321        let tri = Triangle::new(n, n, data);
322        let cal_test = calendar_year_effect_test(&tri.view());
323        assert!(cal_test.z_score < -1.96, "z={}", cal_test.z_score);
324        assert!(cal_test.lower_tail_p_value < 0.025);
325    }
326
327    #[test]
328    fn correlation_test_computes_exact_null_variance() {
329        let n = 6usize;
330        let mut data = vec![f64::NAN; n * n];
331        for i in 0..n {
332            let mut c = 100.0 * (i + 1) as f64;
333            data[i * n] = c;
334            for j in 1..(n - i) {
335                let jitter = 1.0 + 0.02 * ((i * 3 + j) % 5) as f64;
336                c *= (1.4 - 0.05 * j as f64) * jitter;
337                data[i * n + j] = c;
338            }
339        }
340        let tri = Triangle::new(n, n, data);
341        let res = adjacent_factor_correlation_test(&tri.view());
342        // Total weight for n=6: (n-2)(n-3)/2 = 4*3/2 = 6 -> Var(T) = 1/6.
343        assert!((res.null_variance - 1.0 / 6.0).abs() < 1e-12);
344        assert!(res.two_sided_p_value >= 0.0 && res.two_sided_p_value <= 1.0);
345    }
346}