Skip to main content

reserving_kernels/deterministic/
case_outstanding.rs

1//! Case Outstanding (Paid-to-Case & Case-to-Case) reserving kernel.
2//!
3//! Implements the Friedland (2010, Ch. 11) / CAS Case Outstanding development
4//! technique (corresponding to `chainladder-python`'s `CaseOutstanding`
5//! estimator):
6//!
7//! 1. Given aligned cumulative paid ($P_{i,j}$) and case-outstanding
8//!    ($O_{i,j} = I_{i,j} - P_{i,j}$) triangles, compute age-to-age ratios:
9//!    - **Paid-to-prior-case ratio** for incremental paid $p_{i,j} = P_{i,j} - P_{i,j-1}$:
10//!      $$r^{\text{paid}}_j = \frac{\sum_i p_{i,j}}{\sum_i O_{i,j-1}}$$
11//!    - **Case-to-prior-case ratio**:
12//!      $$r^{\text{case}}_j = \frac{\sum_i O_{i,j}}{\sum_i O_{i,j-1}}$$
13//! 2. Project future incremental paid and future case reserves cell-by-cell
14//!    across the lower-right triangle:
15//!    $$\hat{p}_{i,j} = \hat{O}_{i,j-1} \cdot r^{\text{paid}}_j, \qquad
16//!    \hat{O}_{i,j} = \hat{O}_{i,j-1} \cdot r^{\text{case}}_j.$$
17//! 3. Accumulate projected incremental paid (plus any remaining terminal case
18//!    reserve if `include_terminal_case` is set) to obtain paid ultimates and
19//!    total unpaid reserves.
20
21use serde::{Deserialize, Serialize};
22
23use crate::{
24    preprocessing::triangle::{cumulative_to_incremental, latest_diagonal},
25    types::TriangleView,
26    validate::{
27        MonotonicityPolicy, ValidationError, validate_monotone_cumulative, validate_triangle,
28    },
29};
30
31/// Ratio averaging rule for [`CaseOutstandingOptions`].
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33pub enum CaseRatioAverage {
34    /// Volume-weighted ratio $\sum_i y_{i,j} / \sum_i O_{i,j-1}$.
35    VolumeWeighted,
36    /// Unweighted arithmetic mean of cell ratios $y_{i,j} / O_{i,j-1}$.
37    Simple,
38}
39
40/// Configuration for [`project_case_outstanding`].
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42pub struct CaseOutstandingOptions {
43    /// Averaging method for paid-to-case and case-to-case ratios.
44    pub average: CaseRatioAverage,
45    /// Optional trailing window length (`Some(k)` uses at most the latest `k`
46    /// observed origins at each development age; `None` uses all observed).
47    pub last_n: Option<usize>,
48    /// Whether to add any residual projected case reserve at the final
49    /// development age to the ultimate paid projection (default: `true`,
50    /// assuming remaining terminal case reserves eventually pay out 1:1).
51    pub include_terminal_case: bool,
52    /// Monotonicity policy for validating the cumulative paid triangle.
53    pub paid_policy: MonotonicityPolicy,
54}
55
56impl Default for CaseOutstandingOptions {
57    fn default() -> Self {
58        Self {
59            average: CaseRatioAverage::VolumeWeighted,
60            last_n: None,
61            include_terminal_case: true,
62            paid_policy: MonotonicityPolicy::AllowNegativeIncrements,
63        }
64    }
65}
66
67/// Output of the Case Outstanding reserving projection.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub struct CaseOutstandingProjection {
70    /// Selected paid-to-prior-case ratios for development transitions `j = 1..n_devs`.
71    pub paid_to_case_ratios: Vec<f64>,
72    /// Selected case-to-prior-case ratios for development transitions `j = 1..n_devs`.
73    pub case_to_case_ratios: Vec<f64>,
74    /// Full completed cumulative paid triangle (row-major `n_origins × n_devs`).
75    pub completed_paid: Vec<f64>,
76    /// Full completed case-outstanding triangle (row-major `n_origins × n_devs`).
77    pub completed_case: Vec<f64>,
78    /// Projected ultimate loss per origin.
79    pub ultimate: Vec<f64>,
80    /// Projected total unpaid reserve (`ultimate - latest_paid`) per origin.
81    pub reserve: Vec<f64>,
82    /// Projected IBNR (`reserve - latest_case`) per origin.
83    pub ibnr: Vec<f64>,
84    /// Sum of `reserve` across all origins.
85    pub total_reserve: f64,
86    /// Sum of `ibnr` across all origins.
87    pub total_ibnr: f64,
88}
89
90fn select_ratio(
91    numerators: &[f64],
92    denominators: &[f64],
93    average: CaseRatioAverage,
94    last_n: Option<usize>,
95) -> f64 {
96    let pairs: Vec<(f64, f64)> = numerators
97        .iter()
98        .zip(denominators.iter())
99        .filter(|&(num, den)| num.is_finite() && den.is_finite() && *den > 0.0)
100        .map(|(&num, &den)| (num, den))
101        .collect();
102    if pairs.is_empty() {
103        return 0.0;
104    }
105    let slice = match last_n {
106        Some(k) if k > 0 && k < pairs.len() => &pairs[pairs.len() - k..],
107        _ => &pairs[..],
108    };
109    match average {
110        CaseRatioAverage::VolumeWeighted => {
111            let num_sum: f64 = slice.iter().map(|(n, _)| *n).sum();
112            let den_sum: f64 = slice.iter().map(|(_, d)| *d).sum();
113            if den_sum > 0.0 {
114                num_sum / den_sum
115            } else {
116                0.0
117            }
118        }
119        CaseRatioAverage::Simple => {
120            let ratio_sum: f64 = slice.iter().map(|(n, d)| *n / *d).sum();
121            ratio_sum / slice.len() as f64
122        }
123    }
124}
125
126/// Project ultimates and reserves using the Case Outstanding method from
127/// aligned cumulative `paid` and `case_outstanding` triangles.
128pub fn project_case_outstanding(
129    paid: &TriangleView<'_>,
130    case_outstanding: &TriangleView<'_>,
131    options: &CaseOutstandingOptions,
132) -> Result<CaseOutstandingProjection, ValidationError> {
133    validate_triangle(paid)?;
134    if options.paid_policy == MonotonicityPolicy::Strict {
135        validate_monotone_cumulative(paid)?;
136    }
137    if paid.n_origins != case_outstanding.n_origins || paid.n_devs != case_outstanding.n_devs {
138        return Err(ValidationError::ShapeMismatch);
139    }
140    let n_origins = paid.n_origins;
141    let n_devs = paid.n_devs;
142    if n_origins < 2 || n_devs < 2 {
143        return Err(ValidationError::ShapeMismatch);
144    }
145
146    let inc_paid = cumulative_to_incremental(paid);
147    let mut paid_to_case_ratios = Vec::with_capacity(n_devs - 1);
148    let mut case_to_case_ratios = Vec::with_capacity(n_devs - 1);
149
150    for j in 1..n_devs {
151        let mut p_nums = Vec::with_capacity(n_origins);
152        let mut c_nums = Vec::with_capacity(n_origins);
153        let mut dens = Vec::with_capacity(n_origins);
154        for i in 0..n_origins {
155            let prev_case = case_outstanding.get(i, j - 1);
156            let cur_inc_paid = inc_paid[i * n_devs + j];
157            let cur_case = case_outstanding.get(i, j);
158            if prev_case.is_finite() && cur_inc_paid.is_finite() && cur_case.is_finite() {
159                p_nums.push(cur_inc_paid);
160                c_nums.push(cur_case);
161                dens.push(prev_case);
162            }
163        }
164        paid_to_case_ratios.push(select_ratio(
165            &p_nums,
166            &dens,
167            options.average,
168            options.last_n,
169        ));
170        case_to_case_ratios.push(select_ratio(
171            &c_nums,
172            &dens,
173            options.average,
174            options.last_n,
175        ));
176    }
177
178    let mut completed_paid = paid.data.to_vec();
179    let mut completed_case = case_outstanding.data.to_vec();
180
181    for i in 0..n_origins {
182        for j in 1..n_devs {
183            let idx = i * n_devs + j;
184            if !completed_paid[idx].is_finite() || !completed_case[idx].is_finite() {
185                let prev_paid = completed_paid[i * n_devs + (j - 1)];
186                let prev_case = completed_case[i * n_devs + (j - 1)];
187                let r_p = paid_to_case_ratios[j - 1];
188                let r_c = case_to_case_ratios[j - 1];
189                completed_paid[idx] = prev_paid + prev_case * r_p;
190                completed_case[idx] = prev_case * r_c;
191            }
192        }
193    }
194
195    let latest_paid = latest_diagonal(paid);
196    let latest_case = latest_diagonal(case_outstanding);
197    let mut ultimate = Vec::with_capacity(n_origins);
198    let mut reserve = Vec::with_capacity(n_origins);
199    let mut ibnr = Vec::with_capacity(n_origins);
200
201    for i in 0..n_origins {
202        let end_paid = completed_paid[i * n_devs + (n_devs - 1)];
203        let end_case = completed_case[i * n_devs + (n_devs - 1)];
204        let ult = if options.include_terminal_case {
205            end_paid + end_case
206        } else {
207            end_paid
208        };
209        let lp = if latest_paid[i].is_finite() {
210            latest_paid[i]
211        } else {
212            0.0
213        };
214        let lc = if latest_case[i].is_finite() {
215            latest_case[i]
216        } else {
217            0.0
218        };
219        let res = ult - lp;
220        ultimate.push(ult);
221        reserve.push(res);
222        ibnr.push(res - lc);
223    }
224
225    let total_reserve = reserve.iter().sum();
226    let total_ibnr = ibnr.iter().sum();
227
228    Ok(CaseOutstandingProjection {
229        paid_to_case_ratios,
230        case_to_case_ratios,
231        completed_paid,
232        completed_case,
233        ultimate,
234        reserve,
235        ibnr,
236        total_reserve,
237        total_ibnr,
238    })
239}
240
241/// Convenience wrapper deriving `case_outstanding = incurred - paid` from
242/// aligned cumulative `paid` and `incurred` triangles.
243pub fn project_from_paid_incurred(
244    paid: &TriangleView<'_>,
245    incurred: &TriangleView<'_>,
246    options: &CaseOutstandingOptions,
247) -> Result<CaseOutstandingProjection, ValidationError> {
248    if paid.n_origins != incurred.n_origins || paid.n_devs != incurred.n_devs {
249        return Err(ValidationError::ShapeMismatch);
250    }
251    let case_data: Vec<f64> = incurred
252        .data
253        .iter()
254        .zip(paid.data.iter())
255        .map(|(&inc, &p)| {
256            if inc.is_finite() && p.is_finite() {
257                inc - p
258            } else {
259                f64::NAN
260            }
261        })
262        .collect();
263    let case_view = TriangleView {
264        n_origins: paid.n_origins,
265        n_devs: paid.n_devs,
266        data: &case_data,
267    };
268    project_case_outstanding(paid, &case_view, options)
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use crate::types::Triangle;
275
276    #[test]
277    fn exact_multiplicative_paid_and_case_recovery() {
278        // Construct exact paid & case triangles with constant r_p = 0.5, r_c = 0.4.
279        let n = 4;
280        let mut paid = vec![f64::NAN; n * n];
281        let mut case = vec![f64::NAN; n * n];
282        for i in 0..n {
283            let mut p = 100.0 * (1.0 + 0.1 * i as f64);
284            let mut c = 200.0 * (1.0 + 0.1 * i as f64);
285            for j in 0..(n - i) {
286                if j > 0 {
287                    p += 0.5 * c;
288                    c *= 0.4;
289                }
290                paid[i * n + j] = p;
291                case[i * n + j] = c;
292            }
293        }
294        let pt = Triangle::new(n, n, paid);
295        let ct = Triangle::new(n, n, case);
296        let res =
297            project_case_outstanding(&pt.view(), &ct.view(), &CaseOutstandingOptions::default())
298                .expect("case outstanding");
299        for &rp in &res.paid_to_case_ratios {
300            assert!((rp - 0.5).abs() < 1e-12, "rp={rp}");
301        }
302        for &rc in &res.case_to_case_ratios {
303            assert!((rc - 0.4).abs() < 1e-12, "rc={rc}");
304        }
305        assert!(res.total_reserve > 0.0);
306    }
307}