Skip to main content

qualia_core_db/specialized_libs/financial_modeling/
risk.rs

1use super::*;
2
3/// Risk assessor
4pub struct RiskAssessor {
5    risk_models: HashMap<String, RiskModel>,
6    risk_metrics: HashMap<String, RiskMetric>,
7    scenario_analyzer: ScenarioAnalyzer,
8}
9
10/// Risk models
11#[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/// Risk model types
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21pub enum RiskModelType {
22    VaR,
23    CVaR,
24    MonteCarlo,
25    Historical,
26    Parametric,
27    StressTest,
28}
29
30/// Risk model parameters
31#[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/// Validation results
40#[derive(Debug, Clone)]
41pub struct ValidationResults {
42    pub backtest_results: BacktestResults,
43    pub model_accuracy: f64,
44    pub calibration_quality: f64,
45}
46
47/// Backtest results
48#[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/// Risk metrics
58#[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/// Metric types
68#[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
79/// Scenario analyzer
80pub struct ScenarioAnalyzer {
81    scenarios: HashMap<String, Scenario>,
82    stress_tests: HashMap<String, StressTest>,
83    sensitivity_analyzer: SensitivityAnalyzer,
84    /// Registered `MarketScenario`s used by `run_scenarios` and as the basis
85    /// for deterministic scenario-based stress testing.
86    market_scenarios: Vec<MarketScenario>,
87}
88
89/// Scenarios
90#[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/// Scenario types
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101pub enum ScenarioType {
102    Economic,
103    Market,
104    Geopolitical,
105    Environmental,
106    Regulatory,
107}
108
109/// Scenario parameters
110#[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/// Stress tests
119#[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/// Stress test types
129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130pub enum StressTestType {
131    Historical,
132    Hypothetical,
133    Reverse,
134    Custom,
135}
136
137/// Stress test results
138#[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/// A market scenario used for scenario-based stress testing.
147///
148/// `shocks` maps `asset_id` → price shock percentage, where e.g. `-0.20`
149/// means a 20% drop in that asset's price. Assets without an entry are
150/// assumed to be unaffected by the scenario.
151#[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    /// Construct a `MarketScenario` from the given fields.
160    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/// Aggregated results of a Monte Carlo stress-test simulation run.
170///
171/// All monetary values are expressed in the portfolio's currency. VaR figures
172/// are reported as positive numbers representing the magnitude of loss at the
173/// given confidence level (i.e. the loss that is not exceeded with the stated
174/// probability). `expected_shortfall` is the average loss in the tail beyond
175/// the 95% VaR. `max_drawdown` is the worst single-simulation loss relative to
176/// the initial portfolio value.
177#[derive(Debug, Clone, PartialEq)]
178pub struct StressTestResult {
179    /// Value-at-Risk at the 95% confidence level (positive = loss magnitude).
180    pub var_95: f64,
181    /// Value-at-Risk at the 99% confidence level (positive = loss magnitude).
182    pub var_99: f64,
183    /// Expected shortfall (average loss beyond the 95% VaR).
184    pub expected_shortfall: f64,
185    /// Largest single-simulation loss relative to the initial portfolio value.
186    pub max_drawdown: f64,
187    /// Fraction of simulations that ended below the initial portfolio value.
188    pub probability_of_loss: f64,
189    /// Mean portfolio value across all simulations.
190    pub mean_portfolio_value: f64,
191    /// Standard deviation of simulated portfolio values.
192    pub std_dev: f64,
193    /// Number of simulations run.
194    pub num_simulations: usize,
195}
196
197/// The impact of a single defined `MarketScenario` on a portfolio.
198#[derive(Debug, Clone, PartialEq)]
199pub struct ScenarioResult {
200    /// Name of the scenario that was applied.
201    pub scenario_name: String,
202    /// Change in portfolio value (negative = loss) as an absolute amount.
203    pub portfolio_impact: f64,
204    /// Portfolio value after applying the scenario's shocks.
205    pub final_value: f64,
206    /// The probability assigned to this scenario.
207    pub probability: f64,
208}
209
210/// Sensitivity analyzer
211pub struct SensitivityAnalyzer {
212    sensitivity_factors: HashMap<String, SensitivityFactor>,
213    correlation_matrix: CorrelationMatrix,
214}
215
216/// Sensitivity factors
217#[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/// Factor types
226#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
227pub enum FactorType {
228    InterestRate,
229    Equity,
230    Credit,
231    Currency,
232    Commodity,
233}
234
235/// Correlation matrix
236#[derive(Debug, Clone)]
237pub struct CorrelationMatrix {
238    pub assets: Vec<String>,
239    pub correlations: Vec<Vec<f64>>,
240    pub last_updated: u64,
241}
242
243/// Risk analyzer
244pub struct RiskAnalyzer {
245    risk_models: HashMap<String, RiskModel>,
246    risk_metrics: HashMap<String, RiskMetric>,
247    scenario_analyzer: ScenarioAnalyzer,
248    /// Registered benchmark return series used to compute real beta/alpha (see
249    /// `portfolio_risk::compute_risk_metrics`). Without an active benchmark,
250    /// beta/alpha are honestly reported as NaN rather than fabricated.
251    benchmark_comparator: BenchmarkComparator,
252    /// Name of the benchmark to use in `calculate_risk_metrics`, if any.
253    active_benchmark: Option<String>,
254}
255
256impl RiskAssessor {
257    /// Construct a `RiskAssessor` with default field values.
258    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    /// Initialize `RiskAssessor`; `Ok` when ready.
267    pub fn initialize(&mut self) -> Result<(), FinancialError> {
268        self.scenario_analyzer.initialize()?;
269        Ok(())
270    }
271
272    /// Add `risk_model` to the `RiskAssessor`.
273    pub fn add_risk_model(&mut self, model: RiskModel) {
274        self.risk_models.insert(model.model_id.clone(), model);
275    }
276
277    /// Look up `risk_model` by id; `None` when absent.
278    pub fn get_risk_model(&self, model_id: &str) -> Option<&RiskModel> {
279        self.risk_models.get(model_id)
280    }
281
282    /// Ids of every registered `risk_model`.
283    pub fn list_risk_models(&self) -> Vec<String> {
284        self.risk_models.keys().cloned().collect()
285    }
286
287    /// Add `risk_metric` to the `RiskAssessor`.
288    pub fn add_risk_metric(&mut self, metric: RiskMetric) {
289        self.risk_metrics.insert(metric.metric_id.clone(), metric);
290    }
291
292    /// Look up `risk_metric` by id; `None` when absent.
293    pub fn get_risk_metric(&self, metric_id: &str) -> Option<&RiskMetric> {
294        self.risk_metrics.get(metric_id)
295    }
296
297    /// Ids of every registered `risk_metric`.
298    pub fn list_risk_metrics(&self) -> Vec<String> {
299        self.risk_metrics.keys().cloned().collect()
300    }
301}
302
303impl ScenarioAnalyzer {
304    /// Construct a `ScenarioAnalyzer` with default field values.
305    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    /// Initialize `ScenarioAnalyzer`; `Ok` when ready.
315    pub fn initialize(&mut self) -> Result<(), FinancialError> {
316        Ok(())
317    }
318
319    /// Register a `MarketScenario` for later use by `run_scenarios`.
320    pub fn add_scenario(&mut self, scenario: MarketScenario) {
321        self.market_scenarios.push(scenario);
322    }
323
324    /// Run a Monte Carlo stress-test simulation over `portfolio`.
325    ///
326    /// For each of `num_simulations` trials, every asset receives an
327    /// independent multiplicative shock drawn from a normal distribution with
328    /// mean `0.0` and standard deviation `volatility` (i.e. a simple return
329    /// model: `new_price = price * (1 + z * volatility)` where `z ~ N(0,1)`
330    /// via an inline Box-Muller transform). The portfolio value after shocks
331    /// is recorded and aggregated into a `StressTestResult`.
332    ///
333    /// A fixed deterministic seed is used so results are reproducible across
334    /// runs (important for test stability). Returns
335    /// `FinancialError::PortfolioError` if the portfolio has no assets or no
336    /// positive value, and `FinancialError::ValidationError` if
337    /// `num_simulations` is zero or `volatility` is negative.
338    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        // Deterministic seed for reproducible results (and stable tests).
369        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    /// Apply each registered `MarketScenario` to `portfolio` and compute its
395    /// impact. Returns one `ScenarioResult` per registered scenario, in
396    /// registration order. An empty scenario set yields an empty result list.
397    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    /// Add `named_scenario` to the `ScenarioAnalyzer`.
429    pub fn add_named_scenario(&mut self, scenario: Scenario) {
430        self.scenarios
431            .insert(scenario.scenario_id.clone(), scenario);
432    }
433
434    /// Look up `named_scenario` by id; `None` when absent.
435    pub fn get_named_scenario(&self, scenario_id: &str) -> Option<&Scenario> {
436        self.scenarios.get(scenario_id)
437    }
438
439    /// Ids of every registered `named_scenario`.
440    pub fn list_named_scenarios(&self) -> Vec<String> {
441        self.scenarios.keys().cloned().collect()
442    }
443
444    /// Add `stress_test` to the `ScenarioAnalyzer`.
445    pub fn add_stress_test(&mut self, test: StressTest) {
446        self.stress_tests.insert(test.test_id.clone(), test);
447    }
448
449    /// Look up `stress_test` by id; `None` when absent.
450    pub fn get_stress_test(&self, test_id: &str) -> Option<&StressTest> {
451        self.stress_tests.get(test_id)
452    }
453
454    /// Ids of every registered `stress_test`.
455    pub fn list_stress_tests(&self) -> Vec<String> {
456        self.stress_tests.keys().cloned().collect()
457    }
458
459    /// The `sensitivity_analyzer` component.
460    pub fn sensitivity_analyzer(&self) -> &SensitivityAnalyzer {
461        &self.sensitivity_analyzer
462    }
463
464    /// The `sensitivity_analyzer` component (mutable).
465    pub fn sensitivity_analyzer_mut(&mut self) -> &mut SensitivityAnalyzer {
466        &mut self.sensitivity_analyzer
467    }
468}
469
470/// Aggregate a vector of simulated portfolio values into a `StressTestResult`.
471///
472/// `initial_value` is the pre-shock portfolio value used as the reference for
473/// loss/drawdown calculations. Expects `values.len() == num_simulations`.
474fn 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    // Losses relative to the initial value (positive = loss).
485    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    // Percentile helper: returns the loss at the given percentile (p in [0,1])
489    // using nearest-rank interpolation.
490    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    // Expected shortfall: average of losses at/above the 95% VaR threshold.
502    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
531/// A small, deterministic, seedable PRNG for Monte Carlo simulation.
532///
533/// Implements a 64-bit linear congruential generator (Numerical Recipes
534/// constants) plus an inline Box-Muller transform for standard normal
535/// samples. No external crate required.
536struct McRng {
537    state: u64,
538}
539
540impl McRng {
541    /// Construct the RNG with `seed` (zero falls back to a canonical non-zero state).
542    fn new(seed: u64) -> Self {
543        // LCG requires a non-zero state; fall back to a canonical seed.
544        Self {
545            state: if seed == 0 {
546                0x9E37_79B9_7F4A_7C15
547            } else {
548                seed
549            },
550        }
551    }
552
553    /// Next raw u64 from the LCG.
554    fn next_u64(&mut self) -> u64 {
555        // Numerical Recipes 64-bit LCG constants.
556        self.state = self
557            .state
558            .wrapping_mul(6364136223846793005)
559            .wrapping_add(1442695040888963407);
560        self.state
561    }
562
563    /// Next uniform f64 in [0, 1).
564    fn next_uniform(&mut self) -> f64 {
565        // Use the high 53 bits for a full-precision mantissa.
566        let x = self.next_u64() >> 11;
567        (x as f64) * (1.0 / (1u64 << 53) as f64)
568    }
569
570    /// Next standard normal sample via the Box-Muller transform.
571    fn next_normal(&mut self) -> f64 {
572        // z = sqrt(-2 ln u1) * cos(2π u2)
573        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    /// Construct a `SensitivityAnalyzer` with default field values.
586    pub fn new() -> Self {
587        Self {
588            sensitivity_factors: HashMap::new(),
589            correlation_matrix: CorrelationMatrix::new(),
590        }
591    }
592
593    /// Add `factor` to the `SensitivityAnalyzer`.
594    pub fn add_factor(&mut self, factor: SensitivityFactor) {
595        self.sensitivity_factors
596            .insert(factor.factor_id.clone(), factor);
597    }
598
599    /// Look up `factor` by id; `None` when absent.
600    pub fn get_factor(&self, factor_id: &str) -> Option<&SensitivityFactor> {
601        self.sensitivity_factors.get(factor_id)
602    }
603
604    /// Ids of every registered `factor`.
605    pub fn list_factors(&self) -> Vec<String> {
606        self.sensitivity_factors.keys().cloned().collect()
607    }
608
609    /// The `correlation_matrix` component.
610    pub fn correlation_matrix(&self) -> &CorrelationMatrix {
611        &self.correlation_matrix
612    }
613
614    /// Replace the `correlation_matrix`.
615    pub fn set_correlation_matrix(&mut self, matrix: CorrelationMatrix) {
616        self.correlation_matrix = matrix;
617    }
618}
619
620impl CorrelationMatrix {
621    /// Construct a `CorrelationMatrix` with default field values.
622    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    /// Construct a `RiskAnalyzer` with default field values.
633    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    /// Initialize `RiskAnalyzer`; `Ok` when ready.
644    pub fn initialize(&mut self) -> Result<(), FinancialError> {
645        self.scenario_analyzer.initialize()?;
646        Ok(())
647    }
648
649    /// Register a benchmark return series by name. If no benchmark is currently
650    /// active, the newly registered one becomes active so that subsequent
651    /// `calculate_risk_metrics` calls produce real beta/alpha.
652    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    /// Select which registered benchmark `calculate_risk_metrics` should use, or
660    /// `None` to compute beta/alpha-free (NaN) metrics.
661    pub fn set_active_benchmark(&mut self, name: Option<&str>) {
662        self.active_benchmark = name.map(|s| s.to_string());
663    }
664
665    /// Compute real risk metrics for `portfolio` via
666    /// `portfolio_risk::compute_risk_metrics` (volatility, VaR/CVaR,
667    /// Sharpe, Sortino, max-drawdown from actual return series). Fails
668    /// `InsufficientData` without price history; beta/alpha are NaN
669    /// unless a benchmark is active via `set_active_benchmark`.
670    pub fn calculate_risk_metrics(
671        &self,
672        portfolio: &Portfolio,
673    ) -> Result<RiskMetrics, FinancialError> {
674        // REAL: computed from the portfolio's asset return time series (derived
675        // from each Asset's price_history, value-weighted into a portfolio return
676        // series), in the `portfolio_risk` library submodule. Volatility, 95% VaR
677        // and CVaR (historical), Sharpe, Sortino and max-drawdown are genuine
678        // sample statistics — never the old fabricated defaults (Sharpe 0.75 etc).
679        // When no return history is present, it still REFUSES with InsufficientData
680        // (the metrics are undefined without returns); beta/alpha are reported NaN
681        // unless an active benchmark is registered, in which case they are
682        // Cov(R_p,R_b)/Var(R_b) and mean(R_p)−beta·mean(R_b).
683        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        // Risk-profile validation: compare the computed volatility / 95% VaR
690        // against the portfolio's declared RiskTolerance. A mismatch yields a
691        // plain-language warning in `risk_profile_assessment` (never a fabricated
692        // "all clear" — `None` means within tolerance, not "unchecked").
693        metrics.risk_profile_assessment =
694            assess_risk_profile(&portfolio.risk_profile.risk_tolerance, &metrics);
695        Ok(metrics)
696    }
697
698    /// Add `risk_model` to the `RiskAnalyzer`.
699    pub fn add_risk_model(&mut self, model: RiskModel) {
700        self.risk_models.insert(model.model_id.clone(), model);
701    }
702
703    /// Look up `risk_model` by id; `None` when absent.
704    pub fn get_risk_model(&self, model_id: &str) -> Option<&RiskModel> {
705        self.risk_models.get(model_id)
706    }
707
708    /// Ids of every registered `risk_model`.
709    pub fn list_risk_models(&self) -> Vec<String> {
710        self.risk_models.keys().cloned().collect()
711    }
712
713    /// Add `risk_metric` to the `RiskAnalyzer`.
714    pub fn add_risk_metric(&mut self, metric: RiskMetric) {
715        self.risk_metrics.insert(metric.metric_id.clone(), metric);
716    }
717
718    /// Look up `risk_metric` by id; `None` when absent.
719    pub fn get_risk_metric(&self, metric_id: &str) -> Option<&RiskMetric> {
720        self.risk_metrics.get(metric_id)
721    }
722
723    /// Ids of every registered `risk_metric`.
724    pub fn list_risk_metrics(&self) -> Vec<String> {
725        self.risk_metrics.keys().cloned().collect()
726    }
727}
728
729/// Compare computed risk metrics against a declared `RiskTolerance` and return a
730/// warning string when the portfolio is riskier than its profile permits. Returns
731/// `None` when the metrics fit the declared tolerance.
732fn assess_risk_profile(tolerance: &RiskTolerance, metrics: &RiskMetrics) -> Option<String> {
733    // Per-period volatility / VaR thresholds for each tolerance band. These are
734    // stated, conservative guards — a Conservative portfolio carrying >10%
735    // per-period volatility or >5% 95% VaR is flagged, etc.
736    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    /// Construct a `RiskModel` with default field values.
763    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    /// Construct a `RiskModelParameters` with default field values.
775    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    /// Construct a `ValidationResults` with default field values.
787    pub fn new() -> Self {
788        Self {
789            backtest_results: BacktestResults::new(),
790            // not measured (scaffold defaults; no model validation is performed)
791            model_accuracy: 0.0,
792            calibration_quality: 0.0,
793        }
794    }
795}
796
797impl BacktestResults {
798    /// Construct a `BacktestResults` with default field values.
799    pub fn new() -> Self {
800        Self {
801            period: (0, 86400 * 365), // 1 year
802            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    /// Construct a `RiskMetric` with default field values.
812    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    /// Construct a `Scenario` with default field values.
825    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    /// Construct a `ScenarioParameters` with default field values.
838    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    /// Construct a `StressTest` with default field values.
850    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    /// Construct a `StressTestResults` with default field values.
863    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    /// Construct a `SensitivityFactor` with default field values.
875    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}