Skip to main content

reserving_kernels/subannual/
reserving.rs

1//! Asymmetric chain-ladder and interim-valuation Bornhuetter–Ferguson / Cape Cod
2//! reserving kernels (Friedland 2010).
3//!
4//! * [`asymmetric_chain_ladder`] — computes link ratios and ultimates directly
5//!   on rectangular `n_origins × n_devs` triangles with ragged/staggered
6//!   diagonals (e.g., annual origins × semiannual/quarterly development at an
7//!   interim valuation date).
8//! * [`interim_bf`] — Bornhuetter–Ferguson using interpolated sub-annual CDFs
9//!   and pro-rated stub-period expected ultimate / exposure.
10//! * [`interim_cape_cod`] — Cape Cod using interpolated sub-annual CDFs and
11//!   pro-rated stub-period earned premium.
12
13use crate::deterministic::ldf::{
14    LdfSelectionMethod, cdfs_from_ldfs, volume_weighted_ldfs_observed_counts,
15};
16use crate::preprocessing::ragged::{
17    ex_hi_lo_observed_counts, simple_average_observed_counts,
18    volume_weighted_last_n_observed_counts,
19};
20use crate::subannual::grid::AsymmetricAgeGrid;
21use crate::validate::{
22    MonotonicityPolicy, ValidationError, validate_nonnegative_finite_slice,
23    validate_positive_finite_slice, validate_tail,
24};
25
26/// Result of [`asymmetric_chain_ladder`] on a rectangular/staggered triangle.
27#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
28pub struct AsymmetricChainLadderProjection {
29    /// Selected step-to-step LDFs (length `n_devs - 1`).
30    pub ldfs: Vec<f64>,
31    /// Cumulative development factors to ultimate by development column (length `n_devs`).
32    pub cdfs: Vec<f64>,
33    /// Applied tail factor (`>= 1.0`).
34    pub tail: f64,
35    /// Latest observed cumulative loss by origin.
36    pub latest: Vec<f64>,
37    /// Development column index of each origin's latest observed cell.
38    pub latest_dev_indices: Vec<usize>,
39    /// Valuation age in months of each origin's latest observed cell.
40    pub latest_ages_months: Vec<f64>,
41    /// Applied CDF-to-ultimate for each origin (`cdfs[latest_dev_indices[i]]`).
42    pub origin_cdfs: Vec<f64>,
43    /// Projected ultimate loss by origin.
44    pub ultimates: Vec<f64>,
45    /// Projected IBNR reserve (`ultimate - latest`) by origin.
46    pub ibnr: Vec<f64>,
47    /// Total latest observed cumulative loss across origins.
48    pub total_latest: f64,
49    /// Total projected ultimate loss across origins.
50    pub total_ultimate: f64,
51    /// Total projected IBNR reserve across origins.
52    pub total_ibnr: f64,
53}
54
55/// Validate a rectangular cumulative buffer against an [`AsymmetricAgeGrid`].
56pub(crate) fn validate_asymmetric_cumulative(
57    cum: &[f64],
58    grid: &AsymmetricAgeGrid,
59    policy: MonotonicityPolicy,
60) -> Result<(), ValidationError> {
61    if grid.n_origins == 0 || grid.n_devs < 2 {
62        return Err(ValidationError::ShapeMismatch);
63    }
64    if cum.len() != grid.n_origins * grid.n_devs || grid.observed_counts.len() != grid.n_origins {
65        return Err(ValidationError::ShapeMismatch);
66    }
67    for i in 0..grid.n_origins {
68        let cnt = grid.observed_counts[i];
69        if cnt == 0 || cnt > grid.n_devs {
70            return Err(ValidationError::ShapeMismatch);
71        }
72        let mut prev = None;
73        for j in 0..cnt {
74            let v = cum[i * grid.n_devs + j];
75            if !v.is_finite() {
76                return Err(ValidationError::NotFinite);
77            }
78            if v < 0.0 {
79                return Err(ValidationError::Negative);
80            }
81            if policy == MonotonicityPolicy::Strict
82                && let Some(p) = prev
83                && v < p
84            {
85                return Err(ValidationError::NonMonotoneCumulative {
86                    origin: i,
87                    dev: j,
88                    previous: p,
89                    value: v,
90                });
91            }
92            prev = Some(v);
93        }
94    }
95    Ok(())
96}
97
98/// Compute median link ratios across arbitrary observed row widths.
99fn median_observed_counts(cum: &[f64], n_o: usize, n_d: usize, counts: &[usize], out: &mut [f64]) {
100    let n_links = n_d.saturating_sub(1);
101    let mut buf = Vec::with_capacity(n_o);
102    for j in 0..n_links {
103        buf.clear();
104        for i in 0..n_o {
105            if counts[i] <= j + 1 {
106                continue;
107            }
108            let x = cum[i * n_d + j];
109            let y = cum[i * n_d + j + 1];
110            if x > 0.0 && x.is_finite() && y.is_finite() {
111                buf.push(y / x);
112            }
113        }
114        if buf.is_empty() {
115            out[j] = f64::NAN;
116        } else {
117            buf.sort_by(f64::total_cmp);
118            let mid = buf.len() / 2;
119            out[j] = if buf.len() % 2 == 1 {
120                buf[mid]
121            } else {
122                f64::midpoint(buf[mid - 1], buf[mid])
123            };
124        }
125    }
126}
127
128/// Compute link ratios and chain-ladder ultimates directly on an asymmetric
129/// (e.g., annual-origin × semiannual/quarterly-dev) triangle with staggered or
130/// ragged diagonals at interim valuation dates (Friedland 2010).
131///
132/// Only links `j -> j + 1` with at least one eligible origin pair (`counts[i] > j + 1`)
133/// are estimated from data; any unobserved trailing columns beyond `max(observed_counts)`
134/// are assigned neutral factor `1.0`.
135pub fn asymmetric_chain_ladder(
136    cum: &[f64],
137    grid: &AsymmetricAgeGrid,
138    method: LdfSelectionMethod,
139    tail: f64,
140    policy: MonotonicityPolicy,
141) -> Result<AsymmetricChainLadderProjection, ValidationError> {
142    validate_asymmetric_cumulative(cum, grid, policy)?;
143    validate_tail(tail)?;
144
145    let n_o = grid.n_origins;
146    let n_d = grid.n_devs;
147    let n_links = n_d - 1;
148    let counts = &grid.observed_counts;
149    let max_obs = counts.iter().copied().max().unwrap_or(0);
150    if max_obs < 2 {
151        return Err(ValidationError::InvalidParameter(
152            "asymmetric_chain_ladder requires at least one origin with >= 2 observed cells",
153        ));
154    }
155
156    let mut ldfs = vec![1.0; n_links];
157    match method {
158        LdfSelectionMethod::VolumeWeighted => {
159            volume_weighted_ldfs_observed_counts(cum, n_o, n_d, counts, &mut ldfs);
160        }
161        LdfSelectionMethod::SimpleAverage => {
162            simple_average_observed_counts(cum, n_o, n_d, counts, None, &mut ldfs);
163        }
164        LdfSelectionMethod::ExHiLo => {
165            ex_hi_lo_observed_counts(cum, n_o, n_d, counts, &mut ldfs);
166        }
167        LdfSelectionMethod::Median => {
168            median_observed_counts(cum, n_o, n_d, counts, &mut ldfs);
169        }
170        LdfSelectionMethod::LastNVolumeWeighted { last_n } => {
171            if last_n == 0 {
172                return Err(ValidationError::InvalidParameter("last_n must be >= 1"));
173            }
174            volume_weighted_last_n_observed_counts(cum, n_o, n_d, counts, last_n, &mut ldfs);
175        }
176        LdfSelectionMethod::LastNSimpleAverage { last_n } => {
177            if last_n == 0 {
178                return Err(ValidationError::InvalidParameter("last_n must be >= 1"));
179            }
180            simple_average_observed_counts(cum, n_o, n_d, counts, Some(last_n), &mut ldfs);
181        }
182        LdfSelectionMethod::Selected => {
183            return Err(ValidationError::InvalidParameter(
184                "Selected method requires explicit LDFs; use a computed LdfSelectionMethod",
185            ));
186        }
187    }
188
189    // Trailing unobserved columns beyond max_obs - 1 default to neutral 1.0;
190    // observed links 0..(max_obs - 1) must be finite and strictly positive.
191    for j in (max_obs - 1)..n_links {
192        if !ldfs[j].is_finite() {
193            ldfs[j] = 1.0;
194        }
195    }
196    validate_positive_finite_slice(&ldfs, "asymmetric LDF")?;
197
198    let mut cdfs = vec![0.0; n_d];
199    cdfs_from_ldfs(&ldfs, tail, &mut cdfs);
200
201    let mut latest = Vec::with_capacity(n_o);
202    let mut latest_dev_indices = Vec::with_capacity(n_o);
203    let mut latest_ages_months = Vec::with_capacity(n_o);
204    let mut origin_cdfs = Vec::with_capacity(n_o);
205    let mut ultimates = Vec::with_capacity(n_o);
206    let mut ibnr = Vec::with_capacity(n_o);
207
208    for i in 0..n_o {
209        let d_i = counts[i] - 1;
210        let lat = cum[i * n_d + d_i];
211        let cdf = cdfs[d_i];
212        let ult = lat * cdf;
213        latest.push(lat);
214        latest_dev_indices.push(d_i);
215        latest_ages_months.push(grid.cell_age(i, d_i));
216        origin_cdfs.push(cdf);
217        ultimates.push(ult);
218        ibnr.push(ult - lat);
219    }
220
221    let total_latest = latest.iter().sum();
222    let total_ultimate = ultimates.iter().sum();
223    let total_ibnr = ibnr.iter().sum();
224
225    Ok(AsymmetricChainLadderProjection {
226        ldfs,
227        cdfs,
228        tail,
229        latest,
230        latest_dev_indices,
231        latest_ages_months,
232        origin_cdfs,
233        ultimates,
234        ibnr,
235        total_latest,
236        total_ultimate,
237        total_ibnr,
238    })
239}
240
241/// Output from [`interim_bf`] (interim-valuation Bornhuetter–Ferguson with
242/// pro-rated stub exposure and sub-annual CDFs).
243#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
244pub struct InterimBfProjection {
245    /// Latest observed cumulative losses by origin.
246    pub latest: Vec<f64>,
247    /// Applied sub-annual CDF-to-ultimate for each origin.
248    pub cdfs: Vec<f64>,
249    /// Earned exposure fraction `e_i in (0, 1]` for each origin.
250    pub exposure_fractions: Vec<f64>,
251    /// Pro-rated earned expected ultimate (`full_period_expected_ultimate[i] * e_i`).
252    pub earned_expected_ultimate: Vec<f64>,
253    /// Implied percent reported (`1 / cdfs[i]`).
254    pub pct_reported: Vec<f64>,
255    /// Projected IBNR reserve (`earned_expected_ultimate[i] * (1 - 1 / cdfs[i])`).
256    pub ibnr: Vec<f64>,
257    /// Projected earned ultimate (`latest[i] + ibnr[i]`).
258    pub ultimates: Vec<f64>,
259    /// Total latest observed cumulative losses.
260    pub total_latest: f64,
261    /// Total projected IBNR reserve.
262    pub total_ibnr: f64,
263    /// Total projected earned ultimate losses.
264    pub total_ultimate: f64,
265}
266
267/// Run Bornhuetter–Ferguson at an interim valuation date using interpolated
268/// sub-annual CDFs and pro-rated stub-period expected ultimate / exposure
269/// (Friedland 2010).
270///
271/// Reduces identically to standard Bornhuetter–Ferguson when all
272/// `exposure_fractions == 1.0`.
273pub fn interim_bf(
274    latest: &[f64],
275    cdfs_at_origin: &[f64],
276    full_period_expected_ultimate: &[f64],
277    exposure_fractions: &[f64],
278) -> Result<InterimBfProjection, ValidationError> {
279    let n = latest.len();
280    if n == 0
281        || cdfs_at_origin.len() != n
282        || full_period_expected_ultimate.len() != n
283        || exposure_fractions.len() != n
284    {
285        return Err(ValidationError::ShapeMismatch);
286    }
287    validate_nonnegative_finite_slice(latest)?;
288    validate_positive_finite_slice(cdfs_at_origin, "origin CDF")?;
289    validate_nonnegative_finite_slice(full_period_expected_ultimate)?;
290    validate_positive_finite_slice(exposure_fractions, "exposure_fractions")?;
291    if exposure_fractions.iter().any(|&e| e > 1.0 + 1e-9) {
292        return Err(ValidationError::InvalidParameter(
293            "exposure_fractions must lie in (0, 1]",
294        ));
295    }
296
297    let mut earned_expected_ultimate = Vec::with_capacity(n);
298    let mut pct_reported = Vec::with_capacity(n);
299    let mut ibnr = Vec::with_capacity(n);
300    let mut ultimates = Vec::with_capacity(n);
301
302    for i in 0..n {
303        let earned_exp = full_period_expected_ultimate[i] * exposure_fractions[i];
304        let p = 1.0 / cdfs_at_origin[i];
305        let r = earned_exp * (1.0 - p);
306        let u = latest[i] + r;
307        earned_expected_ultimate.push(earned_exp);
308        pct_reported.push(p);
309        ibnr.push(r);
310        ultimates.push(u);
311    }
312
313    Ok(InterimBfProjection {
314        latest: latest.to_vec(),
315        cdfs: cdfs_at_origin.to_vec(),
316        exposure_fractions: exposure_fractions.to_vec(),
317        earned_expected_ultimate,
318        pct_reported,
319        ibnr: ibnr.clone(),
320        ultimates: ultimates.clone(),
321        total_latest: latest.iter().sum(),
322        total_ibnr: ibnr.iter().sum(),
323        total_ultimate: ultimates.iter().sum(),
324    })
325}
326
327/// Output from [`interim_cape_cod`] (interim-valuation Cape Cod with pro-rated
328/// stub earned premium and sub-annual CDFs).
329#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
330pub struct InterimCapeCodProjection {
331    /// Latest observed cumulative losses by origin.
332    pub latest: Vec<f64>,
333    /// Applied sub-annual CDF-to-ultimate for each origin.
334    pub cdfs: Vec<f64>,
335    /// Earned exposure fraction `e_i in (0, 1]` for each origin.
336    pub exposure_fractions: Vec<f64>,
337    /// Pro-rated earned premium (`full_period_premium[i] * e_i`).
338    pub earned_premium: Vec<f64>,
339    /// Used-up earned premium (`earned_premium[i] / cdfs[i]`).
340    pub used_up_premium: Vec<f64>,
341    /// Pooled Cape Cod expected loss ratio `sum(latest) / sum(used_up_premium)`.
342    pub elr: f64,
343    /// Projected IBNR reserve (`earned_premium[i] * elr * (1 - 1 / cdfs[i])`).
344    pub ibnr: Vec<f64>,
345    /// Projected earned ultimate (`latest[i] + ibnr[i]`).
346    pub ultimates: Vec<f64>,
347    /// Total latest observed cumulative losses.
348    pub total_latest: f64,
349    /// Total projected IBNR reserve.
350    pub total_ibnr: f64,
351    /// Total projected earned ultimate losses.
352    pub total_ultimate: f64,
353}
354
355/// Run Cape Cod at an interim valuation date using interpolated sub-annual CDFs
356/// and pro-rated stub-period earned premium (Friedland 2010).
357///
358/// Reduces identically to standard Cape Cod when all `exposure_fractions == 1.0`.
359pub fn interim_cape_cod(
360    latest: &[f64],
361    cdfs_at_origin: &[f64],
362    full_period_premium: &[f64],
363    exposure_fractions: &[f64],
364) -> Result<InterimCapeCodProjection, ValidationError> {
365    let n = latest.len();
366    if n == 0
367        || cdfs_at_origin.len() != n
368        || full_period_premium.len() != n
369        || exposure_fractions.len() != n
370    {
371        return Err(ValidationError::ShapeMismatch);
372    }
373    validate_nonnegative_finite_slice(latest)?;
374    validate_positive_finite_slice(cdfs_at_origin, "origin CDF")?;
375    validate_positive_finite_slice(full_period_premium, "premium")?;
376    validate_positive_finite_slice(exposure_fractions, "exposure_fractions")?;
377    if exposure_fractions.iter().any(|&e| e > 1.0 + 1e-9) {
378        return Err(ValidationError::InvalidParameter(
379            "exposure_fractions must lie in (0, 1]",
380        ));
381    }
382
383    let mut earned_premium = Vec::with_capacity(n);
384    let mut used_up_premium = Vec::with_capacity(n);
385    for i in 0..n {
386        let ep = full_period_premium[i] * exposure_fractions[i];
387        let uup = ep / cdfs_at_origin[i];
388        earned_premium.push(ep);
389        used_up_premium.push(uup);
390    }
391
392    let total_latest: f64 = latest.iter().sum();
393    let total_uup: f64 = used_up_premium.iter().sum();
394    if !(total_uup > 0.0) || !total_uup.is_finite() {
395        return Err(ValidationError::DivideByZero("used-up premium"));
396    }
397    let elr = total_latest / total_uup;
398
399    let mut ibnr = Vec::with_capacity(n);
400    let mut ultimates = Vec::with_capacity(n);
401    for i in 0..n {
402        let r = earned_premium[i] * elr * (1.0 - 1.0 / cdfs_at_origin[i]);
403        let u = latest[i] + r;
404        ibnr.push(r);
405        ultimates.push(u);
406    }
407
408    Ok(InterimCapeCodProjection {
409        latest: latest.to_vec(),
410        cdfs: cdfs_at_origin.to_vec(),
411        exposure_fractions: exposure_fractions.to_vec(),
412        earned_premium,
413        used_up_premium,
414        elr,
415        ibnr: ibnr.clone(),
416        ultimates: ultimates.clone(),
417        total_latest,
418        total_ibnr: ibnr.iter().sum(),
419        total_ultimate: ultimates.iter().sum(),
420    })
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426    use crate::subannual::grid::asymmetric_age_grid;
427
428    #[test]
429    fn asymmetric_cl_recovers_exact_synthetic_pattern() {
430        // 4 annual origins × 6 semiannual devs, valued at full year 4 (48m) -> counts = [6, 6, 4, 2].
431        let grid = asymmetric_age_grid(4, 6, 12.0, 6.0, 6.0, None).unwrap();
432        assert_eq!(grid.observed_counts, vec![6, 6, 4, 2]);
433        let true_ldfs = [1.5, 1.3, 1.15, 1.08, 1.03];
434        let base_first = [100.0, 120.0, 140.0, 160.0];
435        let mut cum = vec![f64::NAN; 4 * 6];
436        for i in 0..4 {
437            let mut val = base_first[i];
438            for j in 0..grid.observed_counts[i] {
439                if j > 0 {
440                    val *= true_ldfs[j - 1];
441                }
442                cum[i * 6 + j] = val;
443            }
444        }
445
446        let res = asymmetric_chain_ladder(
447            &cum,
448            &grid,
449            LdfSelectionMethod::VolumeWeighted,
450            1.0,
451            MonotonicityPolicy::Strict,
452        )
453        .unwrap();
454        for (got, expected) in res.ldfs.iter().zip(true_ldfs.iter()) {
455            assert!((got - expected).abs() < 1e-12);
456        }
457        assert!(res.total_ibnr > 0.0);
458    }
459
460    #[test]
461    fn interim_bf_and_cape_cod_pro_rate_stub_row() {
462        let latest = [1000.0, 800.0, 300.0];
463        let cdfs = [1.0, 1.25, 2.0];
464        let full_exp = [1000.0, 1000.0, 1000.0];
465        let fracs = [1.0, 1.0, 0.5];
466
467        let bf = interim_bf(&latest, &cdfs, &full_exp, &fracs).unwrap();
468        // Origin 2: earned expected = 500, pct unreported = 0.5 -> IBNR = 250, Ult = 550.
469        assert!((bf.earned_expected_ultimate[2] - 500.0).abs() < 1e-12);
470        assert!((bf.ibnr[2] - 250.0).abs() < 1e-12);
471        assert!((bf.ultimates[2] - 550.0).abs() < 1e-12);
472
473        let cc = interim_cape_cod(&latest, &cdfs, &full_exp, &fracs).unwrap();
474        // Used-up premiums: 1000/1 + 1000/1.25 + 500/2 = 1000 + 800 + 250 = 2050.
475        // ELR = 2100 / 2050.
476        assert!((cc.elr - (2100.0 / 2050.0)).abs() < 1e-12);
477        assert!((cc.ibnr[2] - 500.0 * cc.elr * 0.5).abs() < 1e-12);
478    }
479}