Skip to main content

qualia_core_db/specialized_libs/financial_modeling/
rebalancing.rs

1use super::*;
2
3/// Rebalancing engine
4pub struct RebalancingEngine {
5    rebalancing_strategies: HashMap<String, RebalancingStrategy>,
6    optimization_engine: OptimizationEngine,
7    execution_engine: ExecutionEngine,
8}
9
10/// Rebalancing strategies
11#[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    /// Target portfolio weights keyed by `asset_id`, summing to ~1.0. Used by
19    /// `RebalancingEngine::rebalance` to compute drift away from the target
20    /// allocation. Assets without an entry are treated as target weight 0.0.
21    pub target_weights: HashMap<String, f64>,
22}
23
24/// A single rebalance trade produced by `RebalancingEngine::rebalance`.
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct RebalanceTrade {
27    /// The asset to trade.
28    pub asset_id: String,
29    /// Whether to buy or sell.
30    pub action: TradeAction,
31    /// Number of units to trade (always positive; direction is in `action`).
32    pub quantity: f64,
33    /// The target weight this trade moves the asset towards.
34    pub target_weight: f64,
35}
36
37/// Direction of a `RebalanceTrade`.
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub enum TradeAction {
40    Buy,
41    Sell,
42}
43
44/// Rebalancing strategy types
45#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
46pub enum RebalancingStrategyType {
47    TimeBased,
48    ThresholdBased,
49    OptimizationBased,
50    Hybrid,
51}
52
53/// Rebalancing parameters
54#[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/// Transaction costs
64#[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/// Rebalancing constraints
73#[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/// Liquidity constraints
82#[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/// Regulatory constraints
90#[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
97/// Optimization engine
98pub struct OptimizationEngine {
99    optimization_algorithms: HashMap<String, OptimizationAlgorithm>,
100    objective_functions: HashMap<String, ObjectiveFunction>,
101    constraints: Vec<OptimizationConstraint>,
102}
103
104/// Optimization algorithms
105#[derive(Debug, Clone)]
106pub struct OptimizationAlgorithm {
107    pub algorithm_id: String,
108    pub algorithm_type: OptimizationAlgorithmType,
109    pub parameters: OptimizationParameters,
110}
111
112/// Optimization algorithm types
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub enum OptimizationAlgorithmType {
115    MeanVariance,
116    BlackLitterman,
117    RiskParity,
118    EqualWeight,
119    Custom,
120}
121
122/// Optimization parameters
123#[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/// Objective functions
132#[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/// Objective function types
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub enum ObjectiveFunctionType {
142    MaximizeReturn,
143    MinimizeRisk,
144    MaximizeSharpe,
145    MinimizeDrawdown,
146    Custom,
147}
148
149/// Optimization constraints
150#[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/// Constraint types
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub enum ConstraintType {
160    Equality,
161    Inequality,
162    Bound,
163    Linear,
164    Nonlinear,
165}
166
167/// Constraint bounds
168#[derive(Debug, Clone, Serialize, Deserialize)]
169pub struct ConstraintBounds {
170    pub lower_bound: f64,
171    pub upper_bound: f64,
172}
173
174impl RebalancingEngine {
175    /// Creates a `RebalancingEngine` with empty registries / default configuration.
176    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    /// Readies the `RebalancingEngine` sub-components; registers/populates any built-in defaults.
185    pub fn initialize(&mut self) -> Result<(), FinancialError> {
186        self.optimization_engine.initialize()?;
187        self.execution_engine.initialize()?;
188        Ok(())
189    }
190
191    /// Register a rebalancing strategy, keyed by `strategy.strategy_id`.
192    pub fn register_strategy(&mut self, strategy: RebalancingStrategy) {
193        self.rebalancing_strategies
194            .insert(strategy.strategy_id.clone(), strategy);
195    }
196
197    /// Look up a registered strategy by id.
198    pub fn get_strategy(&self, strategy_id: &str) -> Option<&RebalancingStrategy> {
199        self.rebalancing_strategies.get(strategy_id)
200    }
201
202    /// Compute the current portfolio weights (`market_value / total`) keyed by
203    /// `asset_id`. These are the "drifted" weights that `rebalance` compares
204    /// against a strategy's `target_weights`. Returns an empty map when the
205    /// portfolio has no positive market value.
206    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    /// Compute drift against `strategy.target_weights` and, for any asset whose
219    /// drift exceeds `strategy.parameters.deviation_threshold`, generate a
220    /// `RebalanceTrade` that would move the asset back to its target weight.
221    ///
222    /// Trades are sized in units: `quantity = |target_value − current_value| /
223    /// current_price`, where `target_value = target_weight · total_value`. The
224    /// portfolio is **not** mutated by this method — it only proposes trades;
225    /// applying them (and their costs) is the execution layer's job.
226    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    /// Creates a `OptimizationEngine` with empty registries / default configuration.
281    pub fn new() -> Self {
282        Self {
283            optimization_algorithms: HashMap::new(),
284            objective_functions: HashMap::new(),
285            constraints: Vec::new(),
286        }
287    }
288
289    /// Readies the `OptimizationEngine` sub-components; registers/populates any built-in defaults.
290    pub fn initialize(&mut self) -> Result<(), FinancialError> {
291        Ok(())
292    }
293
294    /// Registers `algorithm` in the registry (keyed by its id).
295    pub fn add_algorithm(&mut self, algorithm: OptimizationAlgorithm) {
296        self.optimization_algorithms
297            .insert(algorithm.algorithm_id.clone(), algorithm);
298    }
299
300    /// Looks up `algorithm` by id; `None` if not registered.
301    pub fn get_algorithm(&self, algorithm_id: &str) -> Option<&OptimizationAlgorithm> {
302        self.optimization_algorithms.get(algorithm_id)
303    }
304
305    /// Iterates over all registered `algorithms` entries.
306    pub fn list_algorithms(&self) -> Vec<String> {
307        self.optimization_algorithms.keys().cloned().collect()
308    }
309
310    /// Registers `objective function` in the registry (keyed by its id).
311    pub fn add_objective_function(&mut self, function: ObjectiveFunction) {
312        self.objective_functions
313            .insert(function.function_id.clone(), function);
314    }
315
316    /// Looks up `objective function` by id; `None` if not registered.
317    pub fn get_objective_function(&self, function_id: &str) -> Option<&ObjectiveFunction> {
318        self.objective_functions.get(function_id)
319    }
320
321    /// Iterates over all registered `objective functions` entries.
322    pub fn list_objective_functions(&self) -> Vec<String> {
323        self.objective_functions.keys().cloned().collect()
324    }
325
326    /// Registers `constraint` in the registry (keyed by its id).
327    pub fn add_constraint(&mut self, constraint: OptimizationConstraint) {
328        self.constraints.push(constraint);
329    }
330
331    /// Iterates over all registered `constraints` entries.
332    pub fn list_constraints(&self) -> &[OptimizationConstraint] {
333        &self.constraints
334    }
335}
336
337impl RebalancingStrategy {
338    /// Creates a `RebalancingStrategy` with empty registries / default configuration.
339    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    /// Creates a `RebalancingParameters` with empty registries / default configuration.
353    pub fn new() -> Self {
354        Self {
355            rebalance_frequency: 30,   // 30 days
356            deviation_threshold: 0.05, // 5%
357            min_trade_size: 1000.0,
358            max_trade_size: 100000.0,
359            transaction_costs: TransactionCosts::new(),
360        }
361    }
362}
363
364impl TransactionCosts {
365    /// Creates a `TransactionCosts` with empty registries / default configuration.
366    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    /// Creates a `RebalancingConstraints` with empty registries / default configuration.
378    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    /// Creates a `LiquidityConstraints` with empty registries / default configuration.
390    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    /// Creates a `RegulatoryConstraints` with empty registries / default configuration.
401    pub fn new() -> Self {
402        Self {
403            concentration_limits: HashMap::new(),
404            reporting_requirements: vec!["Daily report".to_string()],
405            compliance_deadlines: vec![86400], // 1 day
406        }
407    }
408}
409
410impl OptimizationAlgorithm {
411    /// Creates a `OptimizationAlgorithm` with empty registries / default configuration.
412    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    /// Creates a `OptimizationParameters` with empty registries / default configuration.
423    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    /// Creates a `ObjectiveFunction` with empty registries / default configuration.
439    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    /// Creates a `OptimizationConstraint` with empty registries / default configuration.
450    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    /// Creates a `ConstraintBounds` with empty registries / default configuration.
461    pub fn new() -> Self {
462        Self {
463            lower_bound: 0.0,
464            upper_bound: 1.0,
465        }
466    }
467}