Skip to main content

reserving_kernels/
capital_allocation.rs

1//! Coherent capital allocation via Tasche's (2008) Euler principle and
2//! Myers & Read's (2001) marginal default-put allocation.
3//!
4//! Implements:
5//!
6//! * D. Tasche, *"Capital Allocation to Business Units and Sub-Portfolios: the
7//!   Euler Principle"*, in *Pillar II in the New Basel Accord* (2008),
8//!   pp. 423–453.
9//! * S. C. Myers & J. A. Read, *"Capital Allocation for Insurance Companies"*,
10//!   *Journal of Risk and Insurance*, Vol. 68, No. 4 (2001), pp. 545–580.
11//! * S. J. Mildenhall & J. A. Major, *Introduction to Capital Modeling and
12//!   Portfolio Management*, CAS Monograph No. 15, §5.
13//!
14//! ## Exact Conservation Identities
15//!
16//! For aligned multi-line scenario samples `X_0, ..., X_{d-1}` (each of length
17//! `N`) with aggregate portfolio loss `S_k = sum_{i=0}^{d-1} X_{i, k}`:
18//!
19//! * **Euler TVaR (`euler_tvar_allocation`)**:
20//!   `AC_i(TVaR_alpha) = E[X_i | S >= VaR_alpha(S)]` using exact tie-symmetric
21//!   quantile-integral weights matching [`crate::reserve_distribution::tvar_coherent`]
22//!   (CAS Monograph No. 15, Algorithm 3.4.3). Guarantees exact full allocation
23//!   `sum_i AC_i == tvar_coherent(S, alpha)` even on discrete distributions
24//!   with ties or non-integer `(1 - alpha) * N`.
25//! * **Euler RVaR (`euler_rvar_allocation`)**:
26//!   exact tie-symmetric allocation for Range VaR `RVaR_{p_low, p_high}(S)`,
27//!   conserving `sum_i AC_i == rvar(S, p_low, p_high)`.
28//! * **Euler Standard Deviation (`euler_sd_allocation`)**:
29//!   `AC_i = E[X_i] + kappa * Cov(X_i, S) / sigma(S)`, conserving
30//!   `sum_i AC_i == E[S] + kappa * sigma(S)`.
31//! * **Myers & Read (2001) (`myers_read_allocation`)**:
32//!   marginal default-value allocation equalizing `dD / dL_i = D / L` at asset
33//!   level `A = L + Q`:
34//!   `Q_i = L_i * (Q / L) + (E[X_i | S > A] - (L_i / L) * E[S | S > A])`,
35//!   conserving `sum_i Q_i == Q` and `sum_i (L_i + Q_i) == A` identically.
36
37use crate::reserve_distribution::{mean, rvar, tvar_coherent};
38use crate::validate::{ValidationError, validate_finite_slice};
39
40/// Output of an Euler coherent risk-measure capital allocation across `d` lines.
41#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
42pub struct EulerAllocationResult {
43    /// Portfolio aggregate risk measure `rho(S)`.
44    pub portfolio_risk_measure: f64,
45    /// Portfolio expected loss `E[S]`.
46    pub portfolio_mean: f64,
47    /// Portfolio risk capital above mean `rho(S) - E[S]`.
48    pub portfolio_risk_capital: f64,
49    /// Standalone expected loss `E[X_i]` per line (length `d`).
50    pub standalone_means: Vec<f64>,
51    /// Standalone risk measure `rho(X_i)` per line (length `d`).
52    pub standalone_risk_measures: Vec<f64>,
53    /// Euler allocated total risk measure `AC_i` per line (`sum_i AC_i == rho(S)`).
54    pub allocated_total: Vec<f64>,
55    /// Euler allocated risk capital above mean `AC_i - E[X_i]` per line.
56    pub allocated_capital: Vec<f64>,
57    /// Allocation shares `AC_i / rho(S)` per line (summing to `1.0` when `rho(S) != 0`).
58    pub allocation_shares: Vec<f64>,
59    /// Diversification credit per line: `standalone_risk_measures[i] - allocated_total[i]`.
60    pub diversification_credit: Vec<f64>,
61    /// Portfolio diversification ratio `rho(S) / sum_i rho(X_i)`.
62    pub diversification_ratio: f64,
63}
64
65/// Output of Myers & Read (2001) marginal default-put surplus allocation.
66#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
67pub struct MyersReadAllocationResult {
68    /// Total portfolio expected liabilities `L = E[S]`.
69    pub portfolio_liability: f64,
70    /// Total portfolio assets `A = L + Q`.
71    pub portfolio_assets: f64,
72    /// Total portfolio surplus `Q = A - L`.
73    pub portfolio_surplus: f64,
74    /// Portfolio insolvency probability `P(S > A)`.
75    pub default_probability: f64,
76    /// Insolvency default put value `D(A) = E[(S - A)_+]`.
77    pub default_put_value: f64,
78    /// Portfolio default-value-to-liability ratio `d = D(A) / L`.
79    pub default_value_ratio: f64,
80    /// Expected liability `L_i = E[X_i]` per line (length `d`).
81    pub line_liabilities: Vec<f64>,
82    /// Conditional tail expectation `E[X_i | S > A]` per line (length `d`).
83    pub conditional_tail_losses: Vec<f64>,
84    /// Allocated assets `A_i = L_i + Q_i` per line (`sum_i A_i == A`).
85    pub allocated_assets: Vec<f64>,
86    /// Allocated surplus `Q_i` per line (`sum_i Q_i == Q`).
87    pub allocated_surplus: Vec<f64>,
88    /// Allocated surplus-to-liability ratio `s_i = Q_i / L_i` per line.
89    pub surplus_ratios: Vec<f64>,
90    /// Portfolio aggregate surplus-to-liability ratio `s = Q / L`.
91    pub portfolio_surplus_ratio: f64,
92}
93
94/// Compute exact coherent Euler allocation of `TVaR_alpha(S)` across `lines`
95/// (Tasche 2008; CAS Monograph No. 15, §5).
96///
97/// Scenario weights match [`crate::reserve_distribution::tvar_coherent`]
98/// (Algorithm 3.4.3) and distribute boundary-tie mass symmetrically across all
99/// tied scenarios, ensuring exact permutation invariance and
100/// `sum_i allocated_total[i] == tvar_coherent(S, alpha)`.
101pub fn euler_tvar_allocation(
102    lines: &[&[f64]],
103    alpha: f64,
104) -> Result<EulerAllocationResult, ValidationError> {
105    if !alpha.is_finite() {
106        return Err(ValidationError::NotFinite);
107    }
108    if !(0.0..=1.0).contains(&alpha) {
109        return Err(ValidationError::InvalidMaturity {
110            index: 0,
111            value: alpha,
112        });
113    }
114    let (d, n, total) = validate_and_sum_lines(lines)?;
115    let (sparse_weights, portfolio_risk_measure) =
116        coherent_interval_sparse_weights(&total, alpha, 1.0);
117
118    let standalone_risk_measures = lines
119        .iter()
120        .map(|col| tvar_coherent(col, alpha))
121        .collect::<Result<Vec<_>, _>>()?;
122
123    build_euler_result(
124        lines,
125        &total,
126        &sparse_weights,
127        d,
128        n,
129        portfolio_risk_measure,
130        standalone_risk_measures,
131    )
132}
133
134/// Compute exact tie-symmetric Euler allocation of Range VaR
135/// `RVaR_{p_low, p_high}(S)` across `lines` (Cont et al. 2010; CAS Monograph 15).
136pub fn euler_rvar_allocation(
137    lines: &[&[f64]],
138    p_low: f64,
139    p_high: f64,
140) -> Result<EulerAllocationResult, ValidationError> {
141    if !p_low.is_finite() || !p_high.is_finite() {
142        return Err(ValidationError::NotFinite);
143    }
144    if !(0.0..=1.0).contains(&p_low) {
145        return Err(ValidationError::InvalidMaturity {
146            index: 0,
147            value: p_low,
148        });
149    }
150    if !(0.0..=1.0).contains(&p_high) {
151        return Err(ValidationError::InvalidMaturity {
152            index: 1,
153            value: p_high,
154        });
155    }
156    if !(p_low < p_high) {
157        return Err(ValidationError::InvalidParameter(
158            "euler_rvar_allocation requires p_low < p_high",
159        ));
160    }
161    let (d, n, total) = validate_and_sum_lines(lines)?;
162    let (sparse_weights, portfolio_risk_measure) =
163        coherent_interval_sparse_weights(&total, p_low, p_high);
164
165    let standalone_risk_measures = lines
166        .iter()
167        .map(|col| rvar(col, p_low, p_high))
168        .collect::<Result<Vec<_>, _>>()?;
169
170    build_euler_result(
171        lines,
172        &total,
173        &sparse_weights,
174        d,
175        n,
176        portfolio_risk_measure,
177        standalone_risk_measures,
178    )
179}
180
181/// Compute exact Euler allocation under the Standard Deviation principle
182/// `rho_kappa(S) = E[S] + kappa * sigma(S)` (Tasche 2008, Example 2.3):
183///
184/// `AC_i = E[X_i] + kappa * Cov(X_i, S) / sigma(S)`.
185pub fn euler_sd_allocation(
186    lines: &[&[f64]],
187    kappa: f64,
188) -> Result<EulerAllocationResult, ValidationError> {
189    if !kappa.is_finite() {
190        return Err(ValidationError::NotFinite);
191    }
192    if kappa < 0.0 {
193        return Err(ValidationError::Negative);
194    }
195    let (d, n, total) = validate_and_sum_lines(lines)?;
196    let nf = n as f64;
197    let denom = if n > 1 { nf - 1.0 } else { 1.0 };
198
199    let portfolio_mean = mean(&total)?;
200    let total_var = if n > 1 {
201        total
202            .iter()
203            .map(|&s| (s - portfolio_mean).powi(2))
204            .sum::<f64>()
205            / denom
206    } else {
207        0.0
208    };
209    let total_sd = total_var.sqrt();
210    let portfolio_risk_measure = portfolio_mean + kappa * total_sd;
211
212    let mut standalone_means = Vec::with_capacity(d);
213    let mut standalone_risk_measures = Vec::with_capacity(d);
214    let mut allocated_total = Vec::with_capacity(d);
215    let mut allocated_capital = Vec::with_capacity(d);
216
217    for &col in lines {
218        let mu_i = mean(col)?;
219        let var_i = if n > 1 {
220            col.iter().map(|&x| (x - mu_i).powi(2)).sum::<f64>() / denom
221        } else {
222            0.0
223        };
224        let cov_is = if n > 1 {
225            col.iter()
226                .zip(total.iter())
227                .map(|(&x, &s)| (x - mu_i) * (s - portfolio_mean))
228                .sum::<f64>()
229                / denom
230        } else {
231            0.0
232        };
233        let cap_i = if total_sd > 0.0 {
234            kappa * cov_is / total_sd
235        } else {
236            0.0
237        };
238        standalone_means.push(mu_i);
239        standalone_risk_measures.push(mu_i + kappa * var_i.sqrt());
240        allocated_capital.push(cap_i);
241        allocated_total.push(mu_i + cap_i);
242    }
243
244    Ok(finalize_euler_struct(
245        portfolio_risk_measure,
246        portfolio_mean,
247        standalone_means,
248        standalone_risk_measures,
249        allocated_total,
250        allocated_capital,
251    ))
252}
253
254/// Compute Myers & Read (2001) marginal default-put surplus allocation across
255/// `lines` at explicit total portfolio assets `total_assets` (`A = L + Q`).
256///
257/// Requires `total_assets < max(S)` so that the insolvency event `{S > A}` has
258/// strictly positive empirical probability (`P(S > A) > 0`).
259pub fn myers_read_allocation(
260    lines: &[&[f64]],
261    total_assets: f64,
262) -> Result<MyersReadAllocationResult, ValidationError> {
263    if !total_assets.is_finite() {
264        return Err(ValidationError::NotFinite);
265    }
266    let (d, n, total) = validate_and_sum_lines(lines)?;
267    myers_read_allocation_with_total(lines, d, n, &total, total_assets)
268}
269
270fn myers_read_allocation_with_total(
271    lines: &[&[f64]],
272    d: usize,
273    n: usize,
274    total: &[f64],
275    total_assets: f64,
276) -> Result<MyersReadAllocationResult, ValidationError> {
277    let nf = n as f64;
278
279    let portfolio_liability: f64 = total.iter().sum::<f64>() / nf;
280    if !(portfolio_liability > 0.0) {
281        return Err(ValidationError::InvalidParameter(
282            "Myers & Read allocation requires strictly positive expected portfolio liability",
283        ));
284    }
285    let line_liabilities: Vec<f64> = lines
286        .iter()
287        .map(|col| col.iter().sum::<f64>() / nf)
288        .collect();
289
290    let mut tail_indices = Vec::new();
291    let mut default_put_sum = 0.0;
292    let mut tail_total_sum = 0.0;
293    for (k, &sk) in total.iter().enumerate() {
294        if sk > total_assets {
295            tail_indices.push(k);
296            default_put_sum += sk - total_assets;
297            tail_total_sum += sk;
298        }
299    }
300    if tail_indices.is_empty() {
301        return Err(ValidationError::InvalidParameter(
302            "Myers & Read allocation requires total_assets < max(S) for positive default probability",
303        ));
304    }
305
306    let n_tail = tail_indices.len() as f64;
307    let default_probability = n_tail / nf;
308    let default_put_value = default_put_sum / nf;
309    let default_value_ratio = default_put_value / portfolio_liability;
310    let portfolio_surplus = total_assets - portfolio_liability;
311    let portfolio_surplus_ratio = portfolio_surplus / portfolio_liability;
312    let cond_tail_total = tail_total_sum / n_tail;
313
314    let mut conditional_tail_losses = Vec::with_capacity(d);
315    let mut allocated_surplus = Vec::with_capacity(d);
316    let mut allocated_assets = Vec::with_capacity(d);
317    let mut surplus_ratios = Vec::with_capacity(d);
318
319    for (i, &col) in lines.iter().enumerate() {
320        let mut line_tail_sum = 0.0;
321        for &idx in &tail_indices {
322            line_tail_sum += col[idx];
323        }
324        let e_xi_tail = line_tail_sum / n_tail;
325        let li = line_liabilities[i];
326        let li_share = li / portfolio_liability;
327
328        // Myers & Read (2001) Eq. (11):
329        // Q_i = L_i * (Q / L) + (E[X_i | S > A] - (L_i / L) * E[S | S > A]).
330        let qi = li * portfolio_surplus_ratio + (e_xi_tail - li_share * cond_tail_total);
331        let ai = li + qi;
332        conditional_tail_losses.push(e_xi_tail);
333        allocated_surplus.push(qi);
334        allocated_assets.push(ai);
335        surplus_ratios.push(if li.abs() > 0.0 { qi / li } else { 0.0 });
336    }
337
338    Ok(MyersReadAllocationResult {
339        portfolio_liability,
340        portfolio_assets: total_assets,
341        portfolio_surplus,
342        default_probability,
343        default_put_value,
344        default_value_ratio,
345        line_liabilities,
346        conditional_tail_losses,
347        allocated_assets,
348        allocated_surplus,
349        surplus_ratios,
350        portfolio_surplus_ratio,
351    })
352}
353
354/// Solve for the portfolio asset level `A` matching a target default-value-to-
355/// liability ratio `target_default_ratio = E[(S - A)_+] / E[S]` and compute
356/// the resulting Myers & Read (2001) surplus allocation.
357pub fn myers_read_from_default_ratio(
358    lines: &[&[f64]],
359    target_default_ratio: f64,
360) -> Result<MyersReadAllocationResult, ValidationError> {
361    if !target_default_ratio.is_finite() {
362        return Err(ValidationError::NotFinite);
363    }
364    if !(target_default_ratio > 0.0 && target_default_ratio < 1.0) {
365        return Err(ValidationError::InvalidParameter(
366            "target_default_ratio must lie strictly inside (0, 1)",
367        ));
368    }
369    let (d, n, total) = validate_and_sum_lines(lines)?;
370    let nf = n as f64;
371    let l = total.iter().sum::<f64>() / nf;
372    if !(l > 0.0) {
373        return Err(ValidationError::InvalidParameter(
374            "Myers & Read allocation requires positive expected liability",
375        ));
376    }
377    let target_sum_excess = target_default_ratio * l * nf;
378    let mut sorted_total = total.clone();
379    sorted_total.sort_unstable_by(f64::total_cmp);
380    let s_max = sorted_total[n - 1];
381
382    // Exact closed-form solver for piecewise-linear G(A) = sum_k max(s_k - A, 0) = target_sum_excess.
383    // Scan from the largest outcome downward to bracket the active tail interval.
384    let mut tail_sum = 0.0_f64;
385    let mut assets = None;
386    for (tail_count, m) in (0..n).rev().enumerate() {
387        let sm = sorted_total[m];
388        let g_at_sm = tail_sum - (tail_count as f64) * sm;
389        if g_at_sm >= target_sum_excess && tail_count > 0 {
390            assets = Some((tail_sum - target_sum_excess) / tail_count as f64);
391            break;
392        }
393        tail_sum += sm;
394    }
395    let assets = assets.unwrap_or_else(|| (tail_sum - target_sum_excess) / nf);
396    // Guarantee strictly below s_max so at least one scenario has S > A (MSRV 1.85 safe).
397    let safe_assets = if assets >= s_max {
398        s_max - s_max.abs().max(1.0) * 1e-12
399    } else {
400        assets
401    };
402    myers_read_allocation_with_total(lines, d, n, &total, safe_assets)
403}
404
405fn validate_and_sum_lines(lines: &[&[f64]]) -> Result<(usize, usize, Vec<f64>), ValidationError> {
406    if lines.is_empty() {
407        return Err(ValidationError::ShapeMismatch);
408    }
409    let n = lines[0].len();
410    if n == 0 {
411        return Err(ValidationError::ShapeMismatch);
412    }
413    for &col in lines {
414        if col.len() != n {
415            return Err(ValidationError::ShapeMismatch);
416        }
417        validate_finite_slice(col)?;
418    }
419    let mut total = vec![0.0; n];
420    for &col in lines {
421        for k in 0..n {
422            total[k] += col[k];
423        }
424    }
425    Ok((lines.len(), n, total))
426}
427
428/// Exact O(N) tie-symmetric sparse scenario weights `(idx, w_idx)` (`sum w == 1`)
429/// and exact portfolio risk measure `sum w_idx * total[idx]`, matching
430/// `(1 / (p_high - p_low)) * int_{p_low}^{p_high} F^-(u) du`.
431fn coherent_interval_sparse_weights(
432    total: &[f64],
433    p_low: f64,
434    p_high: f64,
435) -> (Vec<(usize, f64)>, f64) {
436    let n = total.len();
437    let nf = n as f64;
438
439    if p_low >= 1.0 {
440        // Put equal weight on all scenarios tied at the maximum in O(N).
441        let mut max_val = f64::NEG_INFINITY;
442        for &v in total {
443            if v > max_val {
444                max_val = v;
445            }
446        }
447        let mut sparse = Vec::new();
448        for (idx, &v) in total.iter().enumerate() {
449            if v == max_val {
450                sparse.push((idx, 0.0));
451            }
452        }
453        let w = 1.0 / sparse.len() as f64;
454        for pair in &mut sparse {
455            pair.1 = w;
456        }
457        return (sparse, max_val);
458    }
459
460    let width = p_high - p_low;
461    let k_lo = ((p_low * nf).floor() as usize).min(n - 1);
462    let k_hi = ((p_high * nf).ceil() as usize).clamp(k_lo + 1, n);
463
464    // Find the boundary order statistics v_lo = S_{(k_lo)} and v_hi = S_{(k_hi - 1)} in O(N).
465    let mut scratch = total.to_vec();
466    let (_, pivot_lo, right) = scratch.select_nth_unstable_by(k_lo, f64::total_cmp);
467    let v_lo = *pivot_lo;
468    let v_hi = if k_hi - 1 == k_lo {
469        v_lo
470    } else {
471        let rel = k_hi - 1 - k_lo - 1;
472        let (_, pivot_hi, _) = right.select_nth_unstable_by(rel, f64::total_cmp);
473        *pivot_hi
474    };
475
476    let interior_w = 1.0 / (nf * width);
477    let mut sparse = Vec::with_capacity(k_hi - k_lo + 8);
478    let mut portfolio_risk = 0.0;
479
480    if v_lo == v_hi {
481        // Entire quantile interval lies within a single tie value v_lo.
482        let mut count_eq = 0usize;
483        for (idx, &v) in total.iter().enumerate() {
484            if v == v_lo {
485                sparse.push((idx, 0.0));
486                count_eq += 1;
487            }
488        }
489        let w = 1.0 / count_eq as f64;
490        for pair in &mut sparse {
491            pair.1 = w;
492        }
493        return (sparse, v_lo);
494    }
495
496    // Single O(N) pass: collect interior elements (v_lo < v < v_hi) directly with exact
497    // weight 1 / (N * width), and track boundary tie groups at v_lo and v_hi.
498    let mut n_lt_lo = 0usize;
499    let mut eq_lo = Vec::new();
500    let mut n_lt_hi = 0usize;
501    let mut eq_hi = Vec::new();
502
503    for (idx, &v) in total.iter().enumerate() {
504        if v < v_lo {
505            n_lt_lo += 1;
506            n_lt_hi += 1;
507        } else if v == v_lo {
508            eq_lo.push(idx);
509            n_lt_hi += 1;
510        } else if v < v_hi {
511            sparse.push((idx, interior_w));
512            portfolio_risk += interior_w * v;
513            n_lt_hi += 1;
514        } else if v == v_hi {
515            eq_hi.push(idx);
516        }
517    }
518
519    // Tie-symmetric mass for the lower boundary group spanning sorted ranks [n_lt_lo, n_lt_lo + eq_lo.len()).
520    let lo_start = (n_lt_lo as f64 / nf).max(p_low);
521    let lo_end = ((n_lt_lo + eq_lo.len()) as f64 / nf).min(p_high);
522    if lo_end > lo_start && !eq_lo.is_empty() {
523        let group_mass = (lo_end - lo_start) / width;
524        let w_lo = group_mass / eq_lo.len() as f64;
525        portfolio_risk += group_mass * v_lo;
526        for idx in eq_lo {
527            sparse.push((idx, w_lo));
528        }
529    }
530
531    // Tie-symmetric mass for the upper boundary group spanning sorted ranks [n_lt_hi, n_lt_hi + eq_hi.len()).
532    let hi_start = (n_lt_hi as f64 / nf).max(p_low);
533    let hi_end = ((n_lt_hi + eq_hi.len()) as f64 / nf).min(p_high);
534    if hi_end > hi_start && !eq_hi.is_empty() {
535        let group_mass = (hi_end - hi_start) / width;
536        let w_hi = group_mass / eq_hi.len() as f64;
537        portfolio_risk += group_mass * v_hi;
538        for idx in eq_hi {
539            sparse.push((idx, w_hi));
540        }
541    }
542
543    (sparse, portfolio_risk)
544}
545
546fn build_euler_result(
547    lines: &[&[f64]],
548    total: &[f64],
549    sparse_weights: &[(usize, f64)],
550    d: usize,
551    _n: usize,
552    portfolio_risk_measure: f64,
553    standalone_risk_measures: Vec<f64>,
554) -> Result<EulerAllocationResult, ValidationError> {
555    let portfolio_mean = mean(total)?;
556    let mut standalone_means = Vec::with_capacity(d);
557    let mut allocated_total = Vec::with_capacity(d);
558    let mut allocated_capital = Vec::with_capacity(d);
559
560    for &col in lines {
561        let mu_i = mean(col)?;
562        let mut ac_i = 0.0;
563        for &(idx, w) in sparse_weights {
564            ac_i += w * col[idx];
565        }
566        standalone_means.push(mu_i);
567        allocated_total.push(ac_i);
568        allocated_capital.push(ac_i - mu_i);
569    }
570
571    Ok(finalize_euler_struct(
572        portfolio_risk_measure,
573        portfolio_mean,
574        standalone_means,
575        standalone_risk_measures,
576        allocated_total,
577        allocated_capital,
578    ))
579}
580
581fn finalize_euler_struct(
582    portfolio_risk_measure: f64,
583    portfolio_mean: f64,
584    standalone_means: Vec<f64>,
585    standalone_risk_measures: Vec<f64>,
586    allocated_total: Vec<f64>,
587    allocated_capital: Vec<f64>,
588) -> EulerAllocationResult {
589    let portfolio_risk_capital = portfolio_risk_measure - portfolio_mean;
590    let allocation_shares: Vec<f64> = allocated_total
591        .iter()
592        .map(|&ac| {
593            if portfolio_risk_measure.abs() > 0.0 {
594                ac / portfolio_risk_measure
595            } else {
596                0.0
597            }
598        })
599        .collect();
600    let diversification_credit: Vec<f64> = standalone_risk_measures
601        .iter()
602        .zip(allocated_total.iter())
603        .map(|(&s, &a)| s - a)
604        .collect();
605    let sum_standalone: f64 = standalone_risk_measures.iter().sum();
606    let diversification_ratio = if sum_standalone.abs() > 0.0 {
607        portfolio_risk_measure / sum_standalone
608    } else {
609        1.0
610    };
611
612    EulerAllocationResult {
613        portfolio_risk_measure,
614        portfolio_mean,
615        portfolio_risk_capital,
616        standalone_means,
617        standalone_risk_measures,
618        allocated_total,
619        allocated_capital,
620        allocation_shares,
621        diversification_credit,
622        diversification_ratio,
623    }
624}
625
626#[cfg(test)]
627mod tests {
628    use super::*;
629
630    #[test]
631    fn euler_tvar_conserves_sum_exactly_with_ties_and_non_integer_tail() {
632        // 10 scenarios with boundary ties and non-integer tail at alpha = 0.73.
633        let line_a = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 70.0, 90.0, 120.0];
634        let line_b = [15.0, 10.0, 25.0, 30.0, 35.0, 40.0, 50.0, 50.0, 60.0, 110.0];
635        let line_c = [5.0, 12.0, 18.0, 22.0, 28.0, 30.0, 30.0, 30.0, 40.0, 70.0];
636
637        let res = euler_tvar_allocation(&[&line_a, &line_b, &line_c], 0.73).expect("euler tvar");
638        let sum_ac: f64 = res.allocated_total.iter().sum();
639        let sum_cap: f64 = res.allocated_capital.iter().sum();
640
641        assert!((sum_ac - res.portfolio_risk_measure).abs() < 1e-12);
642        assert!((sum_cap - res.portfolio_risk_capital).abs() < 1e-12);
643        assert!(res.diversification_ratio <= 1.0 + 1e-12);
644        for i in 0..3 {
645            assert!(res.allocated_total[i] <= res.standalone_risk_measures[i] + 1e-12);
646        }
647    }
648
649    #[test]
650    fn myers_read_conserves_surplus_and_assets_exactly() {
651        let line_a = [80.0, 90.0, 95.0, 100.0, 105.0, 115.0, 130.0, 180.0];
652        let line_b = [40.0, 45.0, 50.0, 52.0, 55.0, 60.0, 70.0, 140.0];
653        let assets = 220.0;
654
655        let mr = myers_read_allocation(&[&line_a, &line_b], assets).expect("myers read");
656        let sum_surplus: f64 = mr.allocated_surplus.iter().sum();
657        let sum_assets: f64 = mr.allocated_assets.iter().sum();
658
659        assert!((sum_surplus - mr.portfolio_surplus).abs() < 1e-12);
660        assert!((sum_assets - mr.portfolio_assets).abs() < 1e-12);
661        assert!(mr.default_probability > 0.0);
662        assert!(mr.default_put_value > 0.0);
663
664        // Round-trip via target default ratio recovers the same allocation.
665        let mr2 = myers_read_from_default_ratio(&[&line_a, &line_b], mr.default_value_ratio)
666            .expect("from ratio");
667        assert!((mr2.portfolio_assets - assets).abs() < 1e-6);
668    }
669}