1use crate::reserve_distribution::{mean, rvar, tvar_coherent};
38use crate::validate::{ValidationError, validate_finite_slice};
39
40#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
42pub struct EulerAllocationResult {
43 pub portfolio_risk_measure: f64,
45 pub portfolio_mean: f64,
47 pub portfolio_risk_capital: f64,
49 pub standalone_means: Vec<f64>,
51 pub standalone_risk_measures: Vec<f64>,
53 pub allocated_total: Vec<f64>,
55 pub allocated_capital: Vec<f64>,
57 pub allocation_shares: Vec<f64>,
59 pub diversification_credit: Vec<f64>,
61 pub diversification_ratio: f64,
63}
64
65#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
67pub struct MyersReadAllocationResult {
68 pub portfolio_liability: f64,
70 pub portfolio_assets: f64,
72 pub portfolio_surplus: f64,
74 pub default_probability: f64,
76 pub default_put_value: f64,
78 pub default_value_ratio: f64,
80 pub line_liabilities: Vec<f64>,
82 pub conditional_tail_losses: Vec<f64>,
84 pub allocated_assets: Vec<f64>,
86 pub allocated_surplus: Vec<f64>,
88 pub surplus_ratios: Vec<f64>,
90 pub portfolio_surplus_ratio: f64,
92}
93
94pub 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
134pub 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
181pub 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
254pub 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 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
354pub 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 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 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
428fn 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 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 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 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 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 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 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 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 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}