Skip to main content

reserving_kernels/stochastic/
micro_reserving.rs

1//! Antonio & Plat (2014) micro-level individual-claim stochastic reserving.
2//!
3//! Implements:
4//!
5//! * K. Antonio & R. Plat (2014), *Micro-Level Stochastic Loss Reserving for
6//!   General Insurance*, Scandinavian Actuarial Journal, Vol. 2014, No. 7,
7//!   pp. 649–669.
8//!
9//! Models individual claim life-cycles directly rather than aggregating into
10//! run-off triangles:
11//!
12//! 1. **Occurrence process**: piecewise-constant Non-Homogeneous Poisson
13//!    Process (NHPP) with intensity $\lambda_k$ over accident period $k$,
14//!    estimated with exact right-truncation correction
15//!    $\hat{\lambda}_k = N_k^{\text{obs}} / \int_{t_k}^{t_{k+1}} F_R(\tau - t)\,dt$.
16//! 2. **Reporting delay**: exponential ($F_R(r) = 1 - e^{-\rho r}$) delay from
17//!    occurrence to reporting, estimated via right-truncated maximum likelihood.
18//! 3. **Multi-state development & settlement hazard**: open claims evolve in
19//!    continuous time under competing Poisson hazards:
20//!    * Interim payment hazard $h_{\text{pay}}$ with lognormal severity $(\mu_{\text{pay}}, \sigma_{\text{pay}})$,
21//!    * Settlement (closure) hazard $h_{\text{settle}}$ with probability $p_{\text{close}}$
22//!      of a final settlement payment with lognormal severity $(\mu_{\text{close}}, \sigma_{\text{close}})$.
23//! 4. **RBNS + IBNR Monte Carlo simulation**: deterministic simulation of
24//!    open RBNS claims to settlement and thinned-NHPP IBNR claims from
25//!    occurrence through reporting to settlement.
26
27use crate::stochastic::bootstrap_odp::DeterministicRng;
28use crate::validate::ValidationError;
29
30/// A single payment transaction on an individual claim.
31#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
32pub struct ClaimPayment {
33    /// Calendar time of the payment ($t \ge \text{report\_time}$).
34    pub time: f64,
35    /// Payment amount ($> 0$).
36    pub amount: f64,
37}
38
39/// Individual claim record observed as of the valuation date.
40#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
41pub struct ClaimRecord {
42    /// Unique claim identifier.
43    pub claim_id: u64,
44    /// Calendar time of loss occurrence ($0 \le t_{\text{occ}} \le \tau$).
45    pub occurrence_time: f64,
46    /// Calendar time of claim reporting ($t_{\text{rep}} \ge t_{\text{occ}}$).
47    pub report_time: f64,
48    /// Settlement/closure calendar time if settled on or before $\tau$; `None` if open (RBNS).
49    pub settlement_time: Option<f64>,
50    /// Historical payments made on or before $\tau$.
51    pub payments: Vec<ClaimPayment>,
52}
53
54/// Parametric Antonio & Plat (2014) micro-level reserving model.
55#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
56pub struct MicroReservingModel {
57    /// Piecewise-constant NHPP occurrence intensities $\lambda_k$ per unit period, length `n_periods`.
58    pub occurrence_intensities: Vec<f64>,
59    /// Exponential reporting-delay rate $\rho > 0$ (mean reporting delay $= 1 / \rho$).
60    pub reporting_delay_rate: f64,
61    /// Interim payment hazard rate $h_{\text{pay}} \ge 0$ per unit time while open.
62    pub interim_payment_hazard: f64,
63    /// Settlement (closure) hazard rate $h_{\text{settle}} > 0$ per unit time while open.
64    pub settlement_hazard: f64,
65    /// Lognormal $\mu$ parameter for interim payments.
66    pub interim_severity_mu: f64,
67    /// Lognormal $\sigma \ge 0$ parameter for interim payments.
68    pub interim_severity_sigma: f64,
69    /// Probability $p_{\text{close}} \in [0, 1]$ of a final payment upon settlement.
70    pub settlement_payment_prob: f64,
71    /// Lognormal $\mu$ parameter for settlement payments.
72    pub settlement_severity_mu: f64,
73    /// Lognormal $\sigma \ge 0$ parameter for settlement payments.
74    pub settlement_severity_sigma: f64,
75}
76
77impl MicroReservingModel {
78    /// Validate all model parameters.
79    pub fn validate(&self) -> Result<(), ValidationError> {
80        if self.occurrence_intensities.is_empty() {
81            return Err(ValidationError::InvalidParameter(
82                "occurrence_intensities must not be empty",
83            ));
84        }
85        for &lam in &self.occurrence_intensities {
86            if !lam.is_finite() || lam < 0.0 {
87                return Err(ValidationError::InvalidParameter(
88                    "occurrence intensities must be finite and non-negative",
89                ));
90            }
91        }
92        if !self.reporting_delay_rate.is_finite() || self.reporting_delay_rate <= 0.0 {
93            return Err(ValidationError::InvalidParameter(
94                "reporting_delay_rate must be finite and positive",
95            ));
96        }
97        if !self.interim_payment_hazard.is_finite() || self.interim_payment_hazard < 0.0 {
98            return Err(ValidationError::InvalidParameter(
99                "interim_payment_hazard must be finite and non-negative",
100            ));
101        }
102        if !self.settlement_hazard.is_finite() || self.settlement_hazard <= 0.0 {
103            return Err(ValidationError::InvalidParameter(
104                "settlement_hazard must be finite and positive",
105            ));
106        }
107        if !self.interim_severity_mu.is_finite()
108            || !self.interim_severity_sigma.is_finite()
109            || self.interim_severity_sigma < 0.0
110            || !self.settlement_severity_mu.is_finite()
111            || !self.settlement_severity_sigma.is_finite()
112            || self.settlement_severity_sigma < 0.0
113            || !self.settlement_payment_prob.is_finite()
114            || self.settlement_payment_prob < 0.0
115            || self.settlement_payment_prob > 1.0
116        {
117            return Err(ValidationError::InvalidParameter(
118                "invalid severity or settlement payment probability parameter",
119            ));
120        }
121        Ok(())
122    }
123
124    /// Exact theoretical expected total cost per claim from reporting to settlement.
125    pub fn expected_claim_severity(&self) -> f64 {
126        let mean_open_duration = 1.0 / self.settlement_hazard;
127        let expected_interim_count = self.interim_payment_hazard * mean_open_duration;
128        let mean_interim =
129            (self.interim_severity_mu + 0.5 * self.interim_severity_sigma.powi(2)).exp();
130        let mean_close =
131            (self.settlement_severity_mu + 0.5 * self.settlement_severity_sigma.powi(2)).exp();
132        expected_interim_count * mean_interim + self.settlement_payment_prob * mean_close
133    }
134
135    /// Exact theoretical expected unreported IBNR claim count over `[0, tau]`
136    /// assuming unit-length periods `0..n_periods` and `tau = n_periods as f64`.
137    pub fn expected_ibnr_count(&self, valuation_time: f64) -> f64 {
138        let rho = self.reporting_delay_rate;
139        let mut total = 0.0;
140        for (k, &lam) in self.occurrence_intensities.iter().enumerate() {
141            let a = k as f64;
142            let b = ((k + 1) as f64).min(valuation_time);
143            if b <= a {
144                continue;
145            }
146            // Integral_{a}^{b} exp(-rho * (tau - t)) dt = (exp(-rho*(tau-b)) - exp(-rho*(tau-a))) / rho
147            let integral =
148                ((-rho * (valuation_time - b)).exp() - (-rho * (valuation_time - a)).exp()) / rho;
149            total += lam * integral;
150        }
151        total
152    }
153}
154
155/// Summary statistics of a micro-level stochastic reserve simulation.
156#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
157pub struct MicroReservingResult {
158    /// Number of Monte Carlo scenarios simulated.
159    pub n_simulations: usize,
160    /// Number of open RBNS claims at valuation date.
161    pub n_open_claims: usize,
162    /// Mean simulated IBNR claim count.
163    pub mean_ibnr_count: f64,
164    /// Mean RBNS reserve.
165    pub mean_rbns: f64,
166    /// Mean IBNR reserve.
167    pub mean_ibnr: f64,
168    /// Mean total reserve (`mean_rbns + mean_ibnr`).
169    pub mean_total: f64,
170    /// Standard deviation of RBNS reserve.
171    pub sd_rbns: f64,
172    /// Standard deviation of IBNR reserve.
173    pub sd_ibnr: f64,
174    /// Standard deviation of total reserve.
175    pub sd_total: f64,
176    /// 50th, 75th, 90th, 95th, and 99th percentiles of total reserve.
177    pub total_quantiles: [f64; 5],
178    /// Simulated total reserve draws (length `n_simulations`).
179    pub total_draws: Vec<f64>,
180}
181
182impl std::fmt::Display for MicroReservingResult {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        write!(
185            f,
186            "MicroReserving(rbns={:.2}, ibnr={:.2}, total={:.2}, sd={:.2})",
187            self.mean_rbns, self.mean_ibnr, self.mean_total, self.sd_total
188        )
189    }
190}
191
192/// Fit an Antonio & Plat (2014) [`MicroReservingModel`] from an observed
193/// individual-claim event log up to `valuation_time` across `n_periods` unit
194/// accident periods `[0, 1), ..., [n_periods - 1, n_periods)`.
195pub fn fit_from_claims(
196    claims: &[ClaimRecord],
197    valuation_time: f64,
198    n_periods: usize,
199) -> Result<MicroReservingModel, ValidationError> {
200    if claims.is_empty() || n_periods == 0 || !valuation_time.is_finite() || valuation_time <= 0.0 {
201        return Err(ValidationError::InvalidParameter(
202            "non-empty claims, positive valuation_time, and n_periods >= 1 required",
203        ));
204    }
205
206    // 1. Right-truncated MLE for exponential reporting-delay rate rho.
207    // Log-likelihood: sum_i [ ln(rho) - rho * r_i - ln(1 - exp(-rho * T_i)) ], T_i = tau - t_occ_i.
208    let mut delays = Vec::new();
209    let mut truncs = Vec::new();
210    for c in claims {
211        if c.report_time <= valuation_time && c.report_time >= c.occurrence_time {
212            let t_cap = valuation_time - c.occurrence_time;
213            if t_cap > 1e-9 {
214                delays.push(c.report_time - c.occurrence_time);
215                truncs.push(t_cap);
216            }
217        }
218    }
219    if delays.is_empty() {
220        return Err(ValidationError::InvalidParameter(
221            "no valid reported claims before valuation_time",
222        ));
223    }
224    let mean_delay = delays.iter().sum::<f64>() / delays.len() as f64;
225    let mut rho = if mean_delay > 1e-9 {
226        1.0 / mean_delay
227    } else {
228        10.0
229    };
230    // Damped Newton-Raphson for right-truncated exponential MLE.
231    for _ in 0..40 {
232        let mut grad = 0.0;
233        let mut hess = 0.0;
234        for (&r, &cap) in delays.iter().zip(truncs.iter()) {
235            let x = (rho * cap).min(500.0);
236            let ex = (-x).exp();
237            let one_minus_ex = (1.0 - ex).max(1e-15);
238            grad += 1.0 / rho - r - (cap * ex) / one_minus_ex;
239            hess += -1.0 / (rho * rho) + (cap * cap * ex) / (one_minus_ex * one_minus_ex);
240        }
241        if hess.abs() < 1e-15 {
242            break;
243        }
244        let step = (grad / hess).clamp(-0.5 * rho, 0.5 * rho);
245        rho = (rho - step).max(1e-6);
246        if step.abs() < 1e-10 * rho {
247            break;
248        }
249    }
250
251    // 2. Truncation-corrected NHPP occurrence intensities per period k.
252    let mut period_counts = vec![0.0; n_periods];
253    for c in claims {
254        if c.report_time <= valuation_time && c.occurrence_time >= 0.0 {
255            let k = (c.occurrence_time.floor() as usize).min(n_periods - 1);
256            period_counts[k] += 1.0;
257        }
258    }
259    let mut occurrence_intensities = vec![0.0; n_periods];
260    for k in 0..n_periods {
261        let a = k as f64;
262        let b = ((k + 1) as f64).min(valuation_time);
263        if b <= a {
264            continue;
265        }
266        // Observed fraction integral: int_a^b (1 - exp(-rho * (tau - t))) dt
267        let unreported_int =
268            ((-rho * (valuation_time - b)).exp() - (-rho * (valuation_time - a)).exp()) / rho;
269        let obs_exposure = ((b - a) - unreported_int).max(1e-9);
270        occurrence_intensities[k] = period_counts[k] / obs_exposure;
271    }
272
273    // 3. Multi-state settlement and interim payment hazards & lognormal severities.
274    let mut total_exposure_open = 0.0;
275    let mut n_settled = 0usize;
276    let mut n_settled_with_pay = 0usize;
277    let mut interim_logs = Vec::new();
278    let mut close_logs = Vec::new();
279
280    for c in claims {
281        if c.report_time > valuation_time {
282            continue;
283        }
284        let end_time = match c.settlement_time {
285            Some(ts) if ts <= valuation_time => {
286                n_settled += 1;
287                ts
288            }
289            _ => valuation_time,
290        };
291        total_exposure_open += (end_time - c.report_time).max(0.0);
292
293        let settled_at = c.settlement_time.filter(|&ts| ts <= valuation_time);
294        let mut had_close_pay = false;
295        for p in &c.payments {
296            if p.time > valuation_time || p.amount <= 0.0 {
297                continue;
298            }
299            if let Some(ts) = settled_at
300                && (p.time - ts).abs() <= 1e-6
301            {
302                close_logs.push(p.amount.ln());
303                had_close_pay = true;
304                continue;
305            }
306            interim_logs.push(p.amount.ln());
307        }
308        if had_close_pay {
309            n_settled_with_pay += 1;
310        }
311    }
312
313    if total_exposure_open <= 0.0 || n_settled == 0 {
314        return Err(ValidationError::InvalidParameter(
315            "insufficient settled claim exposure to estimate settlement hazard",
316        ));
317    }
318    let settlement_hazard = n_settled as f64 / total_exposure_open;
319    let interim_payment_hazard = interim_logs.len() as f64 / total_exposure_open;
320    let settlement_payment_prob = n_settled_with_pay as f64 / n_settled as f64;
321
322    let (interim_severity_mu, interim_severity_sigma) = fit_lognormal(&interim_logs);
323    let (settlement_severity_mu, settlement_severity_sigma) = fit_lognormal(&close_logs);
324
325    let model = MicroReservingModel {
326        occurrence_intensities,
327        reporting_delay_rate: rho,
328        interim_payment_hazard,
329        settlement_hazard,
330        interim_severity_mu,
331        interim_severity_sigma,
332        settlement_payment_prob,
333        settlement_severity_mu,
334        settlement_severity_sigma,
335    };
336    model.validate()?;
337    Ok(model)
338}
339
340fn fit_lognormal(log_amounts: &[f64]) -> (f64, f64) {
341    if log_amounts.is_empty() {
342        return (0.0, 0.0);
343    }
344    let m = log_amounts.len() as f64;
345    let mu = log_amounts.iter().sum::<f64>() / m;
346    if log_amounts.len() < 2 {
347        return (mu, 0.0);
348    }
349    let var = log_amounts.iter().map(|&v| (v - mu).powi(2)).sum::<f64>() / (m - 1.0);
350    (mu, var.max(0.0).sqrt())
351}
352
353#[inline]
354fn simulate_single_open_claim(
355    model: &MicroReservingModel,
356    p_interim: f64,
357    rng: &mut DeterministicRng,
358) -> f64 {
359    let mut paid = 0.0;
360    // Competing exponential hazards: geometrically distributed number of interim
361    // payments before settlement (memoryless property).
362    loop {
363        if rng.next_open01() < p_interim {
364            let z = rng.next_standard_normal();
365            paid += (model.interim_severity_mu + model.interim_severity_sigma * z).exp();
366        } else {
367            if model.settlement_payment_prob > 0.0
368                && rng.next_open01() < model.settlement_payment_prob
369            {
370                let z = rng.next_standard_normal();
371                paid += (model.settlement_severity_mu + model.settlement_severity_sigma * z).exp();
372            }
373            break;
374        }
375    }
376    paid
377}
378
379/// Simulate RBNS and IBNR reserve distributions from a fitted [`MicroReservingModel`]
380/// and the observed claim log as of `valuation_time`.
381pub fn simulate_reserves(
382    claims: &[ClaimRecord],
383    model: &MicroReservingModel,
384    valuation_time: f64,
385    n_simulations: usize,
386    seed: u64,
387) -> Result<MicroReservingResult, ValidationError> {
388    model.validate()?;
389    if n_simulations == 0 || !valuation_time.is_finite() || valuation_time <= 0.0 {
390        return Err(ValidationError::InvalidParameter(
391            "n_simulations must be >= 1 and valuation_time > 0",
392        ));
393    }
394
395    let n_open_claims = claims
396        .iter()
397        .filter(|c| {
398            c.report_time <= valuation_time
399                && match c.settlement_time {
400                    Some(ts) => ts > valuation_time,
401                    None => true,
402                }
403        })
404        .count();
405
406    let expected_ibnr = model.expected_ibnr_count(valuation_time);
407    let p_interim =
408        model.interim_payment_hazard / (model.interim_payment_hazard + model.settlement_hazard);
409    let mut rng = DeterministicRng::from_seed(seed);
410
411    let mut total_draws = Vec::with_capacity(n_simulations);
412    let mut ibnr_count_sum = 0.0;
413    let mut w_rbns = OnlineMoments::default();
414    let mut w_ibnr = OnlineMoments::default();
415    let mut w_total = OnlineMoments::default();
416
417    for _ in 0..n_simulations {
418        let mut rbns = 0.0;
419        for _ in 0..n_open_claims {
420            rbns += simulate_single_open_claim(model, p_interim, &mut rng);
421        }
422
423        let n_ibnr = rng.sample_poisson(expected_ibnr).round() as usize;
424        ibnr_count_sum += n_ibnr as f64;
425        let mut ibnr = 0.0;
426        for _ in 0..n_ibnr {
427            ibnr += simulate_single_open_claim(model, p_interim, &mut rng);
428        }
429
430        let tot = rbns + ibnr;
431        w_rbns.push(rbns);
432        w_ibnr.push(ibnr);
433        w_total.push(tot);
434        total_draws.push(tot);
435    }
436
437    let (mean_rbns, sd_rbns) = w_rbns.finish();
438    let (mean_ibnr, sd_ibnr) = w_ibnr.finish();
439    let (mean_total, sd_total) = w_total.finish();
440
441    // Cascading single-clone selection for [50%, 75%, 90%, 95%, 99%] quantiles (O(N)).
442    let total_quantiles = five_quantiles(&total_draws);
443
444    Ok(MicroReservingResult {
445        n_simulations,
446        n_open_claims,
447        mean_ibnr_count: ibnr_count_sum / n_simulations as f64,
448        mean_rbns,
449        mean_ibnr,
450        mean_total,
451        sd_rbns,
452        sd_ibnr,
453        sd_total,
454        total_quantiles,
455        total_draws,
456    })
457}
458
459/// Generate a synthetic individual-claim event log from a known [`MicroReservingModel`]
460/// up to `valuation_time` (for validation, backtesting, and benchmark tests).
461///
462/// Returns `(observed_claims, true_unpaid_rbns, true_unpaid_ibnr)`.
463pub fn simulate_synthetic_portfolio(
464    model: &MicroReservingModel,
465    valuation_time: f64,
466    seed: u64,
467) -> Result<(Vec<ClaimRecord>, f64, f64), ValidationError> {
468    model.validate()?;
469    let mut rng = DeterministicRng::from_seed(seed);
470    let mut observed = Vec::new();
471    let mut true_rbns = 0.0;
472    let mut true_ibnr = 0.0;
473    let mut next_id = 1u64;
474
475    let total_rate = model.interim_payment_hazard + model.settlement_hazard;
476    let p_interim = model.interim_payment_hazard / total_rate;
477
478    for (k, &lam) in model.occurrence_intensities.iter().enumerate() {
479        let a = k as f64;
480        let b = ((k + 1) as f64).min(valuation_time);
481        if b <= a {
482            continue;
483        }
484        let n_occ = rng.sample_poisson(lam * (b - a)).round() as usize;
485        for _ in 0..n_occ {
486            let t_occ = a + (b - a) * rng.next_open01();
487            let rep_delay = -rng.next_open01().ln() / model.reporting_delay_rate;
488            let t_rep = t_occ + rep_delay;
489
490            let mut cur_t = t_rep;
491            let mut obs_payments = Vec::new();
492            let mut future_paid = 0.0;
493            let t_settle;
494
495            loop {
496                let dt = -rng.next_open01().ln() / total_rate;
497                cur_t += dt;
498                if rng.next_open01() < p_interim {
499                    let amt = (model.interim_severity_mu
500                        + model.interim_severity_sigma * rng.next_standard_normal())
501                    .exp();
502                    if cur_t <= valuation_time {
503                        obs_payments.push(ClaimPayment {
504                            time: cur_t,
505                            amount: amt,
506                        });
507                    } else {
508                        future_paid += amt;
509                    }
510                } else {
511                    if model.settlement_payment_prob > 0.0
512                        && rng.next_open01() < model.settlement_payment_prob
513                    {
514                        let amt = (model.settlement_severity_mu
515                            + model.settlement_severity_sigma * rng.next_standard_normal())
516                        .exp();
517                        if cur_t <= valuation_time {
518                            obs_payments.push(ClaimPayment {
519                                time: cur_t,
520                                amount: amt,
521                            });
522                        } else {
523                            future_paid += amt;
524                        }
525                    }
526                    t_settle = cur_t;
527                    break;
528                }
529            }
530
531            if t_rep <= valuation_time {
532                let settlement_time = if t_settle <= valuation_time {
533                    Some(t_settle)
534                } else {
535                    true_rbns += future_paid;
536                    None
537                };
538                observed.push(ClaimRecord {
539                    claim_id: next_id,
540                    occurrence_time: t_occ,
541                    report_time: t_rep,
542                    settlement_time,
543                    payments: obs_payments,
544                });
545                next_id += 1;
546            } else {
547                true_ibnr += future_paid;
548            }
549        }
550    }
551
552    Ok((observed, true_rbns, true_ibnr))
553}
554
555#[derive(Default)]
556struct OnlineMoments {
557    n: usize,
558    mean: f64,
559    m2: f64,
560}
561
562impl OnlineMoments {
563    #[inline]
564    fn push(&mut self, x: f64) {
565        self.n += 1;
566        let delta = x - self.mean;
567        self.mean += delta / self.n as f64;
568        self.m2 += delta * (x - self.mean);
569    }
570
571    fn finish(&self) -> (f64, f64) {
572        if self.n < 2 {
573            return (self.mean, 0.0);
574        }
575        (self.mean, (self.m2 / (self.n - 1) as f64).max(0.0).sqrt())
576    }
577}
578
579fn five_quantiles(xs: &[f64]) -> [f64; 5] {
580    const PROBS: [f64; 5] = [0.50, 0.75, 0.90, 0.95, 0.99];
581    let n = xs.len();
582    if n == 1 {
583        return [xs[0]; 5];
584    }
585    let mut buf = xs.to_vec();
586    let mut out = [0.0; 5];
587    let mut start = 0usize;
588    let last = (n - 1) as f64;
589    for (slot, &p) in out.iter_mut().zip(PROBS.iter()) {
590        let pos = p * last;
591        let lo = pos.floor() as usize;
592        let hi = pos.ceil() as usize;
593        let weight = pos - lo as f64;
594        let (_, v_lo_ref, right) = buf[start..].select_nth_unstable_by(lo - start, f64::total_cmp);
595        let v_lo = *v_lo_ref;
596        if lo == hi {
597            *slot = v_lo;
598        } else {
599            let v_hi = right.iter().copied().min_by(f64::total_cmp).unwrap_or(v_lo);
600            *slot = v_lo * (1.0 - weight) + v_hi * weight;
601        }
602        start = lo;
603    }
604    out
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610
611    #[test]
612    fn synthetic_event_log_parameter_recovery_and_reserve_unbiasedness() {
613        let true_model = MicroReservingModel {
614            occurrence_intensities: vec![250.0, 250.0, 250.0, 250.0, 250.0],
615            reporting_delay_rate: 2.0,
616            interim_payment_hazard: 0.8,
617            settlement_hazard: 1.2,
618            interim_severity_mu: 7.0,
619            interim_severity_sigma: 0.4,
620            settlement_payment_prob: 0.9,
621            settlement_severity_mu: 8.0,
622            settlement_severity_sigma: 0.5,
623        };
624        let tau = 5.0;
625        let (claims, true_rbns, true_ibnr) =
626            simulate_synthetic_portfolio(&true_model, tau, 12345).unwrap();
627
628        let fitted = fit_from_claims(&claims, tau, 5).unwrap();
629        assert!((fitted.reporting_delay_rate - true_model.reporting_delay_rate).abs() < 0.35);
630        assert!((fitted.settlement_hazard - true_model.settlement_hazard).abs() < 0.20);
631        assert!((fitted.interim_payment_hazard - true_model.interim_payment_hazard).abs() < 0.20);
632
633        let sim = simulate_reserves(&claims, &fitted, tau, 2_000, 99).unwrap();
634        let true_total = true_rbns + true_ibnr;
635        assert!(
636            (sim.mean_total - true_total).abs() / true_total < 0.15,
637            "sim.mean_total={} vs true_total={}",
638            sim.mean_total,
639            true_total
640        );
641        // Quantiles must be monotonically non-decreasing.
642        for w in sim.total_quantiles.windows(2) {
643            assert!(w[0] <= w[1]);
644        }
645    }
646}