Skip to main content

reserving_kernels/deterministic/
separation.rs

1//! Taylor (1977) Arithmetic and Geometric Separation Methods.
2//!
3//! Implements:
4//!
5//! * G. C. Taylor (1977), *Separation of Inflation and Other Effects from the
6//!   Distribution of Non-Life Insurance Claim Delays*, ASTIN Bulletin, Vol. 9,
7//!   No. 1–2, pp. 219–230.
8//!
9//! Factors incremental claim costs per unit exposure $S_{i,j} = X_{i,j} / n_i$
10//! into development delay proportions $r_j$ ($\sum_{j=0}^{n-1} r_j = 1$) and
11//! exogenous calendar-year inflation indices $\lambda_{i+j}$:
12//!
13//! $$S_{i,j} = r_j \cdot \lambda_{i+j}$$
14//!
15//! Supports both:
16//! * **Arithmetic Separation** ([`SeparationMethod::Arithmetic`]): exact
17//!   backward diagonal/column recursion matching Taylor (1977) §2.
18//! * **Geometric Separation** ([`SeparationMethod::Geometric`]): exact
19//!   log-linear OLS via Householder QR ($\ln S_{i,j} = \alpha_j + \beta_{i+j}$)
20//!   normalized to $\sum_j r_j = 1$, matching Taylor (1977) §3.
21
22use crate::linalg::weighted_least_squares_qr_beta_only;
23use crate::preprocessing::triangle::{cumulative_to_incremental, latest_diagonal};
24use crate::types::TriangleView;
25use crate::validate::{ValidationError, validate_positive_finite_slice, validate_triangle};
26
27/// Variant of Taylor's (1977) Separation Method.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
29pub enum SeparationMethod {
30    /// Non-parametric arithmetic recursion over calendar diagonals and development columns.
31    Arithmetic,
32    /// Log-linear geometric least-squares separation ($\ln S_{i,j} = \ln r_j + \ln \lambda_{i+j}$).
33    Geometric,
34}
35
36/// Strategy for projecting future calendar-year inflation indices $\lambda_n, \dots, \lambda_{2n-2}$.
37#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
38pub enum InflationProjection {
39    /// Extrapolate from $\hat{\lambda}_{n-1}$ at a constant annual inflation rate `rate`
40    /// ($\lambda_{n-1+h} = \hat{\lambda}_{n-1} (1 + \text{rate})^h$).
41    ConstantRate(f64),
42    /// Extrapolate using the geometric mean historical inflation rate
43    /// $(\hat{\lambda}_{n-1} / \hat{\lambda}_0)^{1/(n-1)} - 1$.
44    HistoricalGeometricMean,
45    /// Use explicit caller-supplied future calendar-year indices
46    /// $\lambda_n, \dots, \lambda_{2n-2}$ (length `n - 1`).
47    ExplicitFutureIndices(Vec<f64>),
48}
49
50/// Result of Taylor's (1977) Separation Method.
51#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
52pub struct SeparationResult {
53    /// Separation variant used.
54    pub method: SeparationMethod,
55    /// Estimated development delay proportions $r_j$ ($\sum r_j = 1$), length $n$.
56    pub delay_proportions: Vec<f64>,
57    /// Estimated historical calendar-year inflation indices $\lambda_0, \dots, \lambda_{n-1}$, length $n$.
58    pub calendar_indices: Vec<f64>,
59    /// Projected future calendar-year inflation indices $\lambda_n, \dots, \lambda_{2n-2}$, length $n - 1$.
60    pub future_calendar_indices: Vec<f64>,
61    /// Implied historical period-to-period calendar inflation rates $\lambda_k / \lambda_{k-1} - 1$, length $n - 1$.
62    pub implied_inflation_rates: Vec<f64>,
63    /// Latest observed cumulative loss per origin, length $n$.
64    pub latest: Vec<f64>,
65    /// Projected reserve per origin, length $n$.
66    pub reserve: Vec<f64>,
67    /// Projected ultimate per origin (`latest + reserve`), length $n$.
68    pub ultimate: Vec<f64>,
69    /// Total reserve across all origins.
70    pub total_reserve: f64,
71}
72
73impl std::fmt::Display for SeparationResult {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        write!(
76            f,
77            "Separation({:?}, total_reserve={:.2})",
78            self.method, self.total_reserve
79        )
80    }
81}
82
83/// Fit Taylor's (1977) Separation Method to a square cumulative loss triangle
84/// and per-origin exposures (e.g. claim counts or earned exposure $n_i > 0$).
85pub fn analyze(
86    cumulative: &TriangleView<'_>,
87    exposures: &[f64],
88    method: SeparationMethod,
89    projection: &InflationProjection,
90) -> Result<SeparationResult, ValidationError> {
91    validate_triangle(cumulative)?;
92    let n = cumulative.n_origins;
93    if n < 2 {
94        return Err(ValidationError::InvalidParameter(
95            "triangle must be at least 2x2",
96        ));
97    }
98    if exposures.len() != n {
99        return Err(ValidationError::ShapeMismatch);
100    }
101    validate_positive_finite_slice(exposures, "exposures")?;
102
103    let inc = cumulative_to_incremental(cumulative);
104    let mut s = vec![f64::NAN; n * n];
105    for i in 0..n {
106        for j in 0..(n - i) {
107            let x = inc[i * n + j];
108            if !x.is_finite() {
109                return Err(ValidationError::NotFinite);
110            }
111            s[i * n + j] = x / exposures[i];
112        }
113    }
114
115    let (delay_proportions, calendar_indices) = match method {
116        SeparationMethod::Arithmetic => fit_arithmetic(&s, n)?,
117        SeparationMethod::Geometric => fit_geometric(&s, n)?,
118    };
119
120    let mut implied_inflation_rates = Vec::with_capacity(n - 1);
121    for k in 1..n {
122        let prev = calendar_indices[k - 1];
123        let curr = calendar_indices[k];
124        if prev.abs() > 0.0 {
125            implied_inflation_rates.push(curr / prev - 1.0);
126        } else {
127            implied_inflation_rates.push(f64::NAN);
128        }
129    }
130
131    let future_calendar_indices = match projection {
132        InflationProjection::ConstantRate(rate) => {
133            if !rate.is_finite() || *rate <= -1.0 {
134                return Err(ValidationError::InvalidParameter(
135                    "inflation rate must be finite and > -1.0",
136                ));
137            }
138            let base = calendar_indices[n - 1];
139            (1..n).map(|h| base * (1.0 + rate).powi(h as i32)).collect()
140        }
141        InflationProjection::HistoricalGeometricMean => {
142            let first = calendar_indices[0];
143            let last = calendar_indices[n - 1];
144            if first <= 0.0 || last <= 0.0 {
145                return Err(ValidationError::InvalidParameter(
146                    "geometric mean inflation requires positive first and last calendar indices",
147                ));
148            }
149            let g = (last / first).powf(1.0 / (n as f64 - 1.0));
150            (1..n).map(|h| last * g.powi(h as i32)).collect()
151        }
152        InflationProjection::ExplicitFutureIndices(indices) => {
153            if indices.len() != n - 1 {
154                return Err(ValidationError::ShapeMismatch);
155            }
156            for &v in indices {
157                if !v.is_finite() || v < 0.0 {
158                    return Err(ValidationError::InvalidParameter(
159                        "future calendar indices must be finite and non-negative",
160                    ));
161                }
162            }
163            indices.clone()
164        }
165    };
166
167    let latest = latest_diagonal(cumulative);
168    let mut reserve = vec![0.0; n];
169    let mut ultimate = vec![0.0; n];
170    for i in 0..n {
171        let mut r_i = 0.0;
172        for j in (n - i)..n {
173            let cal_idx = i + j; // in n..=2n-2
174            let lam = future_calendar_indices[cal_idx - n];
175            r_i += exposures[i] * delay_proportions[j] * lam;
176        }
177        reserve[i] = r_i;
178        ultimate[i] = latest[i] + r_i;
179    }
180    let total_reserve: f64 = reserve.iter().sum();
181
182    Ok(SeparationResult {
183        method,
184        delay_proportions,
185        calendar_indices,
186        future_calendar_indices,
187        implied_inflation_rates,
188        latest,
189        reserve,
190        ultimate,
191        total_reserve,
192    })
193}
194
195fn fit_arithmetic(s: &[f64], n: usize) -> Result<(Vec<f64>, Vec<f64>), ValidationError> {
196    let mut diag_sums = vec![0.0; n];
197    let mut col_sums = vec![0.0; n];
198
199    for i in 0..n {
200        for j in 0..(n - i) {
201            let v = s[i * n + j];
202            diag_sums[i + j] += v;
203            col_sums[j] += v;
204        }
205    }
206
207    let mut r = vec![0.0; n];
208    let mut lam = vec![0.0; n];
209
210    let mut sum_r_tail = 0.0_f64;
211    let mut sum_lam_tail = 0.0_f64;
212
213    for k in (0..n).rev() {
214        let rem_r = 1.0_f64 - sum_r_tail;
215        if rem_r.abs() <= 1e-14 {
216            return Err(ValidationError::DivideByZero(
217                "arithmetic separation remaining delay proportion",
218            ));
219        }
220        lam[k] = diag_sums[k] / rem_r;
221        sum_lam_tail += lam[k];
222        if sum_lam_tail.abs() <= 1e-14 {
223            return Err(ValidationError::DivideByZero(
224                "arithmetic separation cumulative calendar index",
225            ));
226        }
227        r[k] = col_sums[k] / sum_lam_tail;
228        sum_r_tail += r[k];
229    }
230
231    Ok((r, lam))
232}
233
234fn fit_geometric(s: &[f64], n: usize) -> Result<(Vec<f64>, Vec<f64>), ValidationError> {
235    // Log-linear OLS: ln(S_{i,j}) = alpha_j + beta_{i+j}, with beta_{n-1} = 0.
236    // Parameters: [alpha_0..alpha_{n-1}, beta_0..beta_{n-2}] (length 2n - 1).
237    let p = 2 * n - 1;
238    let mut x_rows = Vec::new();
239    let mut y_vals = Vec::new();
240
241    for i in 0..n {
242        for j in 0..(n - i) {
243            let v = s[i * n + j];
244            if v <= 0.0 {
245                return Err(ValidationError::InvalidParameter(
246                    "geometric separation requires strictly positive incremental losses",
247                ));
248            }
249            let mut row = vec![0.0; p];
250            row[j] = 1.0;
251            let k = i + j;
252            if k < n - 1 {
253                row[n + k] = 1.0;
254            }
255            x_rows.extend_from_slice(&row);
256            y_vals.push(v.ln());
257        }
258    }
259
260    let n_obs = y_vals.len();
261    let weights = vec![1.0; n_obs];
262    let beta = weighted_least_squares_qr_beta_only(&x_rows, &y_vals, &weights, n_obs, p)?;
263
264    let raw_r: Vec<f64> = (0..n).map(|j| beta[j].exp()).collect();
265    let sum_r: f64 = raw_r.iter().sum();
266    if !sum_r.is_finite() || sum_r <= 0.0 {
267        return Err(ValidationError::DivideByZero(
268            "geometric separation delay normalization",
269        ));
270    }
271
272    let r: Vec<f64> = raw_r.into_iter().map(|v| v / sum_r).collect();
273    let mut lam = Vec::with_capacity(n);
274    for k in 0..(n - 1) {
275        lam.push(beta[n + k].exp() * sum_r);
276    }
277    lam.push(sum_r);
278
279    Ok((r, lam))
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285    use crate::Triangle;
286
287    #[test]
288    fn exact_recovery_on_synthetic_stepped_inflation_triangle() {
289        let true_r = [0.40, 0.30, 0.18, 0.08, 0.04];
290        let true_lam = [100.0, 108.0, 120.0, 140.0, 165.0];
291        let exposures = [50.0, 55.0, 60.0, 62.0, 70.0];
292        let n = 5;
293
294        let mut inc_rows: Vec<Vec<f64>> = Vec::new();
295        for i in 0..n {
296            let mut row = Vec::new();
297            for j in 0..(n - i) {
298                row.push(exposures[i] * true_r[j] * true_lam[i + j]);
299            }
300            inc_rows.push(row);
301        }
302        let slices: Vec<&[f64]> = inc_rows.iter().map(std::vec::Vec::as_slice).collect();
303        let tri = Triangle::try_from_incremental_rows(&slices).unwrap();
304
305        for method in [SeparationMethod::Arithmetic, SeparationMethod::Geometric] {
306            let res = analyze(
307                &tri.view(),
308                &exposures,
309                method,
310                &InflationProjection::ConstantRate(0.10),
311            )
312            .unwrap();
313
314            let sum_r: f64 = res.delay_proportions.iter().sum();
315            assert!((sum_r - 1.0).abs() < 1e-12);
316            for j in 0..n {
317                assert!(
318                    (res.delay_proportions[j] - true_r[j]).abs() < 1e-10,
319                    "{method:?} r[{j}] mismatch"
320                );
321                assert!(
322                    (res.calendar_indices[j] - true_lam[j]).abs() < 1e-9,
323                    "{method:?} lam[{j}] mismatch"
324                );
325            }
326            assert!(res.total_reserve > 0.0);
327        }
328    }
329}