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