Skip to main content

reserving_kernels/deterministic/
double_chain_ladder.rs

1//! Martínez-Miranda, Nielsen & Verrall (2012) Double Chain Ladder (DCL).
2//!
3//! Implements:
4//!
5//! * M. D. Martínez-Miranda, J. P. Nielsen & R. J. Verrall (2012), *Double Chain
6//!   Ladder*, ASTIN Bulletin, Vol. 42, No. 1, pp. 59–76.
7//!
8//! Combines a **cumulative paid-loss triangle** $X$ and a **cumulative reported
9//! claim-count triangle** $N$ to separate:
10//!
11//! * **Reporting delay distribution** $\hat{\beta}_j$ ($\sum_j \hat{\beta}_j = 1$)
12//!   from the chain ladder on reported counts $N$.
13//! * **Payment / settlement delay distribution** $\hat{\pi}_l$ solved by exact
14//!   forward deconvolution of the paid development proportions $\tilde{\beta}_j$:
15//!   $$\tilde{\beta}_j = \sum_{l=0}^{j} \hat{\beta}_{j-l} \hat{\pi}_l$$
16//! * **Underwriting-year severity inflation** $\hat{\gamma}_i = \tilde{\alpha}_i / \hat{\alpha}_i$
17//!   (ratio of paid CL ultimate to reported-count CL ultimate).
18//! * **RBNS** (Reported But Not Settled) vs. **IBNR** (Incurred But Not Reported)
19//!   reserve decomposition, both within the run-off square ($j \le n - 1$) and
20//!   including the DCL-implied tail ($j \ge n$).
21
22use crate::deterministic::chain_ladder::ChainLadderEngine;
23use crate::deterministic::ldf::DevelopmentFactorEngine;
24use crate::preprocessing::triangle::{cumulative_to_incremental, latest_diagonal};
25use crate::types::TriangleView;
26use crate::validate::{
27    MonotonicityPolicy, ValidationError, validate_monotone_cumulative, validate_triangle,
28};
29
30/// Result of Martínez-Miranda, Nielsen & Verrall (2012) Double Chain Ladder.
31#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
32pub struct DoubleChainLadderResult {
33    /// Ultimate reported claim counts $\hat{\alpha}_i$ from count CL, length $n$.
34    pub count_ultimate: Vec<f64>,
35    /// Reporting delay distribution $\hat{\beta}_j$ ($\sum \hat{\beta}_j = 1$), length $n$.
36    pub reporting_delay: Vec<f64>,
37    /// Ultimate paid losses $\tilde{\alpha}_i$ from paid CL, length $n$.
38    pub paid_cl_ultimate: Vec<f64>,
39    /// Paid development proportions $\tilde{\beta}_j$ ($\sum \tilde{\beta}_j = 1$), length $n$.
40    pub paid_delay: Vec<f64>,
41    /// Deconvolved payment delay parameters $\hat{\pi}_l$ ($l = 0..n-1$), length $n$.
42    pub payment_delay: Vec<f64>,
43    /// Underwriting-year mean severity $\hat{\gamma}_i = \tilde{\alpha}_i / \hat{\alpha}_i$, length $n$.
44    pub severity_inflation: Vec<f64>,
45    /// Normalized severity inflation index $\hat{\iota}_i = \hat{\gamma}_i / \hat{\gamma}_0$, length $n$.
46    pub normalized_inflation: Vec<f64>,
47    /// Latest observed cumulative paid loss per origin, length $n$.
48    pub latest_paid: Vec<f64>,
49    /// In-triangle ($j \le n - 1$) RBNS reserve per origin (using observed reported counts), length $n$.
50    pub rbns_reserve: Vec<f64>,
51    /// In-triangle ($j \le n - 1$) IBNR reserve per origin (future reported counts), length $n$.
52    pub ibnr_reserve: Vec<f64>,
53    /// DCL-implied tail ($j \ge n$) RBNS reserve per origin, length $n$.
54    pub rbns_tail: Vec<f64>,
55    /// DCL-implied tail ($j \ge n$) IBNR reserve per origin, length $n$.
56    pub ibnr_tail: Vec<f64>,
57    /// Total in-triangle DCL reserve per origin (`rbns_reserve + ibnr_reserve`), length $n$.
58    pub total_in_triangle_by_origin: Vec<f64>,
59    /// Total DCL reserve per origin including tail (`rbns + ibnr + rbns_tail + ibnr_tail`), length $n$.
60    pub total_with_tail_by_origin: Vec<f64>,
61    /// Total in-triangle RBNS reserve across all origins.
62    pub total_rbns: f64,
63    /// Total in-triangle IBNR reserve across all origins.
64    pub total_ibnr: f64,
65    /// Total in-triangle DCL reserve (`total_rbns + total_ibnr`).
66    pub total_in_triangle_reserve: f64,
67    /// Total DCL tail reserve (`sum(rbns_tail + ibnr_tail)`).
68    pub total_tail_reserve: f64,
69    /// Total DCL reserve including tail.
70    pub total_reserve_with_tail: f64,
71    /// Reference standard paid Chain Ladder total reserve (for reconciliation).
72    pub paid_cl_total_reserve: f64,
73}
74
75impl std::fmt::Display for DoubleChainLadderResult {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        write!(
78            f,
79            "DoubleChainLadder(rbns={:.2}, ibnr={:.2}, total={:.2}, tail={:.2})",
80            self.total_rbns,
81            self.total_ibnr,
82            self.total_in_triangle_reserve,
83            self.total_tail_reserve
84        )
85    }
86}
87
88fn delay_proportions_from_cdfs(cdfs: &[f64]) -> Vec<f64> {
89    let n = cdfs.len();
90    let mut beta = vec![0.0; n];
91    let mut prev_pct = 0.0;
92    for j in 0..n {
93        let pct = 1.0 / cdfs[j];
94        beta[j] = pct - prev_pct;
95        prev_pct = pct;
96    }
97    beta
98}
99
100/// Fit Double Chain Ladder (Martínez-Miranda, Nielsen & Verrall 2012) to
101/// cumulative paid-loss and cumulative reported-count triangles under strict
102/// monotonicity.
103pub fn analyze(
104    paid_cumulative: &TriangleView<'_>,
105    counts_cumulative: &TriangleView<'_>,
106) -> Result<DoubleChainLadderResult, ValidationError> {
107    analyze_with_policy(
108        paid_cumulative,
109        counts_cumulative,
110        MonotonicityPolicy::Strict,
111    )
112}
113
114/// Fit Double Chain Ladder with an explicit [`MonotonicityPolicy`] and optional
115/// custom severity inflation override (if `None`, uses empirical CL severity
116/// $\hat{\gamma}_i = \tilde{\alpha}_i / \hat{\alpha}_i$).
117pub fn analyze_with_policy(
118    paid_cumulative: &TriangleView<'_>,
119    counts_cumulative: &TriangleView<'_>,
120    policy: MonotonicityPolicy,
121) -> Result<DoubleChainLadderResult, ValidationError> {
122    analyze_with_inflation(paid_cumulative, counts_cumulative, None, policy)
123}
124
125/// Fit Double Chain Ladder with an optional explicit severity inflation vector
126/// $\gamma_i$ (length $n$) and [`MonotonicityPolicy`].
127pub fn analyze_with_inflation(
128    paid_cumulative: &TriangleView<'_>,
129    counts_cumulative: &TriangleView<'_>,
130    custom_severity: Option<&[f64]>,
131    policy: MonotonicityPolicy,
132) -> Result<DoubleChainLadderResult, ValidationError> {
133    validate_triangle(paid_cumulative)?;
134    validate_triangle(counts_cumulative)?;
135    let n = paid_cumulative.n_origins;
136    if n < 2 {
137        return Err(ValidationError::InvalidParameter(
138            "triangles must be at least 2x2",
139        ));
140    }
141    if counts_cumulative.n_origins != n || counts_cumulative.n_devs != n {
142        return Err(ValidationError::ShapeMismatch);
143    }
144    if matches!(policy, MonotonicityPolicy::Strict) {
145        validate_monotone_cumulative(paid_cumulative)?;
146        validate_monotone_cumulative(counts_cumulative)?;
147    }
148
149    let paid_factors = DevelopmentFactorEngine::volume_weighted(paid_cumulative, 1.0)?;
150    let count_factors = DevelopmentFactorEngine::volume_weighted(counts_cumulative, 1.0)?;
151    let paid_cl = ChainLadderEngine::project_with_policy(paid_cumulative, &paid_factors, policy)?;
152    let count_cl =
153        ChainLadderEngine::project_with_policy(counts_cumulative, &count_factors, policy)?;
154
155    let reporting_delay = delay_proportions_from_cdfs(&count_factors.cdfs);
156    let paid_delay = delay_proportions_from_cdfs(&paid_factors.cdfs);
157
158    if !reporting_delay[0].is_finite() || reporting_delay[0] <= 0.0 {
159        return Err(ValidationError::DivideByZero(
160            "initial reporting delay proportion beta_0",
161        ));
162    }
163
164    // Exact forward deconvolution: paid_delay[j] = sum_{l=0}^j reporting_delay[j-l] * pi[l].
165    let mut payment_delay = vec![0.0; n];
166    for l in 0..n {
167        let mut rhs = paid_delay[l];
168        for m in 0..l {
169            rhs -= reporting_delay[l - m] * payment_delay[m];
170        }
171        payment_delay[l] = rhs / reporting_delay[0];
172    }
173
174    // Severity inflation gamma_i = paid_cl_ultimate[i] / count_ultimate[i].
175    let severity_inflation = if let Some(custom) = custom_severity {
176        if custom.len() != n {
177            return Err(ValidationError::ShapeMismatch);
178        }
179        for &g in custom {
180            if !g.is_finite() || g < 0.0 {
181                return Err(ValidationError::InvalidParameter(
182                    "custom severity inflation entries must be finite and non-negative",
183                ));
184            }
185        }
186        custom.to_vec()
187    } else {
188        let mut gamma = Vec::with_capacity(n);
189        for i in 0..n {
190            let alpha_i = count_cl.ultimates[i];
191            if alpha_i <= 0.0 {
192                return Err(ValidationError::DivideByZero("ultimate reported count"));
193            }
194            gamma.push(paid_cl.ultimates[i] / alpha_i);
195        }
196        gamma
197    };
198
199    let base_gamma = severity_inflation[0];
200    let normalized_inflation: Vec<f64> = if base_gamma > 0.0 {
201        severity_inflation.iter().map(|&g| g / base_gamma).collect()
202    } else {
203        vec![f64::NAN; n]
204    };
205
206    let inc_counts = cumulative_to_incremental(counts_cumulative);
207    let latest_paid = latest_diagonal(paid_cumulative);
208
209    // Prefix sums of payment_delay: pay_prefix[m] = sum_{l=0}^{m-1} payment_delay[l].
210    // Collapses both RBNS and IBNR (in-triangle and tail) from O(n^3) to O(n^2).
211    let mut pay_prefix = vec![0.0; n + 1];
212    for l in 0..n {
213        pay_prefix[l + 1] = pay_prefix[l] + payment_delay[l];
214    }
215    let pay_total = pay_prefix[n];
216
217    let mut rbns_reserve = vec![0.0; n];
218    let mut ibnr_reserve = vec![0.0; n];
219    let mut rbns_tail = vec![0.0; n];
220    let mut ibnr_tail = vec![0.0; n];
221
222    for i in 0..n {
223        let last_obs = n - 1 - i;
224        let gamma_i = severity_inflation[i];
225        let alpha_i = count_cl.ultimates[i];
226        let row_base = i * n;
227
228        // RBNS: claims already reported at k in 0..=last_obs.
229        //   In-triangle (j in last_obs+1..n): lag l = j - k in (last_obs + 1 - k)..(n - k).
230        //   Tail (j in n..k+n):               lag l = j - k in (n - k)..n.
231        let mut rbns_in = 0.0;
232        let mut rbns_tl = 0.0;
233        for k in 0..=last_obs {
234            let cnt = inc_counts[row_base + k];
235            let p_nk = pay_prefix[n - k];
236            rbns_in += cnt * (p_nk - pay_prefix[last_obs + 1 - k]);
237            rbns_tl += cnt * (pay_total - p_nk);
238        }
239        rbns_reserve[i] = gamma_i * rbns_in;
240        rbns_tail[i] = gamma_i * rbns_tl;
241
242        // IBNR: future claims reported at k in (last_obs + 1)..n.
243        //   In-triangle (j in k..n): lag l = j - k in 0..(n - k).
244        //   Tail (j in n..k+n):      lag l = j - k in (n - k)..n.
245        let mut ibnr_in = 0.0;
246        let mut ibnr_tl = 0.0;
247        for k in (last_obs + 1)..n {
248            let rep = reporting_delay[k];
249            let p_nk = pay_prefix[n - k];
250            ibnr_in += rep * p_nk;
251            ibnr_tl += rep * (pay_total - p_nk);
252        }
253        let scale = gamma_i * alpha_i;
254        ibnr_reserve[i] = scale * ibnr_in;
255        ibnr_tail[i] = scale * ibnr_tl;
256    }
257
258    let total_in_triangle_by_origin: Vec<f64> =
259        (0..n).map(|i| rbns_reserve[i] + ibnr_reserve[i]).collect();
260    let total_with_tail_by_origin: Vec<f64> = (0..n)
261        .map(|i| rbns_reserve[i] + ibnr_reserve[i] + rbns_tail[i] + ibnr_tail[i])
262        .collect();
263
264    let total_rbns: f64 = rbns_reserve.iter().sum();
265    let total_ibnr: f64 = ibnr_reserve.iter().sum();
266    let total_in_triangle_reserve = total_rbns + total_ibnr;
267    let total_tail_reserve: f64 = (0..n).map(|i| rbns_tail[i] + ibnr_tail[i]).sum();
268    let total_reserve_with_tail = total_in_triangle_reserve + total_tail_reserve;
269    let paid_cl_total_reserve: f64 = paid_cl.reserves.iter().sum();
270
271    Ok(DoubleChainLadderResult {
272        count_ultimate: count_cl.ultimates,
273        reporting_delay,
274        paid_cl_ultimate: paid_cl.ultimates,
275        paid_delay,
276        payment_delay,
277        severity_inflation,
278        normalized_inflation,
279        latest_paid,
280        rbns_reserve,
281        ibnr_reserve,
282        rbns_tail,
283        ibnr_tail,
284        total_in_triangle_by_origin,
285        total_with_tail_by_origin,
286        total_rbns,
287        total_ibnr,
288        total_in_triangle_reserve,
289        total_tail_reserve,
290        total_reserve_with_tail,
291        paid_cl_total_reserve,
292    })
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::Triangle;
299
300    #[test]
301    fn exact_deconvolution_and_cl_reproduction_on_noiseless_portfolio() {
302        // Synthetic portfolio with exact reporting delay, payment delay, and severity inflation.
303        let alpha = [100.0, 110.0, 120.0, 130.0, 140.0];
304        let rep_delay = [0.60, 0.25, 0.10, 0.04, 0.01];
305        let pay_delay = [0.50, 0.30, 0.15, 0.04, 0.01];
306        let gamma = [1000.0, 1050.0, 1102.5, 1157.625, 1215.50625];
307        let n = 5;
308
309        let mut count_rows = Vec::new();
310        let mut paid_rows = Vec::new();
311        for i in 0..n {
312            let mut c_row = Vec::new();
313            let mut p_row = Vec::new();
314            for j in 0..(n - i) {
315                c_row.push(alpha[i] * rep_delay[j]);
316                let mut paid_ij = 0.0;
317                for k in 0..=j {
318                    paid_ij += alpha[i] * rep_delay[k] * pay_delay[j - k];
319                }
320                p_row.push(gamma[i] * paid_ij);
321            }
322            count_rows.push(c_row);
323            paid_rows.push(p_row);
324        }
325
326        let c_slices: Vec<&[f64]> = count_rows.iter().map(std::vec::Vec::as_slice).collect();
327        let p_slices: Vec<&[f64]> = paid_rows.iter().map(std::vec::Vec::as_slice).collect();
328        let counts = Triangle::try_from_incremental_rows(&c_slices).unwrap();
329        let paid = Triangle::try_from_incremental_rows(&p_slices).unwrap();
330
331        let dcl = analyze(&paid.view(), &counts.view()).unwrap();
332
333        // Exact reproduction of standard paid CL total reserve in the triangle square!
334        assert!((dcl.total_in_triangle_reserve - dcl.paid_cl_total_reserve).abs() < 1e-6);
335
336        // Exact recovery of reporting delay and payment delay proportions (up to tail normalization).
337        for j in 0..n {
338            assert!((dcl.reporting_delay[j] - rep_delay[j]).abs() < 1e-10);
339        }
340        assert!(dcl.total_rbns > 0.0);
341        assert!(dcl.total_ibnr > 0.0);
342        // Normalized inflation recovers 5% annual trend.
343        for i in 1..n {
344            let ratio = dcl.normalized_inflation[i] / dcl.normalized_inflation[i - 1];
345            assert!((ratio - 1.05).abs() < 1e-6);
346        }
347    }
348}