Skip to main content

qualia_core_db/specialized_libs/financial_modeling/
assets.rs

1use super::*;
2
3/// Asset manager
4pub struct AssetManager {
5    asset_catalog: AssetCatalog,
6    price_feeds: HashMap<String, PriceFeed>,
7    market_data: MarketData,
8    asset_validator: AssetValidator,
9    /// Per-asset price history cache (oldest first), populated by
10    /// `update_price_history` / `ingest_from_feed` and applied to `Asset`s via
11    /// `apply_to_asset`. The `AssetManager` does not own `Portfolio`/`Asset`
12    /// instances (those live in `PortfolioStorage`), so it keeps the histories it
13    /// ingests here until a caller asks to copy them onto an asset.
14    price_histories: HashMap<String, Vec<f64>>,
15}
16
17/// Asset catalog
18pub struct AssetCatalog {
19    assets: HashMap<String, AssetInfo>,
20    asset_classes: HashMap<String, AssetClass>,
21    asset_relationships: HashMap<String, Vec<AssetRelationship>>,
22}
23
24/// Asset information
25#[derive(Debug, Clone)]
26pub struct AssetInfo {
27    pub asset_id: String,
28    pub symbol: String,
29    pub name: String,
30    pub asset_type: AssetType,
31    pub exchange: String,
32    pub currency: String,
33    pub sector: Option<String>,
34    pub industry: Option<String>,
35    pub market_cap: Option<f64>,
36    pub description: String,
37}
38
39/// Asset class
40#[derive(Debug, Clone)]
41pub struct AssetClass {
42    pub class_id: String,
43    pub class_name: String,
44    pub class_type: AssetType,
45    pub characteristics: Vec<String>,
46    pub risk_level: RiskLevel,
47}
48
49/// Risk levels
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub enum RiskLevel {
52    Low,
53    Medium,
54    High,
55    VeryHigh,
56}
57
58/// Asset relationships
59#[derive(Debug, Clone)]
60pub struct AssetRelationship {
61    pub relationship_id: String,
62    pub source_asset: String,
63    pub target_asset: String,
64    pub relationship_type: AssetRelationshipType,
65    pub correlation: f64,
66}
67
68/// Asset relationship types
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70pub enum AssetRelationshipType {
71    Correlation,
72    Causation,
73    Substitution,
74    Complement,
75    Derivative,
76}
77
78/// Price feed
79#[derive(Debug, Clone)]
80pub struct PriceFeed {
81    pub feed_id: String,
82    pub feed_name: String,
83    pub feed_type: FeedType,
84    pub update_frequency: u64,
85    pub data_quality: DataQuality,
86    pub last_update: u64,
87    /// The asset this feed serves. Used to associate a feed with an asset so
88    /// `AssetManager::ingest_from_feed` can look it up by `asset_id`.
89    pub asset_id: String,
90    /// Cached price series (oldest first) fetched from the feed. When non-empty
91    /// this is used directly to populate an asset's `price_history`; when empty,
92    /// `ingest_from_feed` falls back to a deterministic generator seeded from
93    /// `feed_id` (there is no real network in this scaffold).
94    pub cached_prices: Vec<f64>,
95}
96
97/// Feed types
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub enum FeedType {
100    RealTime,
101    Delayed,
102    EndOfDay,
103    Historical,
104}
105
106/// Data quality
107#[derive(Debug, Clone)]
108pub struct DataQuality {
109    pub accuracy: f64,
110    pub completeness: f64,
111    pub timeliness: f64,
112    pub consistency: f64,
113}
114
115/// Market data
116pub struct MarketData {
117    price_data: HashMap<String, PriceData>,
118    volume_data: HashMap<String, VolumeData>,
119    technical_indicators: HashMap<String, TechnicalIndicators>,
120}
121
122/// Price data
123#[derive(Debug, Clone)]
124pub struct PriceData {
125    pub asset_id: String,
126    pub timestamp: u64,
127    pub open: f64,
128    pub high: f64,
129    pub low: f64,
130    pub close: f64,
131    pub adjusted_close: f64,
132    pub volume: u64,
133}
134
135/// Volume data
136#[derive(Debug, Clone)]
137pub struct VolumeData {
138    pub asset_id: String,
139    pub timestamp: u64,
140    pub volume: u64,
141    pub bid_volume: u64,
142    pub ask_volume: u64,
143}
144
145/// Technical indicators
146#[derive(Debug, Clone)]
147pub struct TechnicalIndicators {
148    pub asset_id: String,
149    pub timestamp: u64,
150    pub moving_averages: HashMap<String, f64>,
151    pub oscillators: HashMap<String, f64>,
152    pub volatility: HashMap<String, f64>,
153}
154
155/// Asset validator
156pub struct AssetValidator {
157    validation_rules: Vec<ValidationRule>,
158    compliance_checker: ComplianceChecker,
159    risk_assessor: RiskAssessor,
160}
161
162/// Validation rules
163#[derive(Debug, Clone)]
164pub struct ValidationRule {
165    pub rule_id: String,
166    pub rule_type: ValidationRuleType,
167    pub condition: String,
168    pub action: ValidationAction,
169}
170
171/// Validation rule types
172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
173pub enum ValidationRuleType {
174    Price,
175    Volume,
176    Liquidity,
177    MarketCap,
178    Regulatory,
179}
180
181/// Validation actions
182#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
183pub enum ValidationAction {
184    Accept,
185    Reject,
186    Flag,
187    Review,
188}
189
190/// Compliance checker
191pub struct ComplianceChecker {
192    compliance_rules: Vec<ComplianceRule>,
193    regulatory_frameworks: Vec<RegulatoryFramework>,
194    screening_lists: HashMap<String, ScreeningList>,
195}
196
197/// Compliance rules evaluated by the `ComplianceMonitor` rule engine.
198///
199/// Each rule is parameterised by numeric `parameters` (e.g. `max_position`,
200/// `margin_pct`, `kyc_required`) and, where a rule needs non-numeric payloads
201/// (e.g. the comma-separated `restricted_assets` list used by
202/// `TradingRestriction`), by `string_parameters`. The latter is kept separate
203/// from `parameters` so the former stays a clean `HashMap<String, f64>` as
204/// specified.
205#[derive(Debug, Clone)]
206pub struct ComplianceRule {
207    pub rule_id: String,
208    pub rule_type: ComplianceRuleType,
209    pub parameters: HashMap<String, f64>,
210    /// String-valued parameters — used by rules that need non-numeric payloads
211    /// (e.g. `restricted_assets` = `"AAPL,GOOG,MSFT"`).
212    pub string_parameters: HashMap<String, String>,
213    pub description: String,
214}
215
216/// Compliance rule types evaluated by the `ComplianceMonitor` rule engine.
217#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
218pub enum ComplianceRuleType {
219    /// Maximum aggregate position size for an asset (param `max_position`).
220    PositionLimit,
221    /// Know-Your-Customer verification (param `kyc_required` = 1.0).
222    KYC,
223    /// Anti-Money-Laundering clearance (param `kyc_required` = 1.0).
224    AML,
225    /// Margin coverage for the order (param `margin_pct` of order value).
226    MarginRequirement,
227    /// Asset-level trading ban (string param `restricted_assets`, comma-separated).
228    TradingRestriction,
229    /// User-defined rule with no built-in check (always passes by default).
230    Custom,
231}
232
233/// Compliance conditions
234#[derive(Debug, Clone)]
235pub struct ComplianceCondition {
236    pub condition_id: String,
237    pub field: String,
238    pub operator: ComparisonOperator,
239    pub value: ComplianceValue,
240}
241
242/// Compliance values
243#[derive(Debug, Clone)]
244pub enum ComplianceValue {
245    String(String),
246    Number(f64),
247    Boolean(bool),
248    Array(Vec<ComplianceValue>),
249}
250
251/// Comparison operators
252#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253pub enum ComparisonOperator {
254    Equals,
255    NotEquals,
256    GreaterThan,
257    LessThan,
258    Contains,
259    Matches,
260}
261
262/// Compliance actions
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264pub enum ComplianceAction {
265    Approve,
266    Reject,
267    Flag,
268    Escalate,
269    Report,
270}
271
272/// Regulatory frameworks
273#[derive(Debug, Clone)]
274pub struct RegulatoryFramework {
275    pub framework_id: String,
276    pub framework_name: String,
277    pub jurisdiction: String,
278    pub requirements: Vec<RegulatoryRequirement>,
279}
280
281/// Regulatory requirements
282#[derive(Debug, Clone)]
283pub struct RegulatoryRequirement {
284    pub requirement_id: String,
285    pub requirement_type: RequirementType,
286    pub description: String,
287    pub mandatory: bool,
288}
289
290/// Requirement types
291#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
292pub enum RequirementType {
293    Reporting,
294    Disclosure,
295    Capital,
296    Risk,
297    Operational,
298}
299
300/// Screening lists
301#[derive(Debug, Clone)]
302pub struct ScreeningList {
303    pub list_id: String,
304    pub list_name: String,
305    pub list_type: ScreeningListType,
306    pub entries: Vec<ScreeningEntry>,
307}
308
309/// Screening list types
310#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
311pub enum ScreeningListType {
312    Sanctions,
313    PEP,
314    WatchList,
315    DeniedPersons,
316}
317
318/// Screening entries
319#[derive(Debug, Clone)]
320pub struct ScreeningEntry {
321    pub entry_id: String,
322    pub name: String,
323    pub aliases: Vec<String>,
324    pub date_of_birth: Option<String>,
325    pub nationality: Option<String>,
326    pub reason: String,
327}
328
329impl AssetManager {
330    /// Construct a `AssetManager` with default field values.
331    pub fn new() -> Self {
332        Self {
333            asset_catalog: AssetCatalog::new(),
334            price_feeds: HashMap::new(),
335            market_data: MarketData::new(),
336            asset_validator: AssetValidator::new(),
337            price_histories: HashMap::new(),
338        }
339    }
340
341    /// Initialize `AssetManager`; `Ok` when ready.
342    pub fn initialize(&mut self) -> Result<(), FinancialError> {
343        self.asset_catalog.initialize()?;
344        self.asset_validator.initialize()?;
345        Ok(())
346    }
347
348    /// Register a price feed. The feed is keyed by its `asset_id` so that
349    /// `ingest_from_feed(asset_id)` can locate it. Re-registering a feed for the
350    /// same asset replaces the prior one.
351    pub fn register_price_feed(&mut self, feed: PriceFeed) {
352        self.price_feeds.insert(feed.asset_id.clone(), feed);
353    }
354
355    /// Directly set the cached price history (oldest first) for `asset_id`. This
356    /// is the manual entry point; `ingest_from_feed` is the feed-driven one. The
357    /// history is held in the manager's cache until `apply_to_asset` copies it
358    /// onto an `Asset`.
359    pub fn update_price_history(&mut self, asset_id: &str, prices: Vec<f64>) {
360        self.price_histories.insert(asset_id.to_string(), prices);
361    }
362
363    /// Look up the cached price history for `asset_id`, if any.
364    pub fn get_price_history(&self, asset_id: &str) -> Option<&Vec<f64>> {
365        self.price_histories.get(asset_id)
366    }
367
368    /// Fetch data from a registered price feed for `asset_id` and populate the manager's
369    /// price-history cache.
370    ///
371    /// Requires non-empty `cached_prices` on the registered feed. If no prices are cached,
372    /// fails closed with `DataError` rather than silently fabricating a synthetic market feed.
373    pub fn ingest_from_feed(&mut self, asset_id: &str) -> Result<(), FinancialError> {
374        let feed = self.price_feeds.get(asset_id).cloned().ok_or_else(|| {
375            FinancialError::DataError(format!("no price feed registered for asset '{}'", asset_id))
376        })?;
377
378        if feed.cached_prices.is_empty() {
379            return Err(FinancialError::DataError(format!(
380                "price feed '{}' for asset '{}' has no cached prices and real network feed transport is not configured (fails closed)",
381                feed.feed_id, asset_id
382            )));
383        }
384
385        self.price_histories.insert(asset_id.to_string(), feed.cached_prices);
386        Ok(())
387    }
388
389    /// Copy the manager's cached price history for `asset.asset_id` onto the
390    /// asset's `price_history`, and refresh `current_price`/`market_value` from
391    /// the last price. No-op when no history is cached for the asset.
392    pub fn apply_to_asset(&self, asset: &mut Asset) {
393        if let Some(prices) = self.price_histories.get(&asset.asset_id) {
394            asset.price_history = prices.clone();
395            if let Some(&last) = prices.last() {
396                asset.current_price = last;
397                asset.market_value = asset.quantity * last;
398            }
399        }
400    }
401
402    /// The `market_data` component.
403    pub fn market_data(&self) -> &MarketData {
404        &self.market_data
405    }
406
407    /// The `market_data` component (mutable).
408    pub fn market_data_mut(&mut self) -> &mut MarketData {
409        &mut self.market_data
410    }
411}
412
413/// Generate a deterministic price series (oldest first) from a seed string.
414/// Uses a simple xorshift LCG seeded by an FNV-1a hash of `seed`, so the same
415/// feed id always produces the same history (reproducible, no fabrication of
416/// "real" market data). The series oscillates around a 100.0 baseline.
417pub fn deterministic_price_series(seed: &str, len: usize) -> Vec<f64> {
418    // FNV-1a hash of the seed string → u64 state.
419    let mut state: u64 = 0xcbf2_9ce4_8422_2325;
420    for &b in seed.as_bytes() {
421        state ^= b as u64;
422        state = state.wrapping_mul(0x1000_0000_01b3);
423    }
424    if state == 0 {
425        state = 0x9e37_79b9_7f4a_7c15;
426    }
427
428    let mut prices = Vec::with_capacity(len);
429    let mut price = 100.0;
430    for _ in 0..len {
431        // xorshift64
432        state ^= state << 13;
433        state ^= state >> 7;
434        state ^= state << 17;
435        // map to a small step in [-1.5, +1.5)
436        let step = ((state >> 33) as f64) / (i32::MAX as f64) * 1.5;
437        price = (price + step).max(1.0);
438        prices.push(price);
439    }
440    prices
441}
442
443impl AssetCatalog {
444    /// Construct a `AssetCatalog` with default field values.
445    pub fn new() -> Self {
446        Self {
447            assets: HashMap::new(),
448            asset_classes: HashMap::new(),
449            asset_relationships: HashMap::new(),
450        }
451    }
452
453    /// Register an `AssetInfo` in the catalog, keyed by its `asset_id`. Re-registering
454    /// an asset with the same id replaces the prior entry.
455    pub fn register_asset(&mut self, asset: AssetInfo) {
456        self.assets.insert(asset.asset_id.clone(), asset);
457    }
458
459    /// Look up an asset by id.
460    pub fn get_asset(&self, asset_id: &str) -> Option<&AssetInfo> {
461        self.assets.get(asset_id)
462    }
463
464    // ----- Asset relationship tracking ----------------------------------------
465
466    /// Add a relationship between two assets. The relationship is stored under the
467    /// `source_asset` id (so `get_relationships(source)` returns it). The
468    /// `source_asset`/`target_asset` fields on `relationship` are authoritative —
469    /// the `source_asset`/`target_asset` arguments here are used only to key the
470    /// storage and are expected to match the relationship's own fields.
471    pub fn add_relationship(
472        &mut self,
473        source_asset: &str,
474        target_asset: &str,
475        relationship: AssetRelationship,
476    ) {
477        let _ = target_asset; // keyed by source; target recorded on the relationship
478        self.asset_relationships
479            .entry(source_asset.to_string())
480            .or_default()
481            .push(relationship);
482    }
483
484    /// Get all relationships for which `asset_id` is the source asset.
485    pub fn get_relationships(&self, asset_id: &str) -> Vec<&AssetRelationship> {
486        self.asset_relationships
487            .get(asset_id)
488            .map(|rels| rels.iter().collect())
489            .unwrap_or_default()
490    }
491
492    /// Get all asset ids related to `asset_id` (as the target of a relationship
493    /// originating from `asset_id`). Duplicates are preserved in insertion order.
494    pub fn get_related_assets(&self, asset_id: &str) -> Vec<String> {
495        self.asset_relationships
496            .get(asset_id)
497            .map(|rels| rels.iter().map(|r| r.target_asset.clone()).collect())
498            .unwrap_or_default()
499    }
500
501    /// Total number of relationships tracked across all source assets.
502    pub fn relationship_count(&self) -> usize {
503        self.asset_relationships
504            .values()
505            .map(|rels| rels.len())
506            .sum()
507    }
508
509    // ----- Asset classification system ----------------------------------------
510
511    /// Register an `AssetClass` keyed by `class_id`. Re-registering a class with the
512    /// same id replaces the prior entry.
513    pub fn register_asset_class(&mut self, class_id: &str, asset_class: AssetClass) {
514        self.asset_classes.insert(class_id.to_string(), asset_class);
515    }
516
517    /// Classify an asset into a class. Verifies that both the asset and the class
518    /// are registered first; returns `AssetError` otherwise. The classification is
519    /// recorded by adding the asset's id to the class's `characteristics` list
520    /// (the catalog has no separate membership map, so the class's own fields carry
521    /// membership). Returns `Ok(())` when the asset is already a member (idempotent).
522    pub fn classify_asset(&mut self, asset_id: &str, class_id: &str) -> Result<(), FinancialError> {
523        if !self.assets.contains_key(asset_id) {
524            return Err(FinancialError::AssetError(format!(
525                "asset '{}' is not registered in the catalog",
526                asset_id
527            )));
528        }
529        let class = self.asset_classes.get_mut(class_id).ok_or_else(|| {
530            FinancialError::AssetError(format!("asset class '{}' is not registered", class_id))
531        })?;
532        if !class.characteristics.iter().any(|c| c == asset_id) {
533            class.characteristics.push(asset_id.to_string());
534        }
535        Ok(())
536    }
537
538    /// Get an asset class by id.
539    pub fn get_asset_class(&self, class_id: &str) -> Option<&AssetClass> {
540        self.asset_classes.get(class_id)
541    }
542
543    /// Get all asset ids that are members of `class_id`. Membership is recorded in
544    /// the class's `characteristics` list by `classify_asset`; entries that were not
545    /// inserted by `classify_asset` (i.e. pre-existing descriptive characteristics)
546    /// are filtered out against the registered asset set so only real asset ids are
547    /// returned.
548    pub fn get_assets_by_class(&self, class_id: &str) -> Vec<String> {
549        match self.asset_classes.get(class_id) {
550            Some(class) => class
551                .characteristics
552                .iter()
553                .filter(|c| self.assets.contains_key(*c))
554                .cloned()
555                .collect(),
556            None => Vec::new(),
557        }
558    }
559
560    /// List all registered asset class ids.
561    pub fn list_asset_classes(&self) -> Vec<String> {
562        self.asset_classes.keys().cloned().collect()
563    }
564
565    /// Populate the catalog with the standard set of asset classes:
566    /// Equity, FixedIncome, Commodity, RealEstate, Cash, Derivative, Cryptocurrency.
567    /// Each is keyed by a lowercase id and tagged with its corresponding `AssetType`.
568    pub fn initialize(&mut self) -> Result<(), FinancialError> {
569        let standards: &[(&str, &str, AssetType, RiskLevel, &[&str])] = &[
570            (
571                "equity",
572                "Equity",
573                AssetType::Stock,
574                RiskLevel::Medium,
575                &["Stocks", "Shares"],
576            ),
577            (
578                "fixed_income",
579                "Fixed Income",
580                AssetType::Bond,
581                RiskLevel::Low,
582                &["Bonds", "Debt instruments"],
583            ),
584            (
585                "commodity",
586                "Commodity",
587                AssetType::Commodity,
588                RiskLevel::High,
589                &["Physical goods", "Futures"],
590            ),
591            (
592                "real_estate",
593                "Real Estate",
594                AssetType::RealEstate,
595                RiskLevel::Medium,
596                &["Property", "Land"],
597            ),
598            (
599                "cash",
600                "Cash",
601                AssetType::Currency,
602                RiskLevel::Low,
603                &["Currency", "Money market"],
604            ),
605            (
606                "derivative",
607                "Derivative",
608                AssetType::Derivative,
609                RiskLevel::VeryHigh,
610                &["Options", "Futures", "Swaps"],
611            ),
612            (
613                "cryptocurrency",
614                "Cryptocurrency",
615                AssetType::Cryptocurrency,
616                RiskLevel::VeryHigh,
617                &["Digital assets", "Tokens"],
618            ),
619        ];
620        for (id, name, ty, risk, chars) in standards {
621            self.register_asset_class(
622                id,
623                AssetClass {
624                    class_id: id.to_string(),
625                    class_name: name.to_string(),
626                    class_type: ty.clone(),
627                    characteristics: chars.iter().map(|s| s.to_string()).collect(),
628                    risk_level: risk.clone(),
629                },
630            );
631        }
632        Ok(())
633    }
634}
635
636impl MarketData {
637    /// Construct a `MarketData` with default field values.
638    pub fn new() -> Self {
639        Self {
640            price_data: HashMap::new(),
641            volume_data: HashMap::new(),
642            technical_indicators: HashMap::new(),
643        }
644    }
645
646    /// Copy cached price data from `price_data` into each asset's `price_history`.
647    /// For every asset in `assets` that has a `PriceData` entry (keyed by
648    /// `asset_id`), the asset's `price_history` is replaced with the cached
649    /// close/adjusted-close series. Because `price_data` holds a single
650    /// `PriceData` per asset (the latest bar), this yields a one-point history;
651    /// callers needing a multi-point series for risk computation should use
652    /// `AssetManager::update_price_history` / `ingest_from_feed` instead.
653    pub fn sync_to_assets(&self, assets: &mut HashMap<String, Asset>) {
654        for asset in assets.values_mut() {
655            if let Some(pd) = self.price_data.get(&asset.asset_id) {
656                // Prefer adjusted_close (split/dividend-adjusted) when present,
657                // else fall back to the raw close.
658                let px = if pd.adjusted_close != 0.0 {
659                    pd.adjusted_close
660                } else {
661                    pd.close
662                };
663                asset.price_history = vec![px];
664                asset.current_price = px;
665                asset.market_value = asset.quantity * px;
666            }
667        }
668    }
669
670    /// Insert/replace a `PriceData` entry (keyed by `asset_id`). Convenience for
671    /// tests and callers that populate market data before syncing.
672    pub fn upsert_price_data(&mut self, data: PriceData) {
673        self.price_data.insert(data.asset_id.clone(), data);
674    }
675
676    /// Insert or replace `volume_data` keyed by `asset_id`.
677    pub fn upsert_volume_data(&mut self, data: VolumeData) {
678        self.volume_data.insert(data.asset_id.clone(), data);
679    }
680
681    /// Look up `volume_data` by id; `None`/`Err` when absent.
682    pub fn get_volume_data(&self, asset_id: &str) -> Option<&VolumeData> {
683        self.volume_data.get(asset_id)
684    }
685
686    /// Insert or replace `technical_indicators` keyed by `asset_id`.
687    pub fn upsert_technical_indicators(&mut self, indicators: TechnicalIndicators) {
688        self.technical_indicators
689            .insert(indicators.asset_id.clone(), indicators);
690    }
691
692    /// Look up `technical_indicators` by id; `None`/`Err` when absent.
693    pub fn get_technical_indicators(&self, asset_id: &str) -> Option<&TechnicalIndicators> {
694        self.technical_indicators.get(asset_id)
695    }
696}
697
698impl AssetValidator {
699    /// Construct a `AssetValidator` with default field values.
700    pub fn new() -> Self {
701        Self {
702            validation_rules: Vec::new(),
703            compliance_checker: ComplianceChecker::new(),
704            risk_assessor: RiskAssessor::new(),
705        }
706    }
707
708    /// Initialize `AssetValidator`; `Ok` when ready.
709    pub fn initialize(&mut self) -> Result<(), FinancialError> {
710        self.compliance_checker.initialize()?;
711        self.risk_assessor.initialize()?;
712        Ok(())
713    }
714
715    /// Add `validation_rule` to the `AssetValidator`.
716    pub fn add_validation_rule(&mut self, rule: ValidationRule) {
717        self.validation_rules.push(rule);
718    }
719
720    /// Ids of every registered `validation_rule`.
721    pub fn list_validation_rules(&self) -> &[ValidationRule] {
722        &self.validation_rules
723    }
724
725    /// Number of registered `validation rules`.
726    pub fn validation_rule_count(&self) -> usize {
727        self.validation_rules.len()
728    }
729}
730
731impl ComplianceChecker {
732    /// Construct a `ComplianceChecker` with default field values.
733    pub fn new() -> Self {
734        Self {
735            compliance_rules: Vec::new(),
736            regulatory_frameworks: Vec::new(),
737            screening_lists: HashMap::new(),
738        }
739    }
740
741    /// Initialize `ComplianceChecker`; `Ok` when ready.
742    pub fn initialize(&mut self) -> Result<(), FinancialError> {
743        Ok(())
744    }
745
746    /// Add `compliance_rule` to the `ComplianceChecker`.
747    pub fn add_compliance_rule(&mut self, rule: ComplianceRule) {
748        self.compliance_rules.push(rule);
749    }
750
751    /// Ids of every registered `compliance_rule`.
752    pub fn list_compliance_rules(&self) -> &[ComplianceRule] {
753        &self.compliance_rules
754    }
755
756    /// Add `regulatory_framework` to the `ComplianceChecker`.
757    pub fn add_regulatory_framework(&mut self, framework: RegulatoryFramework) {
758        self.regulatory_frameworks.push(framework);
759    }
760
761    /// Ids of every registered `regulatory_framework`.
762    pub fn list_regulatory_frameworks(&self) -> &[RegulatoryFramework] {
763        &self.regulatory_frameworks
764    }
765
766    /// Add `screening_list` to the `ComplianceChecker`.
767    pub fn add_screening_list(&mut self, list: ScreeningList) {
768        self.screening_lists.insert(list.list_id.clone(), list);
769    }
770
771    /// Look up `screening_list` by id; `None`/`Err` when absent.
772    pub fn get_screening_list(&self, list_id: &str) -> Option<&ScreeningList> {
773        self.screening_lists.get(list_id)
774    }
775
776    /// Ids of every registered `screening_list`.
777    pub fn list_screening_lists(&self) -> Vec<String> {
778        self.screening_lists.keys().cloned().collect()
779    }
780}
781
782impl ComplianceRule {
783    /// Human-readable name for the rule type, for audit logging.
784    pub(super) fn rule_type_as_str(&self) -> &'static str {
785        match self.rule_type {
786            ComplianceRuleType::PositionLimit => "PositionLimit",
787            ComplianceRuleType::KYC => "KYC",
788            ComplianceRuleType::AML => "AML",
789            ComplianceRuleType::MarginRequirement => "MarginRequirement",
790            ComplianceRuleType::TradingRestriction => "TradingRestriction",
791            ComplianceRuleType::Custom => "Custom",
792        }
793    }
794}
795
796impl AssetInfo {
797    /// Construct a `AssetInfo` with default field values.
798    pub fn new() -> Self {
799        Self {
800            asset_id: "asset_1".to_string(),
801            symbol: "AAPL".to_string(),
802            name: "Apple Inc.".to_string(),
803            asset_type: AssetType::Stock,
804            exchange: "NASDAQ".to_string(),
805            currency: "USD".to_string(),
806            sector: Some("Technology".to_string()),
807            industry: Some("Consumer Electronics".to_string()),
808            market_cap: Some(3000000000000.0),
809            description: "Apple Inc. is a technology company".to_string(),
810        }
811    }
812}
813
814impl AssetClass {
815    /// Construct a `AssetClass` with default field values.
816    pub fn new() -> Self {
817        Self {
818            class_id: "class_1".to_string(),
819            class_name: "US Equities".to_string(),
820            class_type: AssetType::Stock,
821            characteristics: vec!["US listed".to_string(), "Large cap".to_string()],
822            risk_level: RiskLevel::Medium,
823        }
824    }
825}
826
827impl AssetRelationship {
828    /// Construct a `AssetRelationship` with default field values.
829    pub fn new() -> Self {
830        Self {
831            relationship_id: "rel_1".to_string(),
832            source_asset: "AAPL".to_string(),
833            target_asset: "MSFT".to_string(),
834            relationship_type: AssetRelationshipType::Correlation,
835            correlation: 0.7,
836        }
837    }
838}
839
840impl PriceFeed {
841    /// Construct a `PriceFeed` with default field values.
842    pub fn new() -> Self {
843        Self {
844            feed_id: "feed_1".to_string(),
845            feed_name: "Real-time feed".to_string(),
846            feed_type: FeedType::RealTime,
847            update_frequency: 1,
848            data_quality: DataQuality::new(),
849            last_update: 0,
850            asset_id: "asset_1".to_string(),
851            cached_prices: Vec::new(),
852        }
853    }
854}
855
856impl DataQuality {
857    /// Construct a `DataQuality` with default field values.
858    pub fn new() -> Self {
859        Self {
860            // not measured (scaffold defaults; no data-quality assessment is performed)
861            accuracy: 0.0,
862            completeness: 0.0,
863            timeliness: 0.0,
864            consistency: 0.0,
865        }
866    }
867}
868
869impl PriceData {
870    /// Construct a `PriceData` with default field values.
871    pub fn new() -> Self {
872        Self {
873            asset_id: "asset_1".to_string(),
874            timestamp: 0,
875            open: 150.0,
876            high: 155.0,
877            low: 149.0,
878            close: 154.0,
879            adjusted_close: 154.0,
880            volume: 1000000,
881        }
882    }
883}
884
885impl VolumeData {
886    /// Construct a `VolumeData` with default field values.
887    pub fn new() -> Self {
888        Self {
889            asset_id: "asset_1".to_string(),
890            timestamp: 0,
891            volume: 1000000,
892            bid_volume: 500000,
893            ask_volume: 500000,
894        }
895    }
896}
897
898impl TechnicalIndicators {
899    /// Construct a `TechnicalIndicators` with default field values.
900    pub fn new() -> Self {
901        Self {
902            asset_id: "asset_1".to_string(),
903            timestamp: 0,
904            moving_averages: HashMap::new(),
905            oscillators: HashMap::new(),
906            volatility: HashMap::new(),
907        }
908    }
909}
910
911impl ValidationRule {
912    /// Construct a `ValidationRule` with default field values.
913    pub fn new() -> Self {
914        Self {
915            rule_id: "rule_1".to_string(),
916            rule_type: ValidationRuleType::Price,
917            condition: "price > 0".to_string(),
918            action: ValidationAction::Accept,
919        }
920    }
921}
922
923impl ComplianceCondition {
924    /// Construct a `ComplianceCondition` with default field values.
925    pub fn new() -> Self {
926        Self {
927            condition_id: "cond_1".to_string(),
928            field: "price".to_string(),
929            operator: ComparisonOperator::GreaterThan,
930            value: ComplianceValue::Number(0.0),
931        }
932    }
933}
934
935impl ComplianceRule {
936    /// Construct a `ComplianceRule` with default field values.
937    pub fn new() -> Self {
938        Self {
939            rule_id: "rule_1".to_string(),
940            rule_type: ComplianceRuleType::PositionLimit,
941            parameters: HashMap::from([("max_position".to_string(), 1000.0)]),
942            string_parameters: HashMap::new(),
943            description: "Default position-limit rule".to_string(),
944        }
945    }
946}
947
948impl RegulatoryFramework {
949    /// Construct a `RegulatoryFramework` with default field values.
950    pub fn new() -> Self {
951        Self {
952            framework_id: "framework_1".to_string(),
953            framework_name: "SEC".to_string(),
954            jurisdiction: "US".to_string(),
955            requirements: vec![RegulatoryRequirement::new()],
956        }
957    }
958}
959
960impl RegulatoryRequirement {
961    /// Construct a `RegulatoryRequirement` with default field values.
962    pub fn new() -> Self {
963        Self {
964            requirement_id: "req_1".to_string(),
965            requirement_type: RequirementType::Reporting,
966            description: "Must report trades".to_string(),
967            mandatory: true,
968        }
969    }
970}
971
972impl ScreeningList {
973    /// Construct a `ScreeningList` with default field values.
974    pub fn new() -> Self {
975        Self {
976            list_id: "list_1".to_string(),
977            list_name: "Sanctions list".to_string(),
978            list_type: ScreeningListType::Sanctions,
979            entries: vec![ScreeningEntry::new()],
980        }
981    }
982}
983
984impl ScreeningEntry {
985    /// Construct a `ScreeningEntry` with default field values.
986    pub fn new() -> Self {
987        Self {
988            entry_id: "entry_1".to_string(),
989            name: "Test Entity".to_string(),
990            aliases: vec!["Alias 1".to_string()],
991            date_of_birth: Some("1980-01-01".to_string()),
992            nationality: Some("US".to_string()),
993            reason: "Test reason".to_string(),
994        }
995    }
996}