1use super::*;
2
3pub struct AssetManager {
5 asset_catalog: AssetCatalog,
6 price_feeds: HashMap<String, PriceFeed>,
7 market_data: MarketData,
8 asset_validator: AssetValidator,
9 price_histories: HashMap<String, Vec<f64>>,
15}
16
17pub struct AssetCatalog {
19 assets: HashMap<String, AssetInfo>,
20 asset_classes: HashMap<String, AssetClass>,
21 asset_relationships: HashMap<String, Vec<AssetRelationship>>,
22}
23
24#[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#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub enum RiskLevel {
52 Low,
53 Medium,
54 High,
55 VeryHigh,
56}
57
58#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70pub enum AssetRelationshipType {
71 Correlation,
72 Causation,
73 Substitution,
74 Complement,
75 Derivative,
76}
77
78#[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 pub asset_id: String,
90 pub cached_prices: Vec<f64>,
95}
96
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub enum FeedType {
100 RealTime,
101 Delayed,
102 EndOfDay,
103 Historical,
104}
105
106#[derive(Debug, Clone)]
108pub struct DataQuality {
109 pub accuracy: f64,
110 pub completeness: f64,
111 pub timeliness: f64,
112 pub consistency: f64,
113}
114
115pub struct MarketData {
117 price_data: HashMap<String, PriceData>,
118 volume_data: HashMap<String, VolumeData>,
119 technical_indicators: HashMap<String, TechnicalIndicators>,
120}
121
122#[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#[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#[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
155pub struct AssetValidator {
157 validation_rules: Vec<ValidationRule>,
158 compliance_checker: ComplianceChecker,
159 risk_assessor: RiskAssessor,
160}
161
162#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
173pub enum ValidationRuleType {
174 Price,
175 Volume,
176 Liquidity,
177 MarketCap,
178 Regulatory,
179}
180
181#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
183pub enum ValidationAction {
184 Accept,
185 Reject,
186 Flag,
187 Review,
188}
189
190pub struct ComplianceChecker {
192 compliance_rules: Vec<ComplianceRule>,
193 regulatory_frameworks: Vec<RegulatoryFramework>,
194 screening_lists: HashMap<String, ScreeningList>,
195}
196
197#[derive(Debug, Clone)]
206pub struct ComplianceRule {
207 pub rule_id: String,
208 pub rule_type: ComplianceRuleType,
209 pub parameters: HashMap<String, f64>,
210 pub string_parameters: HashMap<String, String>,
213 pub description: String,
214}
215
216#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
218pub enum ComplianceRuleType {
219 PositionLimit,
221 KYC,
223 AML,
225 MarginRequirement,
227 TradingRestriction,
229 Custom,
231}
232
233#[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#[derive(Debug, Clone)]
244pub enum ComplianceValue {
245 String(String),
246 Number(f64),
247 Boolean(bool),
248 Array(Vec<ComplianceValue>),
249}
250
251#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253pub enum ComparisonOperator {
254 Equals,
255 NotEquals,
256 GreaterThan,
257 LessThan,
258 Contains,
259 Matches,
260}
261
262#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264pub enum ComplianceAction {
265 Approve,
266 Reject,
267 Flag,
268 Escalate,
269 Report,
270}
271
272#[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#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
292pub enum RequirementType {
293 Reporting,
294 Disclosure,
295 Capital,
296 Risk,
297 Operational,
298}
299
300#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
311pub enum ScreeningListType {
312 Sanctions,
313 PEP,
314 WatchList,
315 DeniedPersons,
316}
317
318#[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 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 pub fn initialize(&mut self) -> Result<(), FinancialError> {
343 self.asset_catalog.initialize()?;
344 self.asset_validator.initialize()?;
345 Ok(())
346 }
347
348 pub fn register_price_feed(&mut self, feed: PriceFeed) {
352 self.price_feeds.insert(feed.asset_id.clone(), feed);
353 }
354
355 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 pub fn get_price_history(&self, asset_id: &str) -> Option<&Vec<f64>> {
365 self.price_histories.get(asset_id)
366 }
367
368 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 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 pub fn market_data(&self) -> &MarketData {
404 &self.market_data
405 }
406
407 pub fn market_data_mut(&mut self) -> &mut MarketData {
409 &mut self.market_data
410 }
411}
412
413pub fn deterministic_price_series(seed: &str, len: usize) -> Vec<f64> {
418 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 state ^= state << 13;
433 state ^= state >> 7;
434 state ^= state << 17;
435 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 pub fn new() -> Self {
446 Self {
447 assets: HashMap::new(),
448 asset_classes: HashMap::new(),
449 asset_relationships: HashMap::new(),
450 }
451 }
452
453 pub fn register_asset(&mut self, asset: AssetInfo) {
456 self.assets.insert(asset.asset_id.clone(), asset);
457 }
458
459 pub fn get_asset(&self, asset_id: &str) -> Option<&AssetInfo> {
461 self.assets.get(asset_id)
462 }
463
464 pub fn add_relationship(
472 &mut self,
473 source_asset: &str,
474 target_asset: &str,
475 relationship: AssetRelationship,
476 ) {
477 let _ = target_asset; self.asset_relationships
479 .entry(source_asset.to_string())
480 .or_default()
481 .push(relationship);
482 }
483
484 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 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 pub fn relationship_count(&self) -> usize {
503 self.asset_relationships
504 .values()
505 .map(|rels| rels.len())
506 .sum()
507 }
508
509 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 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 pub fn get_asset_class(&self, class_id: &str) -> Option<&AssetClass> {
540 self.asset_classes.get(class_id)
541 }
542
543 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 pub fn list_asset_classes(&self) -> Vec<String> {
562 self.asset_classes.keys().cloned().collect()
563 }
564
565 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 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 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 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 pub fn upsert_price_data(&mut self, data: PriceData) {
673 self.price_data.insert(data.asset_id.clone(), data);
674 }
675
676 pub fn upsert_volume_data(&mut self, data: VolumeData) {
678 self.volume_data.insert(data.asset_id.clone(), data);
679 }
680
681 pub fn get_volume_data(&self, asset_id: &str) -> Option<&VolumeData> {
683 self.volume_data.get(asset_id)
684 }
685
686 pub fn upsert_technical_indicators(&mut self, indicators: TechnicalIndicators) {
688 self.technical_indicators
689 .insert(indicators.asset_id.clone(), indicators);
690 }
691
692 pub fn get_technical_indicators(&self, asset_id: &str) -> Option<&TechnicalIndicators> {
694 self.technical_indicators.get(asset_id)
695 }
696}
697
698impl AssetValidator {
699 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 pub fn initialize(&mut self) -> Result<(), FinancialError> {
710 self.compliance_checker.initialize()?;
711 self.risk_assessor.initialize()?;
712 Ok(())
713 }
714
715 pub fn add_validation_rule(&mut self, rule: ValidationRule) {
717 self.validation_rules.push(rule);
718 }
719
720 pub fn list_validation_rules(&self) -> &[ValidationRule] {
722 &self.validation_rules
723 }
724
725 pub fn validation_rule_count(&self) -> usize {
727 self.validation_rules.len()
728 }
729}
730
731impl ComplianceChecker {
732 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 pub fn initialize(&mut self) -> Result<(), FinancialError> {
743 Ok(())
744 }
745
746 pub fn add_compliance_rule(&mut self, rule: ComplianceRule) {
748 self.compliance_rules.push(rule);
749 }
750
751 pub fn list_compliance_rules(&self) -> &[ComplianceRule] {
753 &self.compliance_rules
754 }
755
756 pub fn add_regulatory_framework(&mut self, framework: RegulatoryFramework) {
758 self.regulatory_frameworks.push(framework);
759 }
760
761 pub fn list_regulatory_frameworks(&self) -> &[RegulatoryFramework] {
763 &self.regulatory_frameworks
764 }
765
766 pub fn add_screening_list(&mut self, list: ScreeningList) {
768 self.screening_lists.insert(list.list_id.clone(), list);
769 }
770
771 pub fn get_screening_list(&self, list_id: &str) -> Option<&ScreeningList> {
773 self.screening_lists.get(list_id)
774 }
775
776 pub fn list_screening_lists(&self) -> Vec<String> {
778 self.screening_lists.keys().cloned().collect()
779 }
780}
781
782impl ComplianceRule {
783 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 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 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 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 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 pub fn new() -> Self {
859 Self {
860 accuracy: 0.0,
862 completeness: 0.0,
863 timeliness: 0.0,
864 consistency: 0.0,
865 }
866 }
867}
868
869impl PriceData {
870 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 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 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 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 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 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 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 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 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 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}