Skip to main content

reserving_kernels/
mack_bf.rs

1//! Mack (2008) distribution-free analytical MSEP for Bornhuetter–Ferguson.
2//!
3//! Implements:
4//!
5//! * T. Mack, *"The Prediction Error of Bornhuetter/Ferguson"*, *ASTIN
6//!   Bulletin*, Vol. 38, No. 1 (2008), pp. 87–109.
7//!
8//! ## Model Assumptions (BF1)–(BF3)
9//!
10//! For incremental losses `S_{i,k}` (`i = 0..n-1`, `k = 0..n-1`):
11//!
12//! * **(BF1)** All increments `S_{i,k}` are mutually independent.
13//! * **(BF2)** `E[S_{i,k}] = nu_i · y_k` where `y_k = z_k - z_{k-1}` is the
14//!   incremental payout pattern (`z_k` cumulative payout proportion,
15//!   `z_{n-1} = 1`).
16//! * **(BF3)** `Var(S_{i,k}) = nu_i · s_k^2` where `s_k^2 >= 0` is the
17//!   development-period process variance parameter.
18//!
19//! ## Analytical MSEP Decomposition
20//!
21//! Given *a priori* ultimates `E_i` (`nu_hat_i`) with standard errors
22//! `s(E_i)`, optional inter-origin prior correlation `rho`, estimated
23//! cumulative payout proportions `z_k` with standard errors `s(z_k)`, and
24//! process variance parameters `s_k^2`:
25//!
26//! For each origin `i` (latest observed age `d_i = n - 1 - i`, reserve
27//! `R_hat_i = E_i · (1 - z_{d_i})`):
28//!
29//! * **Process variance**: `Var(R_i) = E_i · sum_{k = d_i + 1}^{n - 1} s_k^2`.
30//! * **Estimation variance** (exact Goodman variance of independent product):
31//!   `Var(R_hat_i) = E_i^2 · s(z_{d_i})^2 + (1 - z_{d_i})^2 · s(E_i)^2 + s(E_i)^2 · s(z_{d_i})^2`.
32//! * **Total MSEP**: `msep(R_hat_i) = Var(R_i) + Var(R_hat_i)`.
33//!
34//! Across origins `0 <= i < j < n`, shared payout-pattern covariance
35//! `Cov(1 - z_{d_i}, 1 - z_{d_j}) = s(z_{d_i})^2` and optional prior covariance
36//! `Cov(E_i, E_j) = rho_{ij} · s(E_i) · s(E_j)` enter the aggregate MSEP:
37//!
38//! `Cov(R_hat_i, R_hat_j) = (E_i E_j + Cov(E_i, E_j)) · Cov(1 - z_{d_i}, 1 - z_{d_j})
39//!                          + (1 - z_{d_i})(1 - z_{d_j}) · Cov(E_i, E_j)`.
40
41use crate::ldf::{DevelopmentFactorEngine, pct_reported};
42use crate::triangle::{cumulative_to_incremental, latest_diagonal};
43use crate::types::TriangleView;
44use crate::validate::{
45    MonotonicityPolicy, ValidationError, validate_monotone_cumulative,
46    validate_nonnegative_finite_vector, validate_positive_finite_slice, validate_triangle,
47};
48
49/// How the cumulative payout pattern `z_k` is estimated from the triangle in
50/// [`analyze_from_triangle`].
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
52pub enum BfPayoutEstimator {
53    /// Mack (2008) §2 direct incremental BF payout shares:
54    /// `y_k = sum_{i=0}^{n-1-k} S_{i,k} / sum_{i=0}^{n-1-k} E_i`,
55    /// `z_k = 1 - sum_{j=k+1}^{n-1} y_j` (normalized if needed so `z_{n-1} = 1`).
56    #[default]
57    DirectIncremental,
58    /// Chain-ladder implied payout pattern `z_k = 1 / CDF_k` from volume-weighted LDFs.
59    ChainLadderImplied,
60}
61
62/// Configuration options for [`analyze_from_triangle`].
63#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
64pub struct MackBfOptions {
65    /// Payout pattern estimation method.
66    pub payout_estimator: BfPayoutEstimator,
67    /// Uniform pairwise correlation `rho in [0, 1]` between *a priori* ultimate
68    /// estimators `E_i` and `E_j` (`0.0` = independent priors; `1.0` = fully
69    /// comonotonic pricing-cycle uncertainty, as compared in Mack 2008 Table 3).
70    pub prior_correlation: f64,
71    /// Cumulative monotonicity validation policy.
72    pub monotonicity_policy: MonotonicityPolicy,
73}
74
75impl Default for MackBfOptions {
76    fn default() -> Self {
77        Self {
78            payout_estimator: BfPayoutEstimator::DirectIncremental,
79            prior_correlation: 0.0,
80            monotonicity_policy: MonotonicityPolicy::Strict,
81        }
82    }
83}
84
85impl MackBfOptions {
86    /// Set the payout pattern estimation method.
87    pub const fn with_payout_estimator(mut self, estimator: BfPayoutEstimator) -> Self {
88        self.payout_estimator = estimator;
89        self
90    }
91
92    /// Set the uniform pairwise correlation `rho in [0, 1]` between *a priori* ultimates.
93    pub const fn with_prior_correlation(mut self, rho: f64) -> Self {
94        self.prior_correlation = rho;
95        self
96    }
97
98    /// Set the triangle monotonicity policy.
99    pub const fn with_policy(mut self, policy: MonotonicityPolicy) -> Self {
100        self.monotonicity_policy = policy;
101        self
102    }
103}
104
105/// Complete Mack (2008) analytical BF MSEP decomposition.
106#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
107pub struct MackBfResult {
108    /// Latest observed cumulative losses by origin (length `n`).
109    pub latest: Vec<f64>,
110    /// *A priori* ultimate estimates `E_i` (length `n`).
111    pub prior_ultimate: Vec<f64>,
112    /// *A priori* ultimate standard errors `s(E_i)` (length `n`).
113    pub prior_se: Vec<f64>,
114    /// Cumulative payout pattern `z_k` for development ages `k = 0..n-1` (length `n`).
115    pub payout_z: Vec<f64>,
116    /// Payout pattern standard errors `s(z_k)` for `k = 0..n-1` (length `n`).
117    pub payout_se: Vec<f64>,
118    /// Development-period process variance parameters `s_k^2` (length `n`).
119    pub process_sigma_sq: Vec<f64>,
120    /// BF reserves `R_hat_i = E_i * (1 - z_{n - 1 - i})` by origin (length `n`).
121    pub reserves: Vec<f64>,
122    /// BF ultimates `latest[i] + reserves[i]` by origin (length `n`).
123    pub ultimates: Vec<f64>,
124    /// Process variance `Var(R_i)` by origin.
125    pub process_variance: Vec<f64>,
126    /// Prior-uncertainty component `(1 - z_{d_i})^2 * s(E_i)^2` by origin.
127    pub prior_variance: Vec<f64>,
128    /// Payout-pattern uncertainty component `E_i^2 * s(z_{d_i})^2` by origin.
129    pub pattern_variance: Vec<f64>,
130    /// Exact product interaction term `s(E_i)^2 * s(z_{d_i})^2` by origin.
131    pub interaction_variance: Vec<f64>,
132    /// Total estimation variance `Var(R_hat_i)` by origin.
133    pub estimation_variance: Vec<f64>,
134    /// Total MSEP `Var(R_i) + Var(R_hat_i)` by origin.
135    pub msep: Vec<f64>,
136    /// Prediction standard error `sqrt(msep[i])` by origin.
137    pub standard_error: Vec<f64>,
138    /// Coefficient of variation `standard_error[i] / reserves[i]` by origin.
139    pub cv: Vec<f64>,
140    /// Total BF reserve across origins.
141    pub total_reserve: f64,
142    /// Aggregate process variance `sum_i Var(R_i)`.
143    pub total_process_variance: f64,
144    /// Aggregate estimation variance (including cross-origin covariances).
145    pub total_estimation_variance: f64,
146    /// Aggregate cross-origin covariance contribution `2 * sum_{i<j} Cov(R_hat_i, R_hat_j)`.
147    pub total_covariance: f64,
148    /// Aggregate MSEP (`total_process_variance + total_estimation_variance`).
149    pub total_msep: f64,
150    /// Aggregate prediction standard error `sqrt(total_msep)`.
151    pub total_standard_error: f64,
152    /// Aggregate coefficient of variation (`total_standard_error / total_reserve`).
153    pub total_cv: f64,
154}
155
156/// Run Mack (2008) analytical BF MSEP directly from explicit model components:
157/// `latest`, `prior_ultimate` (`E_i`), `prior_se` (`s(E_i)`), `payout_z` (`z_k`),
158/// `payout_se` (`s(z_k)`), `process_sigma_sq` (`s_k^2`), and pairwise prior
159/// correlation `prior_correlation in [0, 1]`.
160///
161/// This entry point matches Mack (2008) Tables 1–3 directly when the actuary
162/// supplies judgmental or externally calibrated `s(E_i)`, `s(z_k)`, and `s_k^2`.
163pub fn analyze_from_components(
164    latest: &[f64],
165    prior_ultimate: &[f64],
166    prior_se: &[f64],
167    payout_z: &[f64],
168    payout_se: &[f64],
169    process_sigma_sq: &[f64],
170    prior_correlation: f64,
171) -> Result<MackBfResult, ValidationError> {
172    let n = latest.len();
173    if n < 2
174        || prior_ultimate.len() != n
175        || prior_se.len() != n
176        || payout_z.len() != n
177        || payout_se.len() != n
178        || process_sigma_sq.len() != n
179    {
180        return Err(ValidationError::ShapeMismatch);
181    }
182    validate_nonnegative_finite_vector(latest, n)?;
183    validate_positive_finite_slice(prior_ultimate, "prior_ultimate")?;
184    validate_nonnegative_finite_vector(prior_se, n)?;
185    validate_nonnegative_finite_vector(payout_se, n)?;
186    validate_nonnegative_finite_vector(process_sigma_sq, n)?;
187    for (idx, &z) in payout_z.iter().enumerate() {
188        if !z.is_finite() {
189            return Err(ValidationError::NotFinite);
190        }
191        if !(0.0..=1.0).contains(&z) {
192            return Err(ValidationError::InvalidMaturity {
193                index: idx,
194                value: z,
195            });
196        }
197    }
198    if !prior_correlation.is_finite() || !(0.0..=1.0).contains(&prior_correlation) {
199        return Err(ValidationError::InvalidParameter(
200            "prior_correlation must lie in [0, 1]",
201        ));
202    }
203
204    let mut reserves = vec![0.0; n];
205    let mut ultimates = vec![0.0; n];
206    let mut process_variance = vec![0.0; n];
207    let mut prior_variance = vec![0.0; n];
208    let mut pattern_variance = vec![0.0; n];
209    let mut interaction_variance = vec![0.0; n];
210    let mut estimation_variance = vec![0.0; n];
211    let mut msep = vec![0.0; n];
212    let mut standard_error = vec![0.0; n];
213    let mut cv = vec![0.0; n];
214
215    for i in 0..n {
216        let d_i = n - 1 - i;
217        let q_i = 1.0 - payout_z[d_i];
218        let e_i = prior_ultimate[i];
219        let se_e = prior_se[i];
220        let se_z = payout_se[d_i];
221
222        reserves[i] = e_i * q_i;
223        ultimates[i] = latest[i] + reserves[i];
224
225        let fut_s_sq: f64 = process_sigma_sq[(d_i + 1)..n].iter().sum();
226        let proc_v = (e_i * fut_s_sq).max(0.0);
227        let prior_v = (q_i * se_e).powi(2);
228        let pat_v = (e_i * se_z).powi(2);
229        let inter_v = (se_e * se_z).powi(2);
230        let est_v = prior_v + pat_v + inter_v;
231        let tot_v = proc_v + est_v;
232
233        process_variance[i] = proc_v;
234        prior_variance[i] = prior_v;
235        pattern_variance[i] = pat_v;
236        interaction_variance[i] = inter_v;
237        estimation_variance[i] = est_v;
238        msep[i] = tot_v;
239        standard_error[i] = tot_v.sqrt();
240        cv[i] = if reserves[i] > 0.0 {
241            standard_error[i] / reserves[i]
242        } else {
243            0.0
244        };
245    }
246
247    let total_reserve: f64 = reserves.iter().sum();
248    let total_process_variance: f64 = process_variance.iter().sum();
249
250    // Cross-origin covariances for 0 <= i < j < n:
251    // origin i is older (d_i > d_j), so shared future pattern columns are k = d_i+1..n-1,
252    // whose cumulative variance is s(z_{d_i})^2.
253    let mut total_covariance = 0.0;
254    for i in 0..n {
255        let d_i = n - 1 - i;
256        let q_i = 1.0 - payout_z[d_i];
257        let e_i = prior_ultimate[i];
258        let cov_z_ij = payout_se[d_i] * payout_se[d_i];
259
260        for j in (i + 1)..n {
261            let d_j = n - 1 - j;
262            let q_j = 1.0 - payout_z[d_j];
263            let e_j = prior_ultimate[j];
264            let cov_e_ij = prior_correlation * prior_se[i] * prior_se[j];
265
266            let cov_r_ij = (e_i * e_j + cov_e_ij) * cov_z_ij + q_i * q_j * cov_e_ij;
267            total_covariance += 2.0 * cov_r_ij;
268        }
269    }
270
271    let sum_est_var: f64 = estimation_variance.iter().sum();
272    let total_estimation_variance = (sum_est_var + total_covariance).max(0.0);
273    let total_msep = total_process_variance + total_estimation_variance;
274    let total_standard_error = total_msep.sqrt();
275    let total_cv = if total_reserve > 0.0 {
276        total_standard_error / total_reserve
277    } else {
278        0.0
279    };
280
281    Ok(MackBfResult {
282        latest: latest.to_vec(),
283        prior_ultimate: prior_ultimate.to_vec(),
284        prior_se: prior_se.to_vec(),
285        payout_z: payout_z.to_vec(),
286        payout_se: payout_se.to_vec(),
287        process_sigma_sq: process_sigma_sq.to_vec(),
288        reserves,
289        ultimates,
290        process_variance,
291        prior_variance,
292        pattern_variance,
293        interaction_variance,
294        estimation_variance,
295        msep,
296        standard_error,
297        cv,
298        total_reserve,
299        total_process_variance,
300        total_estimation_variance,
301        total_covariance,
302        total_msep,
303        total_standard_error,
304        total_cv,
305    })
306}
307
308/// Estimate Mack (2008) parameters (`z_k`, `s(z_k)`, `s_k^2`) directly from a
309/// cumulative loss triangle and compute the analytical BF MSEP decomposition.
310pub fn analyze_from_triangle(
311    triangle: &TriangleView<'_>,
312    prior_ultimate: &[f64],
313    prior_se: &[f64],
314    options: MackBfOptions,
315) -> Result<MackBfResult, ValidationError> {
316    validate_triangle(triangle)?;
317    if options.monotonicity_policy == MonotonicityPolicy::Strict {
318        validate_monotone_cumulative(triangle)?;
319    }
320    let n = triangle.n_origins;
321    if n < 3 {
322        return Err(ValidationError::InvalidParameter(
323            "Mack BF triangle estimation requires at least a 3x3 triangle",
324        ));
325    }
326    if prior_ultimate.len() != n || prior_se.len() != n {
327        return Err(ValidationError::ShapeMismatch);
328    }
329    validate_positive_finite_slice(prior_ultimate, "prior_ultimate")?;
330    validate_nonnegative_finite_vector(prior_se, n)?;
331
332    let inc = cumulative_to_incremental(triangle);
333    let latest = latest_diagonal(triangle);
334
335    // Column-wise prior volume V_k = sum_{i=0}^{n-1-k} E_i and incremental shares y_k.
336    let mut vol_k = vec![0.0; n];
337    let mut y_raw = vec![0.0; n];
338    for k in 0..n {
339        let m_k = n - k;
340        let mut s_sum = 0.0;
341        let mut e_sum = 0.0;
342        for i in 0..m_k {
343            s_sum += inc[i * n + k];
344            e_sum += prior_ultimate[i];
345        }
346        vol_k[k] = e_sum;
347        y_raw[k] = s_sum / e_sum;
348    }
349
350    // Build cumulative payout pattern z_k (z_{n-1} = 1.0).
351    let payout_z: Vec<f64> = match options.payout_estimator {
352        BfPayoutEstimator::DirectIncremental => {
353            // Sum only non-negative shares when clamping negative increments so
354            // normalization remains consistent under AllowNegativeIncrements.
355            let pos_sum: f64 = y_raw.iter().map(|&v| v.max(0.0)).sum();
356            let scale = if pos_sum > 0.0 { 1.0 / pos_sum } else { 1.0 };
357            let mut z = vec![0.0; n];
358            let mut cum = 0.0;
359            for k in 0..n {
360                cum += y_raw[k].max(0.0) * scale;
361                z[k] = cum.clamp(0.0, 1.0);
362            }
363            z[n - 1] = 1.0;
364            z
365        }
366        BfPayoutEstimator::ChainLadderImplied => {
367            let factors = DevelopmentFactorEngine::volume_weighted_with_policy(
368                triangle,
369                1.0,
370                options.monotonicity_policy,
371            )?;
372            let mut z = pct_reported(&factors.cdfs);
373            for v in &mut z {
374                *v = v.clamp(0.0, 1.0);
375            }
376            z[n - 1] = 1.0;
377            z
378        }
379    };
380
381    // Mack (2008) §3 unbiased process variance parameters s_k^2:
382    // s_k^2 = 1 / (m_k - 1) * sum_{i=0}^{m_k - 1} E_i * (S_{i,k} / E_i - y_hat_k)^2,
383    // centered at the column-weighted mean y_hat_k = sum(S_{i,k}) / sum(E_i) = y_raw[k].
384    let mut s_sq = vec![0.0; n];
385    for k in 0..(n - 1) {
386        let m_k = n - k;
387        let mut acc = 0.0;
388        for i in 0..m_k {
389            let diff = inc[i * n + k] / prior_ultimate[i] - y_raw[k];
390            acc += prior_ultimate[i] * diff * diff;
391        }
392        s_sq[k] = acc / (m_k as f64 - 1.0);
393    }
394    // Extrapolate final column k = n - 1 (single observation) via Mack's min-rule.
395    s_sq[n - 1] = if n >= 3 {
396        let a = s_sq[n - 2];
397        let b = s_sq[n - 3];
398        if a > 0.0 && b > 0.0 {
399            (a * a / b).min(a).min(b).max(0.0)
400        } else {
401            0.0
402        }
403    } else {
404        s_sq[0].max(0.0)
405    };
406
407    // Payout-pattern standard errors s(z_k) = sqrt(sum_{j=k+1}^{n-1} s_j^2 / V_j).
408    let mut payout_se = vec![0.0; n];
409    for k in 0..(n - 1) {
410        let mut var_z = 0.0;
411        for j in (k + 1)..n {
412            if vol_k[j] > 0.0 {
413                var_z += s_sq[j] / vol_k[j];
414            }
415        }
416        payout_se[k] = var_z.max(0.0).sqrt();
417    }
418    payout_se[n - 1] = 0.0;
419
420    analyze_from_components(
421        &latest,
422        prior_ultimate,
423        prior_se,
424        &payout_z,
425        &payout_se,
426        &s_sq,
427        options.prior_correlation,
428    )
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434    use crate::mack;
435    use crate::types::Triangle;
436
437    const NAN: f64 = f64::NAN;
438
439    #[test]
440    fn analytical_component_identities_hold_exactly() {
441        let latest = [1000.0, 850.0, 600.0, 300.0];
442        let prior = [1000.0, 1020.0, 1050.0, 1100.0];
443        let prior_se = [50.0, 60.0, 70.0, 80.0];
444        let z = [0.30, 0.60, 0.85, 1.00];
445        let z_se = [0.04, 0.03, 0.015, 0.0];
446        let s_sq = [40.0, 25.0, 12.0, 4.0];
447
448        let indep = analyze_from_components(&latest, &prior, &prior_se, &z, &z_se, &s_sq, 0.0)
449            .expect("indep");
450        let corr = analyze_from_components(&latest, &prior, &prior_se, &z, &z_se, &s_sq, 1.0)
451            .expect("corr");
452
453        // Origin 0 is fully developed (z_3 = 1, s(z_3) = 0) -> zero reserve & zero SE.
454        assert_eq!(indep.reserves[0], 0.0);
455        assert_eq!(indep.standard_error[0], 0.0);
456
457        // Per-origin variance decomposition identity.
458        for i in 0..4 {
459            let sum_parts = indep.process_variance[i]
460                + indep.prior_variance[i]
461                + indep.pattern_variance[i]
462                + indep.interaction_variance[i];
463            assert!((indep.msep[i] - sum_parts).abs() < 1e-10);
464        }
465
466        // Positively correlated priors strictly increase aggregate SE while
467        // leaving single-origin SEs unchanged.
468        for i in 0..4 {
469            assert!((indep.standard_error[i] - corr.standard_error[i]).abs() < 1e-12);
470        }
471        assert!(corr.total_standard_error > indep.total_standard_error);
472        assert!(indep.total_covariance > 0.0);
473    }
474
475    #[test]
476    fn bf_msep_dominates_chain_ladder_on_noisy_youngest_origin() {
477        // Construct a noisy 5x5 triangle where origin 4 has an unusually volatile first cell.
478        #[rustfmt::skip]
479        let data = vec![
480            100.0, 220.0, 310.0, 360.0, 380.0,
481            150.0, 250.0, 340.0, 390.0,   NAN,
482             70.0, 210.0, 300.0,   NAN,   NAN,
483            130.0, 260.0,   NAN,   NAN,   NAN,
484            180.0,   NAN,   NAN,   NAN,   NAN,
485        ];
486        let tri = Triangle::new(5, 5, data);
487        let prior = [380.0, 395.0, 390.0, 405.0, 410.0];
488        let prior_se = [20.0; 5]; // 5% a priori CoV
489
490        let m_cl = mack::analyze(&tri.view(), 1.0).unwrap();
491        let m_bf = analyze_from_triangle(&tri.view(), &prior, &prior_se, MackBfOptions::default())
492            .unwrap();
493
494        assert!(
495            m_bf.standard_error[4] < m_cl.standard_error[4],
496            "BF SE={} should be < CL SE={}",
497            m_bf.standard_error[4],
498            m_cl.standard_error[4]
499        );
500    }
501}