Skip to main content

qualia_core_db/specialized_libs/financial_modeling/
results.rs

1use super::*;
2
3/// Financial operation result
4#[derive(Debug, Clone)]
5pub struct FinancialOperationResult<T> {
6    pub result: T,
7    pub execution_time: u64,
8    pub risk_score: f64,
9    pub compliance_status: ComplianceStatus,
10    pub audit_trail: Vec<AuditEntry>,
11}
12
13/// Compliance status
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub enum ComplianceStatus {
16    Compliant,
17    NonCompliant,
18    Pending,
19    Flagged,
20}
21
22impl FinancialPerformanceMetrics {
23    pub fn new() -> Self {
24        Self {
25            total_portfolios: 0,
26            average_return: 0.0,
27            average_volatility: 0.0,
28            average_sharpe_ratio: 0.0,
29            total_assets: 0.0,
30        }
31    }
32}
33
34impl RiskMetrics {
35    pub fn new() -> Self {
36        // Default value — nothing computed. All zero, never fabricated VaR/Sharpe/etc.
37        // (calculate_portfolio_risk returns InsufficientData rather than this default.)
38        Self {
39            portfolio_id: "portfolio_1".to_string(),
40            var_95: 0.0,
41            cvar_95: 0.0,
42            volatility: 0.0,
43            beta: 0.0,
44            alpha: 0.0,
45            sharpe_ratio: 0.0,
46            sortino_ratio: 0.0,
47            max_drawdown: 0.0,
48            overall_risk_score: 0.0,
49            risk_profile_assessment: None,
50        }
51    }
52}
53
54impl OptionParameters {
55    pub fn new() -> Self {
56        Self {
57            underlying_price: 100.0,
58            strike: 105.0,
59            time_to_maturity: 0.25, // 3 months
60            risk_free_rate: 0.05,
61            volatility: 0.2,
62            option_type: OptionType::Call,
63        }
64    }
65}
66
67#[derive(Debug, Clone)]
68pub struct OptionParameters {
69    pub underlying_price: f64,
70    pub strike: f64,
71    pub time_to_maturity: f64,
72    pub risk_free_rate: f64,
73    pub volatility: f64,
74    pub option_type: OptionType,
75}
76
77#[derive(Debug, Clone, PartialEq)]
78pub enum OptionType {
79    Call,
80    Put,
81}
82
83impl OptionPrice {
84    pub fn new() -> Self {
85        Self {
86            price: 5.0,
87            delta: 0.5,
88            gamma: 0.05,
89            theta: -0.01,
90            vega: 0.2,
91            rho: 0.1,
92        }
93    }
94}
95
96#[derive(Debug, Clone)]
97pub struct OptionPrice {
98    pub price: f64,
99    pub delta: f64,
100    pub gamma: f64,
101    pub theta: f64,
102    pub vega: f64,
103    pub rho: f64,
104}
105
106impl TradeResult {
107    pub fn new() -> Self {
108        Self {
109            trade_id: "trade_1".to_string(),
110            order_id: "order_1".to_string(),
111            executed_quantity: 100.0,
112            executed_price: 100.0,
113            execution_time: 0,
114            status: TradeStatus::Filled,
115        }
116    }
117}
118
119#[derive(Debug, Clone, PartialEq)]
120pub enum TradeStatus {
121    Pending,
122    PartiallyFilled,
123    Filled,
124    Cancelled,
125    Rejected,
126}
127
128impl ComplianceResult {
129    pub fn new() -> Self {
130        Self {
131            result_id: "compliance_1".to_string(),
132            portfolio_id: "portfolio_1".to_string(),
133            // Default value — nothing evaluated (Pending), not a fabricated "Compliant / 0.5".
134            status: ComplianceStatus::Pending,
135            risk_score: 0.0,
136            violations: Vec::new(),
137            recommendations: Vec::new(),
138            audit_entries: Vec::new(),
139        }
140    }
141}
142
143/// Trade execution result
144#[derive(Debug, Clone)]
145pub struct TradeResult {
146    pub trade_id: String,
147    pub order_id: String,
148    pub executed_quantity: f64,
149    pub executed_price: f64,
150    pub execution_time: u64,
151    pub status: TradeStatus,
152}
153
154/// Risk analysis metrics for a portfolio
155#[derive(Debug, Clone)]
156pub struct RiskMetrics {
157    pub portfolio_id: String,
158    pub var_95: f64,
159    pub cvar_95: f64,
160    pub volatility: f64,
161    pub beta: f64,
162    pub alpha: f64,
163    pub sharpe_ratio: f64,
164    pub sortino_ratio: f64,
165    pub max_drawdown: f64,
166    pub overall_risk_score: f64,
167    /// Plain-language assessment of whether the computed volatility / VaR fit the
168    /// portfolio's declared `RiskProfile.risk_tolerance`. `None` when the metrics
169    /// are within tolerance (or when no assessment was performed); `Some(warning)`
170    /// when a conservative profile carries high risk — never a fabricated pass.
171    pub risk_profile_assessment: Option<String>,
172}
173
174/// Compliance check result for a portfolio
175#[derive(Debug, Clone)]
176pub struct ComplianceResult {
177    pub result_id: String,
178    pub portfolio_id: String,
179    pub status: ComplianceStatus,
180    pub risk_score: f64,
181    pub violations: Vec<String>,
182    pub recommendations: Vec<String>,
183    pub audit_entries: Vec<AuditEntry>,
184}
185
186/// Per-order compliance report produced by `ComplianceMonitor::check_order`.
187///
188/// Aggregates the pass/fail verdict of every registered rule against a single
189/// order; `overall_pass` is `true` only when every `rule_result` passed. An
190/// empty rule set yields `overall_pass = true` with no `rule_results`.
191#[derive(Debug, Clone)]
192pub struct ComplianceReport {
193    pub order_id: String,
194    pub overall_pass: bool,
195    pub rule_results: Vec<RuleResult>,
196    pub timestamp: u64,
197}
198
199/// Result of evaluating a single compliance rule against an order.
200#[derive(Debug, Clone)]
201pub struct RuleResult {
202    pub rule_id: String,
203    pub passed: bool,
204    pub message: String,
205}
206
207/// Error type returned by compliance-rule evaluation. Aliased to the library's
208/// general `FinancialError` so callers can handle all financial errors uniformly
209/// (the `FinancialError::ComplianceError` variant carries the compliance message).
210pub type ComplianceError = FinancialError;
211
212/// Financial library performance summary metrics
213#[derive(Debug, Clone)]
214pub struct FinancialPerformanceMetrics {
215    pub total_portfolios: u64,
216    pub average_return: f64,
217    pub average_volatility: f64,
218    pub average_sharpe_ratio: f64,
219    pub total_assets: f64,
220}
221
222/// Financial error types
223#[derive(Debug, Clone)]
224pub enum FinancialError {
225    ValidationError(String),
226    PortfolioError(String),
227    AssetError(String),
228    RiskError(String),
229    PricingError(String),
230    TradingError(String),
231    ComplianceError(String),
232    DataError(String),
233    /// The capability is not implemented yet — returned instead of a fabricated result.
234    NotImplemented(String),
235    /// The required input (return history, market data, defined limits) is not present.
236    InsufficientData(String),
237}
238
239impl std::fmt::Display for FinancialError {
240    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241        match self {
242            FinancialError::ValidationError(msg) => write!(f, "Validation error: {}", msg),
243            FinancialError::PortfolioError(msg) => write!(f, "Portfolio error: {}", msg),
244            FinancialError::AssetError(msg) => write!(f, "Asset error: {}", msg),
245            FinancialError::RiskError(msg) => write!(f, "Risk error: {}", msg),
246            FinancialError::PricingError(msg) => write!(f, "Pricing error: {}", msg),
247            FinancialError::TradingError(msg) => write!(f, "Trading error: {}", msg),
248            FinancialError::ComplianceError(msg) => write!(f, "Compliance error: {}", msg),
249            FinancialError::DataError(msg) => write!(f, "Data error: {}", msg),
250            FinancialError::NotImplemented(msg) => write!(f, "Not implemented yet: {}", msg),
251            FinancialError::InsufficientData(msg) => {
252                write!(f, "Required information not available: {}", msg)
253            }
254        }
255    }
256}
257
258impl std::error::Error for FinancialError {}