Skip to main content

reserving_kernels/
multivariate_cl.rs

1//! Multivariate Chain Ladder (Zhang 2010 / Pröhl & Schmidt 2005).
2//!
3//! Models $K$ correlated cumulative loss triangles simultaneously:
4//! $$Y_{i,k+1} = B_k Y_{i,k} + \varepsilon_{i,k+1}, \qquad
5//!   \text{Cov}(\varepsilon_{i,k+1} \mid Y_{i,k}) = D(Y_{i,k})^{1/2} \, \Sigma_k \, D(Y_{i,k})^{1/2},$$
6//! where $Y_{i,k} \in \mathbb{R}^K$ is the vector of cumulative losses across
7//! the $K$ lines of business at origin $i$ and development age $k$.
8//!
9//! Two structural variants are supported (mirroring `mages/ChainLadder`'s
10//! `MultiChainLadder`):
11//! - [`MultivariateModel::DiagonalMcl`]: diagonal development matrices
12//!   $B_k = \text{diag}(f_{k,1}, \dots, f_{k,K})$ with full cross-line
13//!   residual covariance $\Sigma_k$ (Pröhl & Schmidt 2005; Braun 2004).
14//!   Matches univariate Mack reserves line-by-line while capturing exact
15//!   cross-line process and parameter covariance for portfolio MSEP.
16//! - [`MultivariateModel::GeneralGmcl`]: full $K \times K$ development matrices
17//!   $B_k$ estimated via weighted multivariate regression, allowing cross-line
18//!   development spillovers (Zhang 2010).
19
20use serde::{Deserialize, Serialize};
21
22use crate::{
23    linalg::solve_general,
24    triangle::latest_diagonal,
25    types::TriangleView,
26    validate::{
27        MonotonicityPolicy, ValidationError, validate_monotone_cumulative, validate_triangle,
28    },
29};
30
31/// Structural specification for [`analyze_multivariate_cl`].
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33pub enum MultivariateModel {
34    /// Diagonal development matrices with full $K \times K$ residual covariance
35    /// (Braun 2004 / Pröhl & Schmidt 2005 / `MultiChainLadder(..., model="MCL")`).
36    DiagonalMcl,
37    /// Full $K \times K$ development matrices with cross-line regression
38    /// (Zhang 2010 / `MultiChainLadder(..., model="GMCL")`).
39    GeneralGmcl,
40}
41
42/// Options for [`analyze_multivariate_cl`].
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44pub struct MultivariateClOptions {
45    /// Diagonal MCL vs. General GMCL.
46    pub model: MultivariateModel,
47    /// Monotonicity policy applied to each input triangle.
48    pub policy: MonotonicityPolicy,
49}
50
51impl Default for MultivariateClOptions {
52    fn default() -> Self {
53        Self {
54            model: MultivariateModel::DiagonalMcl,
55            policy: MonotonicityPolicy::AllowNegativeIncrements,
56        }
57    }
58}
59
60/// Result of a $K$-line Multivariate Chain Ladder analysis.
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62pub struct MultivariateClResult {
63    /// Number of lines of business $K$.
64    pub n_lines: usize,
65    /// Number of origin / development periods $n$.
66    pub n_origins: usize,
67    /// Estimated $K \times K$ development matrices $B_k$ (each row-major `K × K`) for `k = 0..n-1`.
68    pub development_matrices: Vec<Vec<f64>>,
69    /// Estimated $K \times K$ residual covariance matrices $\Sigma_k$ (row-major `K × K`) for `k = 0..n-1`.
70    pub sigma_matrices: Vec<Vec<f64>>,
71    /// Projected ultimates per line (`n_lines` vectors of length `n_origins`).
72    pub ultimates: Vec<Vec<f64>>,
73    /// Projected reserves per line (`n_lines` vectors of length `n_origins`).
74    pub reserves: Vec<Vec<f64>>,
75    /// Total reserve per line.
76    pub total_reserves_by_line: Vec<f64>,
77    /// Portfolio total reserve summed across all $K$ lines.
78    pub portfolio_total_reserve: f64,
79    /// Full $K \times K$ total-reserve MSEP covariance matrix (row-major `K × K`).
80    /// Diagonal entry `(a, a)` is the MSEP of line `a`; off-diagonal `(a, b)` is
81    /// the cross-line reserve covariance.
82    pub total_msep_matrix: Vec<f64>,
83    /// Portfolio total reserve standard error $\sqrt{\mathbf{1}^\top \text{MSEP} \, \mathbf{1}}$.
84    pub portfolio_standard_error: f64,
85    /// Per-line reserve standard errors $\sqrt{\text{MSEP}_{a,a}}$.
86    pub line_standard_errors: Vec<f64>,
87}
88
89/// Analyze $K$ aligned square $n \times n$ cumulative triangles jointly under
90/// the Multivariate Chain Ladder framework.
91pub fn analyze_multivariate_cl(
92    triangles: &[TriangleView<'_>],
93    options: &MultivariateClOptions,
94) -> Result<MultivariateClResult, ValidationError> {
95    let k_lines = triangles.len();
96    if k_lines == 0 {
97        return Err(ValidationError::ShapeMismatch);
98    }
99    let n = triangles[0].n_origins;
100    if n < 3 || triangles[0].n_devs != n {
101        return Err(ValidationError::ShapeMismatch);
102    }
103    for tri in triangles {
104        validate_triangle(tri)?;
105        if options.policy == MonotonicityPolicy::Strict {
106            validate_monotone_cumulative(tri)?;
107        }
108        if tri.n_origins != n || tri.n_devs != n {
109            return Err(ValidationError::ShapeMismatch);
110        }
111    }
112
113    let n_steps = n - 1;
114    let mut b_mats: Vec<Vec<f64>> = Vec::with_capacity(n_steps);
115    let mut sigma_mats: Vec<Vec<f64>> = Vec::with_capacity(n_steps);
116    let mut s_col: Vec<Vec<f64>> = vec![vec![0.0; k_lines]; n_steps];
117
118    let mut resid = vec![0.0; k_lines];
119    // 1. Estimate development matrices B_k and residual covariance Sigma_k.
120    for k in 0..n_steps {
121        let nk = n - 1 - k;
122        for a in 0..k_lines {
123            let mut sum = 0.0;
124            for i in 0..nk {
125                sum += triangles[a].get(i, k);
126            }
127            s_col[k][a] = sum;
128        }
129
130        let mut bk = vec![0.0; k_lines * k_lines];
131        match options.model {
132            MultivariateModel::DiagonalMcl => {
133                fill_diagonal_mcl(triangles, k, nk, &mut bk);
134            }
135            MultivariateModel::GeneralGmcl => {
136                // If nk <= k_lines, fall back to diagonal MCL for numerical stability.
137                if nk <= k_lines {
138                    fill_diagonal_mcl(triangles, k, nk, &mut bk);
139                } else {
140                    // Weighted multivariate regression for each target line a:
141                    // minimize sum_i w_i * (Y_{i,k+1,a} - sum_b B_{a,b} Y_{i,k,b})^2
142                    // with w_i = 1 / Y_{i,k,a} (matching Mack's alpha = 1 weighting).
143                    let mut xtx = vec![0.0; k_lines * k_lines];
144                    let mut xty = vec![0.0; k_lines];
145                    for a in 0..k_lines {
146                        xtx.fill(0.0);
147                        xty.fill(0.0);
148                        for i in 0..nk {
149                            let y_a = triangles[a].get(i, k);
150                            let w = if y_a > 0.0 { 1.0 / y_a } else { 0.0 };
151                            let target = triangles[a].get(i, k + 1);
152                            for b1 in 0..k_lines {
153                                let x1 = triangles[b1].get(i, k);
154                                xty[b1] += w * x1 * target;
155                                for b2 in 0..k_lines {
156                                    let x2 = triangles[b2].get(i, k);
157                                    xtx[b1 * k_lines + b2] += w * x1 * x2;
158                                }
159                            }
160                        }
161                        match solve_general(&xtx, k_lines, &xty) {
162                            Ok(beta) => {
163                                bk[a * k_lines..(a + 1) * k_lines].copy_from_slice(&beta);
164                            }
165                            Err(_) => {
166                                // Ridge/diagonal fallback on collinear lines.
167                                bk[a * k_lines + a] = diagonal_ldf(&triangles[a], k, nk);
168                            }
169                        }
170                    }
171                }
172            }
173        }
174
175        // Estimate K × K residual covariance Sigma_k:
176        // e_{i,a} = (Y_{i,k+1,a} - (B_k Y_{i,k})_a) / sqrt(Y_{i,k,a})
177        let mut sig = vec![0.0; k_lines * k_lines];
178        let dof = match options.model {
179            MultivariateModel::DiagonalMcl => nk.saturating_sub(1),
180            MultivariateModel::GeneralGmcl => {
181                if nk > k_lines {
182                    nk - k_lines
183                } else {
184                    nk.saturating_sub(1)
185                }
186            }
187        };
188        if dof >= 1 {
189            for i in 0..nk {
190                for a in 0..k_lines {
191                    let mut pred = 0.0;
192                    for b in 0..k_lines {
193                        pred += bk[a * k_lines + b] * triangles[b].get(i, k);
194                    }
195                    let y_a = triangles[a].get(i, k);
196                    resid[a] = if y_a > 0.0 {
197                        (triangles[a].get(i, k + 1) - pred) / y_a.sqrt()
198                    } else {
199                        0.0
200                    };
201                }
202                for a in 0..k_lines {
203                    let ra = resid[a];
204                    for b in 0..k_lines {
205                        sig[a * k_lines + b] += ra * resid[b];
206                    }
207                }
208            }
209            let inv_dof = 1.0 / dof as f64;
210            for v in &mut sig {
211                *v *= inv_dof;
212            }
213        }
214        b_mats.push(bk);
215        sigma_mats.push(sig);
216    }
217
218    // Mack (1993) extrapolation for final development step k = n - 2 (where nk = 1, dof = 0).
219    if n_steps >= 3 {
220        let last = n_steps - 1;
221        let prev1 = n_steps - 2;
222        let prev2 = n_steps - 3;
223        for a in 0..k_lines {
224            let s1 = sigma_mats[prev1][a * k_lines + a];
225            let s2 = sigma_mats[prev2][a * k_lines + a];
226            let s_last = if s2 > 0.0 {
227                (s1 * s1 / s2).min(s1.min(s2))
228            } else {
229                0.0
230            };
231            sigma_mats[last][a * k_lines + a] = s_last.max(0.0);
232        }
233        // Extrapolate off-diagonal covariances preserving correlation from prev1.
234        for a in 0..k_lines {
235            for b in (a + 1)..k_lines {
236                let va1 = sigma_mats[prev1][a * k_lines + a];
237                let vb1 = sigma_mats[prev1][b * k_lines + b];
238                let rho = if va1 > 0.0 && vb1 > 0.0 {
239                    (sigma_mats[prev1][a * k_lines + b] / (va1 * vb1).sqrt()).clamp(-1.0, 1.0)
240                } else {
241                    0.0
242                };
243                let va = sigma_mats[last][a * k_lines + a];
244                let vb = sigma_mats[last][b * k_lines + b];
245                let cov = rho * (va * vb).sqrt();
246                sigma_mats[last][a * k_lines + b] = cov;
247                sigma_mats[last][b * k_lines + a] = cov;
248            }
249        }
250    }
251
252    // 2. Project cumulative triangles jointly into a flat n × n × K buffer.
253    let latest_by_line: Vec<Vec<f64>> = triangles.iter().map(latest_diagonal).collect();
254    let mut proj = vec![0.0; n * n * k_lines];
255    let proj_idx = |i: usize, k: usize, a: usize| (i * n + k) * k_lines + a;
256    for i in 0..n {
257        let start = n - 1 - i;
258        for a in 0..k_lines {
259            proj[proj_idx(i, start, a)] = latest_by_line[a][i];
260        }
261        for k in start..n_steps {
262            let src_base = (i * n + k) * k_lines;
263            let dst_base = (i * n + k + 1) * k_lines;
264            let bk = &b_mats[k];
265            for a in 0..k_lines {
266                let mut acc = 0.0;
267                for b in 0..k_lines {
268                    acc += bk[a * k_lines + b] * proj[src_base + b];
269                }
270                proj[dst_base + a] = acc;
271            }
272        }
273    }
274
275    let mut ultimates = vec![vec![0.0; n]; k_lines];
276    let mut reserves = vec![vec![0.0; n]; k_lines];
277    for a in 0..k_lines {
278        for i in 0..n {
279            let ult = proj[proj_idx(i, n - 1, a)];
280            ultimates[a][i] = ult;
281            reserves[a][i] = ult - latest_by_line[a][i];
282        }
283    }
284    let total_reserves_by_line: Vec<f64> = reserves.iter().map(|r| r.iter().sum()).collect();
285    let portfolio_total_reserve: f64 = total_reserves_by_line.iter().sum();
286
287    // 3. Portfolio K × K MSEP covariance matrix via Braun (2004) / Pröhl–Schmidt (2005)
288    //    recursive propagation of process and parameter covariance matrices.
289    let kk = k_lines * k_lines;
290    let mut total_msep = vec![0.0; kk];
291
292    // Precompute parameter-estimation covariance scale per step k:
293    // Exact Braun (2004) Eq. (3.5) for cross-line parameter covariance:
294    //   Cov(f_{k,a}, f_{k,b}) = (sum_{i=0}^{nk-1} sqrt(C_{i,k,a} C_{i,k,b})) / (S_{k,a} S_{k,b}) * Sigma_{k,ab}.
295    let mut param_scale = vec![0.0; n_steps * kk];
296    for k in 0..n_steps {
297        let nk = n - 1 - k;
298        let ps_base = k * kk;
299        for a in 0..k_lines {
300            let sa = s_col[k][a];
301            if sa <= 0.0 {
302                continue;
303            }
304            for b in a..k_lines {
305                let sb = s_col[k][b];
306                if sb > 0.0 {
307                    let mut cross_sqrt = 0.0;
308                    for i in 0..nk {
309                        let ca = triangles[a].get(i, k).max(0.0);
310                        let cb = triangles[b].get(i, k).max(0.0);
311                        cross_sqrt += (ca * cb).sqrt();
312                    }
313                    let val = (cross_sqrt / (sa * sb)) * sigma_mats[k][a * k_lines + b];
314                    param_scale[ps_base + a * k_lines + b] = val;
315                    param_scale[ps_base + b * k_lines + a] = val;
316                }
317            }
318        }
319    }
320
321    // Precompute cumulative transition products P_{k -> n-1} = B_{n-2} ... B_k (K × K).
322    let mut trans_to_ult = vec![vec![0.0; kk]; n];
323    for a in 0..k_lines {
324        trans_to_ult[n - 1][a * k_lines + a] = 1.0;
325    }
326    for k in (0..n_steps).rev() {
327        trans_to_ult[k] = mat_mul(&trans_to_ult[k + 1], &b_mats[k], k_lines);
328    }
329
330    // Hoisted scratch buffers for zero-allocation MSEP accumulation.
331    let mut step_mat = vec![0.0; kk];
332    let mut pm_scratch = vec![0.0; kk];
333    let mut sqrt_c = vec![0.0; k_lines];
334    let mut z_k = vec![0.0; k_lines];
335
336    // Per-origin process variance:
337    // sum_{k=start}^{n-2} P_{k+1->ult} D(C_{i,k})^{1/2} Sigma_k D(C_{i,k})^{1/2} P_{k+1->ult}^T
338    for i in 1..n {
339        let start = n - 1 - i;
340        for k in start..n_steps {
341            let p_next = &trans_to_ult[k + 1];
342            let base = (i * n + k) * k_lines;
343            for a in 0..k_lines {
344                sqrt_c[a] = proj[base + a].max(0.0).sqrt();
345            }
346            let sig_k = &sigma_mats[k];
347            for a in 0..k_lines {
348                let sa = sqrt_c[a];
349                for b in 0..k_lines {
350                    step_mat[a * k_lines + b] = sa * sqrt_c[b] * sig_k[a * k_lines + b];
351                }
352            }
353            add_mat_mul_ab_at(p_next, &step_mat, k_lines, &mut pm_scratch, &mut total_msep);
354        }
355    }
356
357    // Parameter covariance summed across all origins (including cross-origin pairs i, j):
358    //   P_{k+1->ult} [ (Z_k Z_k^T) ∘ Cov(f_k) ] P_{k+1->ult}^T.
359    for k in 0..n_steps {
360        let first_origin = n - 1 - k;
361        z_k.fill(0.0);
362        for i in first_origin..n {
363            let base = (i * n + k) * k_lines;
364            for a in 0..k_lines {
365                z_k[a] += proj[base + a];
366            }
367        }
368        let ps_base = k * kk;
369        for a in 0..k_lines {
370            let za = z_k[a];
371            for b in 0..k_lines {
372                step_mat[a * k_lines + b] = za * z_k[b] * param_scale[ps_base + a * k_lines + b];
373            }
374        }
375        add_mat_mul_ab_at(
376            &trans_to_ult[k + 1],
377            &step_mat,
378            k_lines,
379            &mut pm_scratch,
380            &mut total_msep,
381        );
382    }
383
384    // Symmetrize numerically.
385    for a in 0..k_lines {
386        for b in (a + 1)..k_lines {
387            let avg = f64::midpoint(total_msep[a * k_lines + b], total_msep[b * k_lines + a]);
388            total_msep[a * k_lines + b] = avg;
389            total_msep[b * k_lines + a] = avg;
390        }
391    }
392
393    let portfolio_var: f64 = total_msep.iter().sum();
394    let portfolio_standard_error = portfolio_var.max(0.0).sqrt();
395    let line_standard_errors: Vec<f64> = (0..k_lines)
396        .map(|a| total_msep[a * k_lines + a].max(0.0).sqrt())
397        .collect();
398
399    Ok(MultivariateClResult {
400        n_lines: k_lines,
401        n_origins: n,
402        development_matrices: b_mats,
403        sigma_matrices: sigma_mats,
404        ultimates,
405        reserves,
406        total_reserves_by_line,
407        portfolio_total_reserve,
408        total_msep_matrix: total_msep,
409        portfolio_standard_error,
410        line_standard_errors,
411    })
412}
413
414fn diagonal_ldf(tri: &TriangleView<'_>, k: usize, nk: usize) -> f64 {
415    let mut num = 0.0;
416    let mut den = 0.0;
417    for i in 0..nk {
418        num += tri.get(i, k + 1);
419        den += tri.get(i, k);
420    }
421    if den > 0.0 { num / den } else { 1.0 }
422}
423
424fn fill_diagonal_mcl(triangles: &[TriangleView<'_>], k: usize, nk: usize, bk: &mut [f64]) {
425    let k_lines = triangles.len();
426    for (a, tri) in triangles.iter().enumerate() {
427        bk[a * k_lines + a] = diagonal_ldf(tri, k, nk);
428    }
429}
430
431fn mat_mul(a: &[f64], b: &[f64], k: usize) -> Vec<f64> {
432    let mut out = vec![0.0; k * k];
433    for i in 0..k {
434        for j in 0..k {
435            let mut acc = 0.0;
436            for m in 0..k {
437                acc += a[i * k + m] * b[m * k + j];
438            }
439            out[i * k + j] = acc;
440        }
441    }
442    out
443}
444
445fn add_mat_mul_ab_at(p: &[f64], m: &[f64], k: usize, pm: &mut [f64], out: &mut [f64]) {
446    for i in 0..k {
447        for j in 0..k {
448            let mut acc = 0.0;
449            for r in 0..k {
450                acc += p[i * k + r] * m[r * k + j];
451            }
452            pm[i * k + j] = acc;
453        }
454    }
455    for i in 0..k {
456        for j in 0..k {
457            let mut acc = 0.0;
458            for r in 0..k {
459                acc += pm[i * k + r] * p[j * k + r];
460            }
461            out[i * k + j] += acc;
462        }
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469    use crate::{mack, types::Triangle};
470
471    #[test]
472    fn diagonal_mcl_matches_univariate_mack_exactly() {
473        #[rustfmt::skip]
474        let genins = Triangle::new(10, 10, vec![
475            357848.0, 1124788.0, 1735330.0, 2218270.0, 2745596.0, 3319994.0, 3466336.0, 3606286.0, 3833515.0, 3901463.0,
476            352118.0, 1236139.0, 2170033.0, 3353322.0, 3799067.0, 4120063.0, 4647867.0, 4914039.0, 5339085.0, f64::NAN,
477            290507.0, 1292306.0, 2218525.0, 3235179.0, 3985995.0, 4132918.0, 4628910.0, 4909315.0, f64::NAN, f64::NAN,
478            310608.0, 1418858.0, 2195047.0, 3757447.0, 4029929.0, 4381982.0, 4588268.0, f64::NAN, f64::NAN, f64::NAN,
479            443160.0, 1136350.0, 2128333.0, 2897821.0, 3402672.0, 3873311.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN,
480            396132.0, 1333217.0, 2180715.0, 2985752.0, 3691712.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN,
481            440832.0, 1288463.0, 2419861.0, 3483130.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN,
482            359480.0, 1421128.0, 2864498.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN,
483            376686.0, 1363294.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN,
484            344014.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN,
485        ]);
486        let m_uni = mack::analyze(&genins.view(), 1.0).expect("mack");
487        let m_multi = analyze_multivariate_cl(&[genins.view()], &MultivariateClOptions::default())
488            .expect("mcl");
489        assert!((m_multi.portfolio_total_reserve - m_uni.total_reserve).abs() < 1e-6);
490        assert!(
491            (m_multi.portfolio_standard_error - m_uni.total_standard_error).abs() < 1e-6,
492            "multi SE={} vs uni SE={}",
493            m_multi.portfolio_standard_error,
494            m_uni.total_standard_error
495        );
496    }
497}