1use super::*;
2
3pub struct RiskAssessor {
5 risk_models: HashMap<String, RiskModel>,
6 risk_metrics: HashMap<String, RiskMetric>,
7 scenario_analyzer: ScenarioAnalyzer,
8}
9
10#[derive(Debug, Clone)]
12pub struct RiskModel {
13 pub model_id: String,
14 pub model_type: RiskModelType,
15 pub parameters: RiskModelParameters,
16 pub validation_results: ValidationResults,
17}
18
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21pub enum RiskModelType {
22 VaR,
23 CVaR,
24 MonteCarlo,
25 Historical,
26 Parametric,
27 StressTest,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct RiskModelParameters {
33 pub confidence_level: f64,
34 pub time_horizon: u32,
35 pub lookback_period: u32,
36 pub simulation_count: u32,
37}
38
39#[derive(Debug, Clone)]
41pub struct ValidationResults {
42 pub backtest_results: BacktestResults,
43 pub model_accuracy: f64,
44 pub calibration_quality: f64,
45}
46
47#[derive(Debug, Clone)]
49pub struct BacktestResults {
50 pub period: (u64, u64),
51 pub hit_rate: f64,
52 pub average_loss: f64,
53 pub maximum_loss: f64,
54 pub sharpe_ratio: f64,
55}
56
57#[derive(Debug, Clone)]
59pub struct RiskMetric {
60 pub metric_id: String,
61 pub metric_name: String,
62 pub metric_type: MetricType,
63 pub value: f64,
64 pub timestamp: u64,
65}
66
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub enum MetricType {
70 VaR,
71 CVaR,
72 Volatility,
73 Beta,
74 Alpha,
75 Sharpe,
76 Sortino,
77}
78
79pub struct ScenarioAnalyzer {
81 scenarios: HashMap<String, Scenario>,
82 stress_tests: HashMap<String, StressTest>,
83 sensitivity_analyzer: SensitivityAnalyzer,
84 market_scenarios: Vec<MarketScenario>,
87}
88
89#[derive(Debug, Clone)]
91pub struct Scenario {
92 pub scenario_id: String,
93 pub scenario_name: String,
94 pub scenario_type: ScenarioType,
95 pub parameters: ScenarioParameters,
96 pub probability: f64,
97}
98
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101pub enum ScenarioType {
102 Economic,
103 Market,
104 Geopolitical,
105 Environmental,
106 Regulatory,
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct ScenarioParameters {
112 pub market_shocks: HashMap<String, f64>,
113 pub interest_rate_changes: HashMap<String, f64>,
114 pub currency_movements: HashMap<String, f64>,
115 pub commodity_price_changes: HashMap<String, f64>,
116}
117
118#[derive(Debug, Clone)]
120pub struct StressTest {
121 pub test_id: String,
122 pub test_name: String,
123 pub test_type: StressTestType,
124 pub scenarios: Vec<String>,
125 pub results: StressTestResults,
126}
127
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130pub enum StressTestType {
131 Historical,
132 Hypothetical,
133 Reverse,
134 Custom,
135}
136
137#[derive(Debug, Clone)]
139pub struct StressTestResults {
140 pub portfolio_value_change: f64,
141 pub worst_case_loss: f64,
142 pub recovery_time: u32,
143 pub affected_assets: Vec<String>,
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct MarketScenario {
153 pub name: String,
154 pub probability: f64,
155 pub shocks: HashMap<String, f64>,
156}
157
158impl MarketScenario {
159 pub fn new(name: impl Into<String>, probability: f64, shocks: HashMap<String, f64>) -> Self {
161 Self {
162 name: name.into(),
163 probability,
164 shocks,
165 }
166 }
167}
168
169#[derive(Debug, Clone, PartialEq)]
178pub struct StressTestResult {
179 pub var_95: f64,
181 pub var_99: f64,
183 pub expected_shortfall: f64,
185 pub max_drawdown: f64,
187 pub probability_of_loss: f64,
189 pub mean_portfolio_value: f64,
191 pub std_dev: f64,
193 pub num_simulations: usize,
195}
196
197#[derive(Debug, Clone, PartialEq)]
199pub struct ScenarioResult {
200 pub scenario_name: String,
202 pub portfolio_impact: f64,
204 pub final_value: f64,
206 pub probability: f64,
208}
209
210pub struct SensitivityAnalyzer {
212 sensitivity_factors: HashMap<String, SensitivityFactor>,
213 correlation_matrix: CorrelationMatrix,
214}
215
216#[derive(Debug, Clone)]
218pub struct SensitivityFactor {
219 pub factor_id: String,
220 pub factor_name: String,
221 pub factor_type: FactorType,
222 pub sensitivity: f64,
223}
224
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
227pub enum FactorType {
228 InterestRate,
229 Equity,
230 Credit,
231 Currency,
232 Commodity,
233}
234
235#[derive(Debug, Clone)]
237pub struct CorrelationMatrix {
238 pub assets: Vec<String>,
239 pub correlations: Vec<Vec<f64>>,
240 pub last_updated: u64,
241}
242
243pub struct RiskAnalyzer {
245 risk_models: HashMap<String, RiskModel>,
246 risk_metrics: HashMap<String, RiskMetric>,
247 scenario_analyzer: ScenarioAnalyzer,
248 benchmark_comparator: BenchmarkComparator,
252 active_benchmark: Option<String>,
254}
255
256impl RiskAssessor {
257 pub fn new() -> Self {
259 Self {
260 risk_models: HashMap::new(),
261 risk_metrics: HashMap::new(),
262 scenario_analyzer: ScenarioAnalyzer::new(),
263 }
264 }
265
266 pub fn initialize(&mut self) -> Result<(), FinancialError> {
268 self.scenario_analyzer.initialize()?;
269 Ok(())
270 }
271
272 pub fn add_risk_model(&mut self, model: RiskModel) {
274 self.risk_models.insert(model.model_id.clone(), model);
275 }
276
277 pub fn get_risk_model(&self, model_id: &str) -> Option<&RiskModel> {
279 self.risk_models.get(model_id)
280 }
281
282 pub fn list_risk_models(&self) -> Vec<String> {
284 self.risk_models.keys().cloned().collect()
285 }
286
287 pub fn add_risk_metric(&mut self, metric: RiskMetric) {
289 self.risk_metrics.insert(metric.metric_id.clone(), metric);
290 }
291
292 pub fn get_risk_metric(&self, metric_id: &str) -> Option<&RiskMetric> {
294 self.risk_metrics.get(metric_id)
295 }
296
297 pub fn list_risk_metrics(&self) -> Vec<String> {
299 self.risk_metrics.keys().cloned().collect()
300 }
301}
302
303impl ScenarioAnalyzer {
304 pub fn new() -> Self {
306 Self {
307 scenarios: HashMap::new(),
308 stress_tests: HashMap::new(),
309 sensitivity_analyzer: SensitivityAnalyzer::new(),
310 market_scenarios: Vec::new(),
311 }
312 }
313
314 pub fn initialize(&mut self) -> Result<(), FinancialError> {
316 Ok(())
317 }
318
319 pub fn add_scenario(&mut self, scenario: MarketScenario) {
321 self.market_scenarios.push(scenario);
322 }
323
324 pub fn run_monte_carlo(
339 &self,
340 portfolio: &Portfolio,
341 num_simulations: usize,
342 volatility: f64,
343 ) -> Result<StressTestResult, FinancialError> {
344 if num_simulations == 0 {
345 return Err(FinancialError::ValidationError(
346 "num_simulations must be greater than zero".to_string(),
347 ));
348 }
349 if volatility < 0.0 {
350 return Err(FinancialError::ValidationError(
351 "volatility must be non-negative".to_string(),
352 ));
353 }
354 if portfolio.assets.is_empty() {
355 return Err(FinancialError::PortfolioError(
356 "portfolio has no assets to simulate".to_string(),
357 ));
358 }
359
360 let initial_value: f64 =
361 portfolio.assets.iter().map(|a| a.market_value).sum::<f64>() + portfolio.cash_balance;
362 if !(initial_value > 0.0) {
363 return Err(FinancialError::PortfolioError(
364 "portfolio has no positive value to simulate".to_string(),
365 ));
366 }
367
368 let mut rng = McRng::new(0x9E37_79B9_7F4A_7C15);
370
371 let mut values: Vec<f64> = Vec::with_capacity(num_simulations);
372 for _ in 0..num_simulations {
373 let mut sim_value = portfolio.cash_balance;
374 for asset in &portfolio.assets {
375 let z = if volatility > 0.0 {
376 rng.next_normal()
377 } else {
378 0.0
379 };
380 let shock = z * volatility;
381 let new_price = asset.current_price * (1.0 + shock);
382 sim_value += new_price * asset.quantity;
383 }
384 values.push(sim_value);
385 }
386
387 Ok(aggregate_stress_test_result(
388 &values,
389 initial_value,
390 num_simulations,
391 ))
392 }
393
394 pub fn run_scenarios(
398 &self,
399 portfolio: &Portfolio,
400 ) -> Result<Vec<ScenarioResult>, FinancialError> {
401 if portfolio.assets.is_empty() {
402 return Err(FinancialError::PortfolioError(
403 "portfolio has no assets to stress".to_string(),
404 ));
405 }
406
407 let initial_value: f64 =
408 portfolio.assets.iter().map(|a| a.market_value).sum::<f64>() + portfolio.cash_balance;
409
410 let mut results = Vec::with_capacity(self.market_scenarios.len());
411 for scenario in &self.market_scenarios {
412 let mut final_value = portfolio.cash_balance;
413 for asset in &portfolio.assets {
414 let shock = scenario.shocks.get(&asset.asset_id).copied().unwrap_or(0.0);
415 let new_price = asset.current_price * (1.0 + shock);
416 final_value += new_price * asset.quantity;
417 }
418 results.push(ScenarioResult {
419 scenario_name: scenario.name.clone(),
420 portfolio_impact: final_value - initial_value,
421 final_value,
422 probability: scenario.probability,
423 });
424 }
425 Ok(results)
426 }
427
428 pub fn add_named_scenario(&mut self, scenario: Scenario) {
430 self.scenarios
431 .insert(scenario.scenario_id.clone(), scenario);
432 }
433
434 pub fn get_named_scenario(&self, scenario_id: &str) -> Option<&Scenario> {
436 self.scenarios.get(scenario_id)
437 }
438
439 pub fn list_named_scenarios(&self) -> Vec<String> {
441 self.scenarios.keys().cloned().collect()
442 }
443
444 pub fn add_stress_test(&mut self, test: StressTest) {
446 self.stress_tests.insert(test.test_id.clone(), test);
447 }
448
449 pub fn get_stress_test(&self, test_id: &str) -> Option<&StressTest> {
451 self.stress_tests.get(test_id)
452 }
453
454 pub fn list_stress_tests(&self) -> Vec<String> {
456 self.stress_tests.keys().cloned().collect()
457 }
458
459 pub fn sensitivity_analyzer(&self) -> &SensitivityAnalyzer {
461 &self.sensitivity_analyzer
462 }
463
464 pub fn sensitivity_analyzer_mut(&mut self) -> &mut SensitivityAnalyzer {
466 &mut self.sensitivity_analyzer
467 }
468}
469
470fn aggregate_stress_test_result(
475 values: &[f64],
476 initial_value: f64,
477 num_simulations: usize,
478) -> StressTestResult {
479 let n = values.len();
480 let mean: f64 = values.iter().sum::<f64>() / n as f64;
481 let variance: f64 = values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / n as f64;
482 let std_dev = variance.sqrt();
483
484 let mut losses: Vec<f64> = values.iter().map(|v| initial_value - v).collect();
486 losses.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
487
488 let percentile = |p: f64| -> f64 {
491 if n == 1 {
492 return losses[0];
493 }
494 let rank = (p * (n - 1) as f64).round() as usize;
495 losses[rank.min(n - 1)]
496 };
497
498 let var_95 = percentile(0.95).max(0.0);
499 let var_99 = percentile(0.99).max(0.0);
500
501 let tail_threshold = percentile(0.95);
503 let tail_losses: Vec<f64> = losses
504 .iter()
505 .filter(|&&l| l >= tail_threshold)
506 .copied()
507 .collect();
508 let expected_shortfall = if tail_losses.is_empty() {
509 var_95
510 } else {
511 tail_losses.iter().sum::<f64>() / tail_losses.len() as f64
512 };
513
514 let max_drawdown = losses.last().copied().unwrap_or(0.0).max(0.0);
515
516 let num_losses = values.iter().filter(|v| **v < initial_value).count() as f64;
517 let probability_of_loss = num_losses / n as f64;
518
519 StressTestResult {
520 var_95,
521 var_99,
522 expected_shortfall,
523 max_drawdown,
524 probability_of_loss,
525 mean_portfolio_value: mean,
526 std_dev,
527 num_simulations,
528 }
529}
530
531struct McRng {
537 state: u64,
538}
539
540impl McRng {
541 fn new(seed: u64) -> Self {
543 Self {
545 state: if seed == 0 {
546 0x9E37_79B9_7F4A_7C15
547 } else {
548 seed
549 },
550 }
551 }
552
553 fn next_u64(&mut self) -> u64 {
555 self.state = self
557 .state
558 .wrapping_mul(6364136223846793005)
559 .wrapping_add(1442695040888963407);
560 self.state
561 }
562
563 fn next_uniform(&mut self) -> f64 {
565 let x = self.next_u64() >> 11;
567 (x as f64) * (1.0 / (1u64 << 53) as f64)
568 }
569
570 fn next_normal(&mut self) -> f64 {
572 let mut u1 = self.next_uniform();
574 if u1 < f64::MIN_POSITIVE {
575 u1 = f64::MIN_POSITIVE;
576 }
577 let u2 = self.next_uniform();
578 let r = (-2.0 * u1.ln()).sqrt();
579 let theta = 2.0 * std::f64::consts::PI * u2;
580 r * theta.cos()
581 }
582}
583
584impl SensitivityAnalyzer {
585 pub fn new() -> Self {
587 Self {
588 sensitivity_factors: HashMap::new(),
589 correlation_matrix: CorrelationMatrix::new(),
590 }
591 }
592
593 pub fn add_factor(&mut self, factor: SensitivityFactor) {
595 self.sensitivity_factors
596 .insert(factor.factor_id.clone(), factor);
597 }
598
599 pub fn get_factor(&self, factor_id: &str) -> Option<&SensitivityFactor> {
601 self.sensitivity_factors.get(factor_id)
602 }
603
604 pub fn list_factors(&self) -> Vec<String> {
606 self.sensitivity_factors.keys().cloned().collect()
607 }
608
609 pub fn correlation_matrix(&self) -> &CorrelationMatrix {
611 &self.correlation_matrix
612 }
613
614 pub fn set_correlation_matrix(&mut self, matrix: CorrelationMatrix) {
616 self.correlation_matrix = matrix;
617 }
618}
619
620impl CorrelationMatrix {
621 pub fn new() -> Self {
623 Self {
624 assets: Vec::new(),
625 correlations: Vec::new(),
626 last_updated: 0,
627 }
628 }
629}
630
631impl RiskAnalyzer {
632 pub fn new() -> Self {
634 Self {
635 risk_models: HashMap::new(),
636 risk_metrics: HashMap::new(),
637 scenario_analyzer: ScenarioAnalyzer::new(),
638 benchmark_comparator: BenchmarkComparator::new(),
639 active_benchmark: None,
640 }
641 }
642
643 pub fn initialize(&mut self) -> Result<(), FinancialError> {
645 self.scenario_analyzer.initialize()?;
646 Ok(())
647 }
648
649 pub fn add_benchmark(&mut self, name: &str, returns: Vec<f64>) {
653 self.benchmark_comparator.add_benchmark(name, returns);
654 if self.active_benchmark.is_none() {
655 self.active_benchmark = Some(name.to_string());
656 }
657 }
658
659 pub fn set_active_benchmark(&mut self, name: Option<&str>) {
662 self.active_benchmark = name.map(|s| s.to_string());
663 }
664
665 pub fn calculate_risk_metrics(
671 &self,
672 portfolio: &Portfolio,
673 ) -> Result<RiskMetrics, FinancialError> {
674 let benchmark_returns = self
684 .active_benchmark
685 .as_deref()
686 .and_then(|name| self.benchmark_comparator.benchmark_returns(name));
687 let mut metrics = portfolio_risk::compute_risk_metrics(portfolio, benchmark_returns)?;
688
689 metrics.risk_profile_assessment =
694 assess_risk_profile(&portfolio.risk_profile.risk_tolerance, &metrics);
695 Ok(metrics)
696 }
697
698 pub fn add_risk_model(&mut self, model: RiskModel) {
700 self.risk_models.insert(model.model_id.clone(), model);
701 }
702
703 pub fn get_risk_model(&self, model_id: &str) -> Option<&RiskModel> {
705 self.risk_models.get(model_id)
706 }
707
708 pub fn list_risk_models(&self) -> Vec<String> {
710 self.risk_models.keys().cloned().collect()
711 }
712
713 pub fn add_risk_metric(&mut self, metric: RiskMetric) {
715 self.risk_metrics.insert(metric.metric_id.clone(), metric);
716 }
717
718 pub fn get_risk_metric(&self, metric_id: &str) -> Option<&RiskMetric> {
720 self.risk_metrics.get(metric_id)
721 }
722
723 pub fn list_risk_metrics(&self) -> Vec<String> {
725 self.risk_metrics.keys().cloned().collect()
726 }
727}
728
729fn assess_risk_profile(tolerance: &RiskTolerance, metrics: &RiskMetrics) -> Option<String> {
733 let (max_vol, max_var): (f64, f64) = match tolerance {
737 RiskTolerance::Conservative => (0.10, 0.05),
738 RiskTolerance::Moderate => (0.20, 0.10),
739 RiskTolerance::Aggressive => (0.35, 0.18),
740 RiskTolerance::VeryAggressive => (f64::INFINITY, f64::INFINITY),
741 };
742 let over_vol = metrics.volatility > max_vol;
743 let over_var = metrics.var_95 > max_var;
744 if over_vol || over_var {
745 let label = match tolerance {
746 RiskTolerance::Conservative => "Conservative",
747 RiskTolerance::Moderate => "Moderate",
748 RiskTolerance::Aggressive => "Aggressive",
749 RiskTolerance::VeryAggressive => "VeryAggressive",
750 };
751 Some(format!(
752 "Portfolio declared as {label} but computed risk exceeds its tolerance band \
753 (volatility {:.4} > limit {:.4}, VaR(95%) {:.4} > limit {:.4}).",
754 metrics.volatility, max_vol, metrics.var_95, max_var,
755 ))
756 } else {
757 None
758 }
759}
760
761impl RiskModel {
762 pub fn new() -> Self {
764 Self {
765 model_id: "model_1".to_string(),
766 model_type: RiskModelType::VaR,
767 parameters: RiskModelParameters::new(),
768 validation_results: ValidationResults::new(),
769 }
770 }
771}
772
773impl RiskModelParameters {
774 pub fn new() -> Self {
776 Self {
777 confidence_level: 0.95,
778 time_horizon: 1,
779 lookback_period: 252,
780 simulation_count: 10000,
781 }
782 }
783}
784
785impl ValidationResults {
786 pub fn new() -> Self {
788 Self {
789 backtest_results: BacktestResults::new(),
790 model_accuracy: 0.0,
792 calibration_quality: 0.0,
793 }
794 }
795}
796
797impl BacktestResults {
798 pub fn new() -> Self {
800 Self {
801 period: (0, 86400 * 365), hit_rate: 0.95,
803 average_loss: 1000.0,
804 maximum_loss: 5000.0,
805 sharpe_ratio: 1.5,
806 }
807 }
808}
809
810impl RiskMetric {
811 pub fn new() -> Self {
813 Self {
814 metric_id: "metric_1".to_string(),
815 metric_name: "VaR".to_string(),
816 metric_type: MetricType::VaR,
817 value: 1000.0,
818 timestamp: 0,
819 }
820 }
821}
822
823impl Scenario {
824 pub fn new() -> Self {
826 Self {
827 scenario_id: "scenario_1".to_string(),
828 scenario_name: "Market crash".to_string(),
829 scenario_type: ScenarioType::Market,
830 parameters: ScenarioParameters::new(),
831 probability: 0.05,
832 }
833 }
834}
835
836impl ScenarioParameters {
837 pub fn new() -> Self {
839 Self {
840 market_shocks: HashMap::new(),
841 interest_rate_changes: HashMap::new(),
842 currency_movements: HashMap::new(),
843 commodity_price_changes: HashMap::new(),
844 }
845 }
846}
847
848impl StressTest {
849 pub fn new() -> Self {
851 Self {
852 test_id: "test_1".to_string(),
853 test_name: "Market stress test".to_string(),
854 test_type: StressTestType::Historical,
855 scenarios: vec!["scenario_1".to_string()],
856 results: StressTestResults::new(),
857 }
858 }
859}
860
861impl StressTestResults {
862 pub fn new() -> Self {
864 Self {
865 portfolio_value_change: -0.2,
866 worst_case_loss: 20000.0,
867 recovery_time: 30,
868 affected_assets: vec!["asset_1".to_string()],
869 }
870 }
871}
872
873impl SensitivityFactor {
874 pub fn new() -> Self {
876 Self {
877 factor_id: "factor_1".to_string(),
878 factor_name: "Interest rate".to_string(),
879 factor_type: FactorType::InterestRate,
880 sensitivity: 0.5,
881 }
882 }
883}