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