Skip to main content

reserving_kernels/
generalized_cape_cod.rs

1//! Generalized (Decay-Weighted) Cape Cod reserving method — Gluck (1997).
2//!
3//! Implements:
4//!
5//! * S. M. Gluck, *"Balancing Development and Trend in Loss Reserve Analysis"*,
6//!   *PCAS*, Vol. LXXXIV (1997), pp. 482–532.
7//! * J. Friedland, *Estimating Unpaid Claims Using Basic Techniques*, CAS
8//!   (2010), Chapter 10 (Generalized Cape Cod).
9//!
10//! ## Formulation
11//!
12//! Standard Cape Cod weights every origin year equally to estimate a single
13//! constant expected loss ratio across the triangle. Gluck (1997) introduces
14//! geometric decay weights `w_{i,k} = delta^{|i - k|}` (`delta in (0, 1]`)
15//! centered on each target origin year `i`:
16//!
17//! `ELR_i = [ sum_k w_{i,k} · C_{k, d_k} · tau_k ] / [ tau_i · sum_k w_{i,k} · P_k · p_{d_k} ]`
18//!
19//! where `p_{d_k} = 1 / CDF_{d_k}` is the percent reported at origin `k`'s
20//! latest observed age `d_k`, `P_k` is on-level earned premium / exposure, and
21//! `tau_k` is an optional loss-trend factor trending origin `k` to a common
22//! cost level (`tau_k = 1` when omitted).
23//!
24//! ## Limiting Identities
25//!
26//! * **`delta = 1.0`** (with unit trend): reduces identically to standard
27//!   Stanard–Bühlmann Cape Cod ([`crate::cape_cod`]).
28//! * **`delta -> 0+`**: puts full weight on origin `i` alone, so
29//!   `ELR_i -> C_{i, d_i} / (P_i · p_{d_i}) = U_i^{CL} / P_i` and the resulting
30//!   BF projection reduces identically to Chain Ladder ([`crate::chain_ladder`]).
31
32use crate::bf::{
33    BornhuetterFergusonEngine, BornhuetterFergusonProjection,
34    project_unchecked as bf_project_unchecked,
35};
36use crate::chain_ladder::latest_observed_by_origin;
37use crate::ldf::{DevelopmentFactors, cdf_from_ldf, pct_reported};
38use crate::triangle::latest_diagonal;
39use crate::types::TriangleView;
40use crate::validate::{
41    MonotonicityPolicy, ValidationError, validate_development_factor_slices,
42    validate_latest_and_dev, validate_monotone_cumulative, validate_positive_finite_slice,
43    validate_premium, validate_triangle,
44};
45
46/// Result of a Generalized (Decay-Weighted) Cape Cod projection.
47#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
48pub struct GeneralizedCapeCodProjection {
49    /// Decay factor `delta` in `(0, 1]`.
50    pub decay: f64,
51    /// Origin-specific expected loss ratios `ELR_i` (length `n`).
52    pub elr_by_origin: Vec<f64>,
53    /// Row-major `n × n` normalized weight matrix (`row i` sums to `1.0`),
54    /// showing the relative contribution of origin `k`'s used premium to `ELR_i`.
55    pub normalized_weights: Vec<f64>,
56    /// Latest observed cumulative loss by origin.
57    pub latest: Vec<f64>,
58    /// Latest observed development index by origin.
59    pub latest_dev: Vec<usize>,
60    /// Percent reported `p_{d_i} = 1 / CDF_{d_i}` by origin.
61    pub reported_percentage: Vec<f64>,
62    /// Used-up premium `P_i * p_{d_i}` by origin.
63    pub used_premium: Vec<f64>,
64    /// Expected ultimate `P_i * ELR_i` by origin.
65    pub expected_ultimate: Vec<f64>,
66    /// Underlying BF projection driven by `expected_ultimate`.
67    pub bf_projection: BornhuetterFergusonProjection,
68}
69
70/// Compute origin-specific Gluck (1997) decay-weighted expected loss ratios
71/// without input validation.
72pub fn elr_by_origin_unchecked(
73    t: &TriangleView<'_>,
74    ldf: &[f64],
75    tail: f64,
76    premium: &[f64],
77    decay: f64,
78) -> Vec<f64> {
79    let n = t.n_origins.min(t.n_devs);
80    debug_assert_eq!(premium.len(), n);
81    let cdf = cdf_from_ldf(ldf, tail);
82    let pct = pct_reported(&cdf);
83    let latest = latest_diagonal(t);
84
85    let mut used = vec![0.0; n];
86    for k in 0..n {
87        used[k] = premium[k] * pct[n - 1 - k];
88    }
89
90    let mut elrs = vec![0.0; n];
91    for i in 0..n {
92        let mut num = 0.0;
93        let mut den = 0.0;
94        for k in 0..n {
95            let w = decay.powi(i.abs_diff(k) as i32);
96            num += w * latest[k];
97            den += w * used[k];
98        }
99        elrs[i] = if den > 0.0 { num / den } else { f64::NAN };
100    }
101    elrs
102}
103
104/// Unchecked Generalized Cape Cod projection returning `(elr_by_origin, bf_projection)`.
105pub fn project_unchecked(
106    t: &TriangleView<'_>,
107    ldf: &[f64],
108    tail: f64,
109    premium: &[f64],
110    decay: f64,
111) -> (Vec<f64>, BornhuetterFergusonProjection) {
112    let elrs = elr_by_origin_unchecked(t, ldf, tail, premium, decay);
113    let expected: Vec<f64> = premium
114        .iter()
115        .zip(elrs.iter())
116        .map(|(&p, &r)| p * r)
117        .collect();
118    (elrs, bf_project_unchecked(t, ldf, tail, &expected))
119}
120
121/// Checked Generalized Cape Cod service (Gluck 1997).
122pub struct GeneralizedCapeCodEngine;
123
124impl GeneralizedCapeCodEngine {
125    /// Run decay-weighted Cape Cod with strict cumulative monotonicity and no
126    /// explicit loss-trend factors (`tau_k = 1.0`).
127    pub fn project(
128        cumulative: &TriangleView<'_>,
129        factors: &DevelopmentFactors,
130        premium: &[f64],
131        decay: f64,
132    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
133        Self::project_with_options(
134            cumulative,
135            factors,
136            premium,
137            decay,
138            None,
139            MonotonicityPolicy::Strict,
140        )
141    }
142
143    /// Run decay-weighted Cape Cod with optional loss-trend factors `tau_k`
144    /// (trending origin `k` losses to a common base level) and explicit
145    /// [`MonotonicityPolicy`].
146    pub fn project_with_options(
147        cumulative: &TriangleView<'_>,
148        factors: &DevelopmentFactors,
149        premium: &[f64],
150        decay: f64,
151        loss_trend_to_base: Option<&[f64]>,
152        policy: MonotonicityPolicy,
153    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
154        validate_triangle(cumulative)?;
155        if policy == MonotonicityPolicy::Strict {
156            validate_monotone_cumulative(cumulative)?;
157        }
158        let n = cumulative.n_origins;
159        validate_premium(premium, n)?;
160        validate_development_factor_slices(
161            &factors.ldfs,
162            &factors.cdfs,
163            factors.tail,
164            cumulative.n_devs,
165            "Generalized Cape Cod factor",
166        )?;
167        if !decay.is_finite() {
168            return Err(ValidationError::NotFinite);
169        }
170        if !(decay > 0.0 && decay <= 1.0) {
171            return Err(ValidationError::InvalidParameter(
172                "Generalized Cape Cod decay factor must lie in (0, 1]",
173            ));
174        }
175        if let Some(trend) = loss_trend_to_base {
176            if trend.len() != n {
177                return Err(ValidationError::ShapeMismatch);
178            }
179            validate_positive_finite_slice(trend, "loss_trend_to_base")?;
180        }
181
182        let mut latest = vec![0.0; n];
183        let mut latest_dev = vec![0; n];
184        latest_observed_by_origin(
185            cumulative.data,
186            cumulative.n_origins,
187            cumulative.n_devs,
188            &mut latest,
189            &mut latest_dev,
190        );
191        validate_latest_and_dev(&latest, &latest_dev, &factors.cdfs)?;
192
193        let mut reported_percentage = vec![0.0; n];
194        let mut used_premium = vec![0.0; n];
195        for i in 0..n {
196            let cdf = factors.cdfs[latest_dev[i]];
197            reported_percentage[i] = 1.0 / cdf;
198            used_premium[i] = premium[i] * reported_percentage[i];
199        }
200
201        let mut decay_powers = vec![1.0; n];
202        for d in 1..n {
203            decay_powers[d] = decay_powers[d - 1] * decay;
204        }
205
206        let mut elr_by_origin = vec![0.0; n];
207        let mut normalized_weights = vec![0.0; n * n];
208        let mut expected_ultimate = vec![0.0; n];
209
210        for i in 0..n {
211            let mut num = 0.0;
212            let mut den = 0.0;
213            for k in 0..n {
214                let w = decay_powers[i.abs_diff(k)];
215                let tau_k = loss_trend_to_base.map_or(1.0, |t| t[k]);
216                let eff_w = w * used_premium[k];
217                normalized_weights[i * n + k] = eff_w;
218                num += w * latest[k] * tau_k;
219                den += eff_w;
220            }
221            if !den.is_finite() || den <= 0.0 {
222                return Err(ValidationError::DivideByZero(
223                    "Generalized Cape Cod used premium",
224                ));
225            }
226            for k in 0..n {
227                normalized_weights[i * n + k] /= den;
228            }
229            let tau_i = loss_trend_to_base.map_or(1.0, |t| t[i]);
230            let elr_i = (num / den) / tau_i;
231            if !elr_i.is_finite() || elr_i < 0.0 {
232                return Err(ValidationError::NotFinite);
233            }
234            elr_by_origin[i] = elr_i;
235            expected_ultimate[i] = premium[i] * elr_i;
236        }
237
238        let bf_projection = BornhuetterFergusonEngine::project_from_expected_ultimate_with_policy(
239            cumulative,
240            factors,
241            &expected_ultimate,
242            policy,
243        )?;
244
245        Ok(GeneralizedCapeCodProjection {
246            decay,
247            elr_by_origin,
248            normalized_weights,
249            latest,
250            latest_dev,
251            reported_percentage,
252            used_premium,
253            expected_ultimate,
254            bf_projection,
255        })
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use crate::cape_cod::CapeCodEngine;
263    use crate::chain_ladder::ChainLadderEngine;
264    use crate::ldf::DevelopmentFactorEngine;
265    use crate::types::Triangle;
266
267    const NAN: f64 = f64::NAN;
268
269    fn sample_triangle() -> (Triangle, Vec<f64>) {
270        #[rustfmt::skip]
271        let data = vec![
272            100.0, 160.0, 200.0, 210.0,
273            120.0, 190.0, 245.0,   NAN,
274            150.0, 245.0,   NAN,   NAN,
275            200.0,   NAN,   NAN,   NAN,
276        ];
277        (Triangle::new(4, 4, data), vec![300.0, 320.0, 350.0, 400.0])
278    }
279
280    #[test]
281    fn decay_one_matches_standard_cape_cod_exactly() {
282        let (tri, prem) = sample_triangle();
283        let factors = DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0).unwrap();
284        let cc = CapeCodEngine::project(&tri.view(), &factors, &prem).unwrap();
285        let gcc = GeneralizedCapeCodEngine::project(&tri.view(), &factors, &prem, 1.0).unwrap();
286
287        for i in 0..4 {
288            assert!((gcc.elr_by_origin[i] - cc.elr).abs() < 1e-12);
289            assert!((gcc.bf_projection.reserves[i] - cc.bf_projection.reserves[i]).abs() < 1e-10);
290        }
291    }
292
293    #[test]
294    fn decay_near_zero_converges_to_chain_ladder() {
295        let (tri, prem) = sample_triangle();
296        let factors = DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0).unwrap();
297        let cl = ChainLadderEngine::project(&tri.view(), &factors).unwrap();
298        let gcc = GeneralizedCapeCodEngine::project(&tri.view(), &factors, &prem, 1e-12).unwrap();
299
300        for i in 0..4 {
301            assert!(
302                (gcc.bf_projection.reserves[i] - cl.reserves[i]).abs() < 1e-6,
303                "origin {i}: gcc={} cl={}",
304                gcc.bf_projection.reserves[i],
305                cl.reserves[i]
306            );
307        }
308    }
309
310    #[test]
311    fn rejects_invalid_decay() {
312        let (tri, prem) = sample_triangle();
313        let factors = DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0).unwrap();
314        assert!(GeneralizedCapeCodEngine::project(&tri.view(), &factors, &prem, 0.0).is_err());
315        assert!(GeneralizedCapeCodEngine::project(&tri.view(), &factors, &prem, 1.1).is_err());
316    }
317}