reserving_kernels/deterministic/
double_chain_ladder.rs1use 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#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
32pub struct DoubleChainLadderResult {
33 pub count_ultimate: Vec<f64>,
35 pub reporting_delay: Vec<f64>,
37 pub paid_cl_ultimate: Vec<f64>,
39 pub paid_delay: Vec<f64>,
41 pub payment_delay: Vec<f64>,
43 pub severity_inflation: Vec<f64>,
45 pub normalized_inflation: Vec<f64>,
47 pub latest_paid: Vec<f64>,
49 pub rbns_reserve: Vec<f64>,
51 pub ibnr_reserve: Vec<f64>,
53 pub rbns_tail: Vec<f64>,
55 pub ibnr_tail: Vec<f64>,
57 pub total_in_triangle_by_origin: Vec<f64>,
59 pub total_with_tail_by_origin: Vec<f64>,
61 pub total_rbns: f64,
63 pub total_ibnr: f64,
65 pub total_in_triangle_reserve: f64,
67 pub total_tail_reserve: f64,
69 pub total_reserve_with_tail: f64,
71 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
100pub 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
114pub 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
125pub 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 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 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 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 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 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 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 assert!((dcl.total_in_triangle_reserve - dcl.paid_cl_total_reserve).abs() < 1e-6);
335
336 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 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}