1use super::*;
2
3pub struct RebalancingEngine {
5 rebalancing_strategies: HashMap<String, RebalancingStrategy>,
6 optimization_engine: OptimizationEngine,
7 execution_engine: ExecutionEngine,
8}
9
10#[derive(Debug, Clone)]
12pub struct RebalancingStrategy {
13 pub strategy_id: String,
14 pub strategy_name: String,
15 pub strategy_type: RebalancingStrategyType,
16 pub parameters: RebalancingParameters,
17 pub constraints: RebalancingConstraints,
18 pub target_weights: HashMap<String, f64>,
22}
23
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct RebalanceTrade {
27 pub asset_id: String,
29 pub action: TradeAction,
31 pub quantity: f64,
33 pub target_weight: f64,
35}
36
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub enum TradeAction {
40 Buy,
41 Sell,
42}
43
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
46pub enum RebalancingStrategyType {
47 TimeBased,
48 ThresholdBased,
49 OptimizationBased,
50 Hybrid,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct RebalancingParameters {
56 pub rebalance_frequency: u32,
57 pub deviation_threshold: f64,
58 pub min_trade_size: f64,
59 pub max_trade_size: f64,
60 pub transaction_costs: TransactionCosts,
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct TransactionCosts {
66 pub commission_rate: f64,
67 pub spread_cost: f64,
68 pub market_impact: f64,
69 pub tax_rate: f64,
70}
71
72#[derive(Debug, Clone)]
74pub struct RebalancingConstraints {
75 pub asset_class_limits: HashMap<String, f64>,
76 pub sector_limits: HashMap<String, f64>,
77 pub liquidity_constraints: LiquidityConstraints,
78 pub regulatory_constraints: RegulatoryConstraints,
79}
80
81#[derive(Debug, Clone)]
83pub struct LiquidityConstraints {
84 pub max_daily_volume: f64,
85 pub min_liquidity_score: f64,
86 pub liquidity_buffer: f64,
87}
88
89#[derive(Debug, Clone)]
91pub struct RegulatoryConstraints {
92 pub concentration_limits: HashMap<String, f64>,
93 pub reporting_requirements: Vec<String>,
94 pub compliance_deadlines: Vec<u64>,
95}
96
97pub struct OptimizationEngine {
99 optimization_algorithms: HashMap<String, OptimizationAlgorithm>,
100 objective_functions: HashMap<String, ObjectiveFunction>,
101 constraints: Vec<OptimizationConstraint>,
102}
103
104#[derive(Debug, Clone)]
106pub struct OptimizationAlgorithm {
107 pub algorithm_id: String,
108 pub algorithm_type: OptimizationAlgorithmType,
109 pub parameters: OptimizationParameters,
110}
111
112#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub enum OptimizationAlgorithmType {
115 MeanVariance,
116 BlackLitterman,
117 RiskParity,
118 EqualWeight,
119 Custom,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct OptimizationParameters {
125 pub risk_aversion: f64,
126 pub expected_returns: Vec<f64>,
127 pub covariance_matrix: Vec<Vec<f64>>,
128 pub constraints: Vec<OptimizationConstraint>,
129}
130
131#[derive(Debug, Clone)]
133pub struct ObjectiveFunction {
134 pub function_id: String,
135 pub function_type: ObjectiveFunctionType,
136 pub parameters: HashMap<String, f64>,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub enum ObjectiveFunctionType {
142 MaximizeReturn,
143 MinimizeRisk,
144 MaximizeSharpe,
145 MinimizeDrawdown,
146 Custom,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct OptimizationConstraint {
152 pub constraint_id: String,
153 pub constraint_type: ConstraintType,
154 pub bounds: ConstraintBounds,
155}
156
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub enum ConstraintType {
160 Equality,
161 Inequality,
162 Bound,
163 Linear,
164 Nonlinear,
165}
166
167#[derive(Debug, Clone, Serialize, Deserialize)]
169pub struct ConstraintBounds {
170 pub lower_bound: f64,
171 pub upper_bound: f64,
172}
173
174impl RebalancingEngine {
175 pub fn new() -> Self {
177 Self {
178 rebalancing_strategies: HashMap::new(),
179 optimization_engine: OptimizationEngine::new(),
180 execution_engine: ExecutionEngine::new(),
181 }
182 }
183
184 pub fn initialize(&mut self) -> Result<(), FinancialError> {
186 self.optimization_engine.initialize()?;
187 self.execution_engine.initialize()?;
188 Ok(())
189 }
190
191 pub fn register_strategy(&mut self, strategy: RebalancingStrategy) {
193 self.rebalancing_strategies
194 .insert(strategy.strategy_id.clone(), strategy);
195 }
196
197 pub fn get_strategy(&self, strategy_id: &str) -> Option<&RebalancingStrategy> {
199 self.rebalancing_strategies.get(strategy_id)
200 }
201
202 pub fn calculate_drift(portfolio: &Portfolio) -> HashMap<String, f64> {
207 let total: f64 = portfolio.assets.iter().map(|a| a.market_value).sum();
208 let mut weights = HashMap::new();
209 if !(total > 0.0) {
210 return weights;
211 }
212 for asset in &portfolio.assets {
213 weights.insert(asset.asset_id.clone(), asset.market_value / total);
214 }
215 weights
216 }
217
218 pub fn rebalance(
227 &self,
228 portfolio: &mut Portfolio,
229 strategy: &RebalancingStrategy,
230 ) -> Result<Vec<RebalanceTrade>, FinancialError> {
231 let total_value: f64 = portfolio.assets.iter().map(|a| a.market_value).sum();
232 if !(total_value > 0.0) {
233 return Err(FinancialError::PortfolioError(
234 "cannot rebalance: total portfolio market value is not positive".to_string(),
235 ));
236 }
237
238 let current_weights = Self::calculate_drift(portfolio);
239 let threshold = strategy.parameters.deviation_threshold;
240 let mut trades = Vec::new();
241
242 for asset in &portfolio.assets {
243 let current_weight = current_weights.get(&asset.asset_id).copied().unwrap_or(0.0);
244 let target_weight = strategy
245 .target_weights
246 .get(&asset.asset_id)
247 .copied()
248 .unwrap_or(0.0);
249 let drift = current_weight - target_weight;
250
251 if drift.abs() > threshold {
252 if asset.current_price <= 0.0 {
253 return Err(FinancialError::AssetError(format!(
254 "asset '{}' has non-positive current price; cannot size a trade",
255 asset.asset_id
256 )));
257 }
258 let target_value = target_weight * total_value;
259 let value_diff = target_value - asset.market_value;
260 let quantity = value_diff / asset.current_price;
261 let action = if quantity >= 0.0 {
262 TradeAction::Buy
263 } else {
264 TradeAction::Sell
265 };
266 trades.push(RebalanceTrade {
267 asset_id: asset.asset_id.clone(),
268 action,
269 quantity: quantity.abs(),
270 target_weight,
271 });
272 }
273 }
274
275 Ok(trades)
276 }
277}
278
279impl OptimizationEngine {
280 pub fn new() -> Self {
282 Self {
283 optimization_algorithms: HashMap::new(),
284 objective_functions: HashMap::new(),
285 constraints: Vec::new(),
286 }
287 }
288
289 pub fn initialize(&mut self) -> Result<(), FinancialError> {
291 Ok(())
292 }
293
294 pub fn add_algorithm(&mut self, algorithm: OptimizationAlgorithm) {
296 self.optimization_algorithms
297 .insert(algorithm.algorithm_id.clone(), algorithm);
298 }
299
300 pub fn get_algorithm(&self, algorithm_id: &str) -> Option<&OptimizationAlgorithm> {
302 self.optimization_algorithms.get(algorithm_id)
303 }
304
305 pub fn list_algorithms(&self) -> Vec<String> {
307 self.optimization_algorithms.keys().cloned().collect()
308 }
309
310 pub fn add_objective_function(&mut self, function: ObjectiveFunction) {
312 self.objective_functions
313 .insert(function.function_id.clone(), function);
314 }
315
316 pub fn get_objective_function(&self, function_id: &str) -> Option<&ObjectiveFunction> {
318 self.objective_functions.get(function_id)
319 }
320
321 pub fn list_objective_functions(&self) -> Vec<String> {
323 self.objective_functions.keys().cloned().collect()
324 }
325
326 pub fn add_constraint(&mut self, constraint: OptimizationConstraint) {
328 self.constraints.push(constraint);
329 }
330
331 pub fn list_constraints(&self) -> &[OptimizationConstraint] {
333 &self.constraints
334 }
335}
336
337impl RebalancingStrategy {
338 pub fn new() -> Self {
340 Self {
341 strategy_id: "strategy_1".to_string(),
342 strategy_name: "Monthly rebalancing".to_string(),
343 strategy_type: RebalancingStrategyType::TimeBased,
344 parameters: RebalancingParameters::new(),
345 constraints: RebalancingConstraints::new(),
346 target_weights: HashMap::new(),
347 }
348 }
349}
350
351impl RebalancingParameters {
352 pub fn new() -> Self {
354 Self {
355 rebalance_frequency: 30, deviation_threshold: 0.05, min_trade_size: 1000.0,
358 max_trade_size: 100000.0,
359 transaction_costs: TransactionCosts::new(),
360 }
361 }
362}
363
364impl TransactionCosts {
365 pub fn new() -> Self {
367 Self {
368 commission_rate: 0.001,
369 spread_cost: 0.0005,
370 market_impact: 0.0002,
371 tax_rate: 0.2,
372 }
373 }
374}
375
376impl RebalancingConstraints {
377 pub fn new() -> Self {
379 Self {
380 asset_class_limits: HashMap::new(),
381 sector_limits: HashMap::new(),
382 liquidity_constraints: LiquidityConstraints::new(),
383 regulatory_constraints: RegulatoryConstraints::new(),
384 }
385 }
386}
387
388impl LiquidityConstraints {
389 pub fn new() -> Self {
391 Self {
392 max_daily_volume: 1000000.0,
393 min_liquidity_score: 0.7,
394 liquidity_buffer: 0.1,
395 }
396 }
397}
398
399impl RegulatoryConstraints {
400 pub fn new() -> Self {
402 Self {
403 concentration_limits: HashMap::new(),
404 reporting_requirements: vec!["Daily report".to_string()],
405 compliance_deadlines: vec![86400], }
407 }
408}
409
410impl OptimizationAlgorithm {
411 pub fn new() -> Self {
413 Self {
414 algorithm_id: "algo_1".to_string(),
415 algorithm_type: OptimizationAlgorithmType::MeanVariance,
416 parameters: OptimizationParameters::new(),
417 }
418 }
419}
420
421impl OptimizationParameters {
422 pub fn new() -> Self {
424 Self {
425 risk_aversion: 1.0,
426 expected_returns: vec![0.1, 0.08, 0.12],
427 covariance_matrix: vec![
428 vec![0.04, 0.02, 0.01],
429 vec![0.02, 0.09, 0.03],
430 vec![0.01, 0.03, 0.16],
431 ],
432 constraints: vec![],
433 }
434 }
435}
436
437impl ObjectiveFunction {
438 pub fn new() -> Self {
440 Self {
441 function_id: "obj_1".to_string(),
442 function_type: ObjectiveFunctionType::MaximizeSharpe,
443 parameters: HashMap::new(),
444 }
445 }
446}
447
448impl OptimizationConstraint {
449 pub fn new() -> Self {
451 Self {
452 constraint_id: "constraint_1".to_string(),
453 constraint_type: ConstraintType::Equality,
454 bounds: ConstraintBounds::new(),
455 }
456 }
457}
458
459impl ConstraintBounds {
460 pub fn new() -> Self {
462 Self {
463 lower_bound: 0.0,
464 upper_bound: 1.0,
465 }
466 }
467}