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).
122#[derive(Debug, Clone, Copy, Default)]
123pub struct GeneralizedCapeCodEngine;
124
125impl GeneralizedCapeCodEngine {
126    /// Run decay-weighted Cape Cod with strict cumulative monotonicity and no
127    /// explicit loss-trend factors (`tau_k = 1.0`).
128    pub fn project(
129        cumulative: &TriangleView<'_>,
130        factors: &DevelopmentFactors,
131        premium: &[f64],
132        decay: f64,
133    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
134        Self::project_with_options(
135            cumulative,
136            factors,
137            premium,
138            decay,
139            None,
140            MonotonicityPolicy::Strict,
141        )
142    }
143
144    /// Run decay-weighted Cape Cod with optional loss-trend factors `tau_k`
145    /// (trending origin `k` losses to a common base level) and explicit
146    /// [`MonotonicityPolicy`].
147    pub fn project_with_options(
148        cumulative: &TriangleView<'_>,
149        factors: &DevelopmentFactors,
150        premium: &[f64],
151        decay: f64,
152        loss_trend_to_base: Option<&[f64]>,
153        policy: MonotonicityPolicy,
154    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
155        validate_triangle(cumulative)?;
156        if policy == MonotonicityPolicy::Strict {
157            validate_monotone_cumulative(cumulative)?;
158        }
159        let n = cumulative.n_origins;
160        validate_premium(premium, n)?;
161        validate_development_factor_slices(
162            &factors.ldfs,
163            &factors.cdfs,
164            factors.tail,
165            cumulative.n_devs,
166            "Generalized Cape Cod factor",
167        )?;
168        if !decay.is_finite() {
169            return Err(ValidationError::NotFinite);
170        }
171        if !(decay > 0.0 && decay <= 1.0) {
172            return Err(ValidationError::InvalidParameter(
173                "Generalized Cape Cod decay factor must lie in (0, 1]",
174            ));
175        }
176        if let Some(trend) = loss_trend_to_base {
177            if trend.len() != n {
178                return Err(ValidationError::ShapeMismatch);
179            }
180            validate_positive_finite_slice(trend, "loss_trend_to_base")?;
181        }
182
183        let mut latest = vec![0.0; n];
184        let mut latest_dev = vec![0; n];
185        latest_observed_by_origin(
186            cumulative.data,
187            cumulative.n_origins,
188            cumulative.n_devs,
189            &mut latest,
190            &mut latest_dev,
191        );
192        validate_latest_and_dev(&latest, &latest_dev, &factors.cdfs)?;
193
194        let mut reported_percentage = vec![0.0; n];
195        let mut used_premium = vec![0.0; n];
196        for i in 0..n {
197            let cdf = factors.cdfs[latest_dev[i]];
198            reported_percentage[i] = 1.0 / cdf;
199            used_premium[i] = premium[i] * reported_percentage[i];
200        }
201
202        let mut decay_powers = vec![1.0; n];
203        for d in 1..n {
204            decay_powers[d] = decay_powers[d - 1] * decay;
205        }
206
207        let mut elr_by_origin = vec![0.0; n];
208        let mut normalized_weights = vec![0.0; n * n];
209        let mut expected_ultimate = vec![0.0; n];
210
211        for i in 0..n {
212            let mut num = 0.0;
213            let mut den = 0.0;
214            for k in 0..n {
215                let w = decay_powers[i.abs_diff(k)];
216                let tau_k = loss_trend_to_base.map_or(1.0, |t| t[k]);
217                let eff_w = w * used_premium[k];
218                normalized_weights[i * n + k] = eff_w;
219                num += w * latest[k] * tau_k;
220                den += eff_w;
221            }
222            if !den.is_finite() || den <= 0.0 {
223                return Err(ValidationError::DivideByZero(
224                    "Generalized Cape Cod used premium",
225                ));
226            }
227            for k in 0..n {
228                normalized_weights[i * n + k] /= den;
229            }
230            let tau_i = loss_trend_to_base.map_or(1.0, |t| t[i]);
231            let elr_i = (num / den) / tau_i;
232            if !elr_i.is_finite() || elr_i < 0.0 {
233                return Err(ValidationError::NotFinite);
234            }
235            elr_by_origin[i] = elr_i;
236            expected_ultimate[i] = premium[i] * elr_i;
237        }
238
239        let bf_projection = BornhuetterFergusonEngine::project_from_expected_ultimate_with_policy(
240            cumulative,
241            factors,
242            &expected_ultimate,
243            policy,
244        )?;
245
246        Ok(GeneralizedCapeCodProjection {
247            decay,
248            elr_by_origin,
249            normalized_weights,
250            latest,
251            latest_dev,
252            reported_percentage,
253            used_premium,
254            expected_ultimate,
255            bf_projection,
256        })
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use crate::cape_cod::CapeCodEngine;
264    use crate::chain_ladder::ChainLadderEngine;
265    use crate::ldf::DevelopmentFactorEngine;
266    use crate::types::Triangle;
267
268    const NAN: f64 = f64::NAN;
269
270    fn sample_triangle() -> (Triangle, Vec<f64>) {
271        #[rustfmt::skip]
272        let data = vec![
273            100.0, 160.0, 200.0, 210.0,
274            120.0, 190.0, 245.0,   NAN,
275            150.0, 245.0,   NAN,   NAN,
276            200.0,   NAN,   NAN,   NAN,
277        ];
278        (Triangle::new(4, 4, data), vec![300.0, 320.0, 350.0, 400.0])
279    }
280
281    #[test]
282    fn decay_one_matches_standard_cape_cod_exactly() {
283        let (tri, prem) = sample_triangle();
284        let factors = DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0).unwrap();
285        let cc = CapeCodEngine::project(&tri.view(), &factors, &prem).unwrap();
286        let gcc = GeneralizedCapeCodEngine::project(&tri.view(), &factors, &prem, 1.0).unwrap();
287
288        for i in 0..4 {
289            assert!((gcc.elr_by_origin[i] - cc.elr).abs() < 1e-12);
290            assert!((gcc.bf_projection.reserves[i] - cc.bf_projection.reserves[i]).abs() < 1e-10);
291        }
292    }
293
294    #[test]
295    fn decay_near_zero_converges_to_chain_ladder() {
296        let (tri, prem) = sample_triangle();
297        let factors = DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0).unwrap();
298        let cl = ChainLadderEngine::project(&tri.view(), &factors).unwrap();
299        let gcc = GeneralizedCapeCodEngine::project(&tri.view(), &factors, &prem, 1e-12).unwrap();
300
301        for i in 0..4 {
302            assert!(
303                (gcc.bf_projection.reserves[i] - cl.reserves[i]).abs() < 1e-6,
304                "origin {i}: gcc={} cl={}",
305                gcc.bf_projection.reserves[i],
306                cl.reserves[i]
307            );
308        }
309    }
310
311    #[test]
312    fn rejects_invalid_decay() {
313        let (tri, prem) = sample_triangle();
314        let factors = DevelopmentFactorEngine::volume_weighted(&tri.view(), 1.0).unwrap();
315        assert!(GeneralizedCapeCodEngine::project(&tri.view(), &factors, &prem, 0.0).is_err());
316        assert!(GeneralizedCapeCodEngine::project(&tri.view(), &factors, &prem, 1.1).is_err());
317    }
318}