work on new engine
This commit is contained in:
parent
44476da13f
commit
a1e5a21847
126 changed files with 3425 additions and 6695 deletions
505
apps/stock/engine/src/risk/bet_sizing.rs
Normal file
505
apps/stock/engine/src/risk/bet_sizing.rs
Normal file
|
|
@ -0,0 +1,505 @@
|
|||
use std::collections::HashMap;
|
||||
use crate::orderbook::analytics::{OrderBookAnalytics, LiquidityProfile};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BetSizingParameters {
|
||||
pub signal_strength: f64, // -1 to 1
|
||||
pub signal_confidence: f64, // 0 to 1
|
||||
pub market_regime: MarketRegime,
|
||||
pub volatility: f64,
|
||||
pub liquidity_score: f64,
|
||||
pub correlation_exposure: f64,
|
||||
pub current_drawdown: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum MarketRegime {
|
||||
Trending,
|
||||
RangeBound,
|
||||
HighVolatility,
|
||||
LowVolatility,
|
||||
Transitioning,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PositionSize {
|
||||
pub shares: u32,
|
||||
pub notional_value: f64,
|
||||
pub percent_of_capital: f64,
|
||||
pub risk_adjusted_size: f64,
|
||||
pub sizing_method: String,
|
||||
pub adjustments: Vec<SizeAdjustment>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SizeAdjustment {
|
||||
pub reason: String,
|
||||
pub factor: f64,
|
||||
}
|
||||
|
||||
pub struct BetSizer {
|
||||
capital: f64,
|
||||
base_risk_per_trade: f64,
|
||||
max_position_size: f64,
|
||||
min_position_size: f64,
|
||||
use_kelly: bool,
|
||||
volatility_scaling: bool,
|
||||
regime_adjustments: HashMap<MarketRegime, f64>,
|
||||
}
|
||||
|
||||
impl BetSizer {
|
||||
pub fn new(capital: f64, base_risk_per_trade: f64) -> Self {
|
||||
let mut regime_adjustments = HashMap::new();
|
||||
regime_adjustments.insert(MarketRegime::Trending, 1.2);
|
||||
regime_adjustments.insert(MarketRegime::RangeBound, 0.8);
|
||||
regime_adjustments.insert(MarketRegime::HighVolatility, 0.6);
|
||||
regime_adjustments.insert(MarketRegime::LowVolatility, 1.1);
|
||||
regime_adjustments.insert(MarketRegime::Transitioning, 0.7);
|
||||
|
||||
Self {
|
||||
capital,
|
||||
base_risk_per_trade,
|
||||
max_position_size: 0.10, // 10% max
|
||||
min_position_size: 0.001, // 0.1% min
|
||||
use_kelly: true,
|
||||
volatility_scaling: true,
|
||||
regime_adjustments,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn calculate_position_size(
|
||||
&self,
|
||||
params: &BetSizingParameters,
|
||||
price: f64,
|
||||
stop_loss: Option<f64>,
|
||||
historical_performance: Option<&PerformanceStats>,
|
||||
orderbook_analytics: Option<&OrderBookAnalytics>,
|
||||
liquidity_profile: Option<&LiquidityProfile>,
|
||||
) -> PositionSize {
|
||||
let mut adjustments = Vec::new();
|
||||
|
||||
// Start with base position size
|
||||
let mut risk_fraction = self.base_risk_per_trade;
|
||||
|
||||
// 1. Kelly Criterion adjustment
|
||||
if self.use_kelly {
|
||||
if let Some(perf) = historical_performance {
|
||||
let kelly_fraction = self.calculate_kelly_fraction(perf);
|
||||
let kelly_adjustment = (kelly_fraction / self.base_risk_per_trade).min(2.0).max(0.1);
|
||||
risk_fraction *= kelly_adjustment;
|
||||
adjustments.push(SizeAdjustment {
|
||||
reason: "Kelly Criterion".to_string(),
|
||||
factor: kelly_adjustment,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Signal strength adjustment
|
||||
let signal_adjustment = self.calculate_signal_adjustment(params.signal_strength, params.signal_confidence);
|
||||
risk_fraction *= signal_adjustment;
|
||||
adjustments.push(SizeAdjustment {
|
||||
reason: "Signal Strength".to_string(),
|
||||
factor: signal_adjustment,
|
||||
});
|
||||
|
||||
// 3. Volatility adjustment
|
||||
if self.volatility_scaling {
|
||||
let vol_adjustment = self.calculate_volatility_adjustment(params.volatility);
|
||||
risk_fraction *= vol_adjustment;
|
||||
adjustments.push(SizeAdjustment {
|
||||
reason: "Volatility Scaling".to_string(),
|
||||
factor: vol_adjustment,
|
||||
});
|
||||
}
|
||||
|
||||
// 4. Market regime adjustment
|
||||
if let Some(®ime_factor) = self.regime_adjustments.get(¶ms.market_regime) {
|
||||
risk_fraction *= regime_factor;
|
||||
adjustments.push(SizeAdjustment {
|
||||
reason: format!("Market Regime ({:?})", params.market_regime),
|
||||
factor: regime_factor,
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Liquidity adjustment
|
||||
let liquidity_adjustment = self.calculate_liquidity_adjustment(
|
||||
params.liquidity_score,
|
||||
orderbook_analytics,
|
||||
liquidity_profile,
|
||||
);
|
||||
risk_fraction *= liquidity_adjustment;
|
||||
adjustments.push(SizeAdjustment {
|
||||
reason: "Liquidity".to_string(),
|
||||
factor: liquidity_adjustment,
|
||||
});
|
||||
|
||||
// 6. Correlation adjustment
|
||||
let correlation_adjustment = self.calculate_correlation_adjustment(params.correlation_exposure);
|
||||
risk_fraction *= correlation_adjustment;
|
||||
adjustments.push(SizeAdjustment {
|
||||
reason: "Correlation Exposure".to_string(),
|
||||
factor: correlation_adjustment,
|
||||
});
|
||||
|
||||
// 7. Drawdown adjustment
|
||||
let drawdown_adjustment = self.calculate_drawdown_adjustment(params.current_drawdown);
|
||||
risk_fraction *= drawdown_adjustment;
|
||||
adjustments.push(SizeAdjustment {
|
||||
reason: "Current Drawdown".to_string(),
|
||||
factor: drawdown_adjustment,
|
||||
});
|
||||
|
||||
// Calculate final position size
|
||||
let position_value = if let Some(stop_price) = stop_loss {
|
||||
// Risk-based sizing
|
||||
let risk_per_share = (price - stop_price).abs();
|
||||
let risk_amount = self.capital * risk_fraction;
|
||||
risk_amount / risk_per_share
|
||||
} else {
|
||||
// Fixed percentage sizing
|
||||
self.capital * risk_fraction / price
|
||||
};
|
||||
|
||||
// Apply min/max constraints
|
||||
let constrained_value = position_value
|
||||
.min(self.capital * self.max_position_size / price)
|
||||
.max(self.capital * self.min_position_size / price);
|
||||
|
||||
let shares = constrained_value.floor() as u32;
|
||||
let notional_value = shares as f64 * price;
|
||||
let percent_of_capital = notional_value / self.capital;
|
||||
|
||||
PositionSize {
|
||||
shares,
|
||||
notional_value,
|
||||
percent_of_capital,
|
||||
risk_adjusted_size: risk_fraction,
|
||||
sizing_method: if stop_loss.is_some() { "Risk-based".to_string() } else { "Fixed-percentage".to_string() },
|
||||
adjustments,
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_kelly_fraction(&self, perf: &PerformanceStats) -> f64 {
|
||||
if perf.total_trades < 20 {
|
||||
return self.base_risk_per_trade; // Not enough data
|
||||
}
|
||||
|
||||
let win_rate = perf.win_rate;
|
||||
let loss_rate = 1.0 - win_rate;
|
||||
|
||||
if perf.avg_loss == 0.0 {
|
||||
return self.base_risk_per_trade;
|
||||
}
|
||||
|
||||
let win_loss_ratio = perf.avg_win / perf.avg_loss.abs();
|
||||
|
||||
// Kelly formula: f = p - q/b
|
||||
// where p = win probability, q = loss probability, b = win/loss ratio
|
||||
let kelly = win_rate - (loss_rate / win_loss_ratio);
|
||||
|
||||
// Apply Kelly fraction (typically 25% of full Kelly)
|
||||
let kelly_fraction = kelly * 0.25;
|
||||
|
||||
// Ensure it's positive and reasonable
|
||||
kelly_fraction.max(0.0).min(0.25)
|
||||
}
|
||||
|
||||
fn calculate_signal_adjustment(&self, strength: f64, confidence: f64) -> f64 {
|
||||
// Strength is -1 to 1, we want 0 to 1
|
||||
let normalized_strength = (strength.abs() + 1.0) / 2.0;
|
||||
|
||||
// Combine strength and confidence
|
||||
let signal_score = normalized_strength * 0.7 + confidence * 0.3;
|
||||
|
||||
// Map to adjustment factor (0.5 to 1.5)
|
||||
0.5 + signal_score
|
||||
}
|
||||
|
||||
fn calculate_volatility_adjustment(&self, volatility: f64) -> f64 {
|
||||
// Target volatility (e.g., 15% annualized)
|
||||
let target_vol = 0.15 / (252.0_f64.sqrt()); // Daily vol
|
||||
|
||||
// Inverse volatility scaling
|
||||
let adjustment = (target_vol / volatility).min(1.5).max(0.5);
|
||||
|
||||
adjustment
|
||||
}
|
||||
|
||||
fn calculate_liquidity_adjustment(
|
||||
&self,
|
||||
liquidity_score: f64,
|
||||
orderbook: Option<&OrderBookAnalytics>,
|
||||
profile: Option<&LiquidityProfile>,
|
||||
) -> f64 {
|
||||
let mut adjustment = 1.0;
|
||||
|
||||
// Base liquidity score adjustment
|
||||
if liquidity_score < 0.3 {
|
||||
adjustment *= 0.5; // Very poor liquidity
|
||||
} else if liquidity_score < 0.5 {
|
||||
adjustment *= 0.7;
|
||||
} else if liquidity_score > 0.8 {
|
||||
adjustment *= 1.1; // Good liquidity bonus
|
||||
}
|
||||
|
||||
// Orderbook spread adjustment
|
||||
if let Some(ob) = orderbook {
|
||||
if ob.spread_bps > 50.0 {
|
||||
adjustment *= 0.8; // Wide spread penalty
|
||||
} else if ob.spread_bps < 10.0 {
|
||||
adjustment *= 1.1; // Tight spread bonus
|
||||
}
|
||||
}
|
||||
|
||||
// Market impact consideration
|
||||
if let Some(prof) = profile {
|
||||
// Check if our typical order size would move the market
|
||||
let typical_order_value = self.capital * self.base_risk_per_trade;
|
||||
let impact = prof.calculate_market_impact(typical_order_value, true);
|
||||
|
||||
if impact.price_impact > 0.001 { // More than 10 bps impact
|
||||
adjustment *= (1.0 - impact.price_impact * 10.0).max(0.5);
|
||||
}
|
||||
}
|
||||
|
||||
adjustment
|
||||
}
|
||||
|
||||
fn calculate_correlation_adjustment(&self, correlation_exposure: f64) -> f64 {
|
||||
// Reduce size if highly correlated with existing positions
|
||||
if correlation_exposure > 0.7 {
|
||||
0.5
|
||||
} else if correlation_exposure > 0.5 {
|
||||
0.7
|
||||
} else if correlation_exposure > 0.3 {
|
||||
0.9
|
||||
} else {
|
||||
1.0
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_drawdown_adjustment(&self, current_drawdown: f64) -> f64 {
|
||||
// Reduce size during drawdowns
|
||||
if current_drawdown > 0.20 {
|
||||
0.5 // 50% reduction if in 20%+ drawdown
|
||||
} else if current_drawdown > 0.10 {
|
||||
0.7
|
||||
} else if current_drawdown > 0.05 {
|
||||
0.85
|
||||
} else {
|
||||
1.0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn calculate_optimal_stop_loss(
|
||||
&self,
|
||||
entry_price: f64,
|
||||
volatility: f64,
|
||||
support_levels: &[f64],
|
||||
atr: Option<f64>,
|
||||
is_long: bool,
|
||||
) -> f64 {
|
||||
let mut stop_candidates = Vec::new();
|
||||
|
||||
// 1. Volatility-based stop
|
||||
let vol_stop = if is_long {
|
||||
entry_price * (1.0 - 2.0 * volatility)
|
||||
} else {
|
||||
entry_price * (1.0 + 2.0 * volatility)
|
||||
};
|
||||
stop_candidates.push(("Volatility", vol_stop));
|
||||
|
||||
// 2. ATR-based stop
|
||||
if let Some(atr_value) = atr {
|
||||
let atr_stop = if is_long {
|
||||
entry_price - 2.0 * atr_value
|
||||
} else {
|
||||
entry_price + 2.0 * atr_value
|
||||
};
|
||||
stop_candidates.push(("ATR", atr_stop));
|
||||
}
|
||||
|
||||
// 3. Support/Resistance based stop
|
||||
if !support_levels.is_empty() {
|
||||
let technical_stop = if is_long {
|
||||
// Find nearest support below entry
|
||||
support_levels.iter()
|
||||
.filter(|&&level| level < entry_price)
|
||||
.max_by(|a, b| a.partial_cmp(b).unwrap())
|
||||
.map(|&level| level * 0.995) // Just below support
|
||||
} else {
|
||||
// Find nearest resistance above entry
|
||||
support_levels.iter()
|
||||
.filter(|&&level| level > entry_price)
|
||||
.min_by(|a, b| a.partial_cmp(b).unwrap())
|
||||
.map(|&level| level * 1.005) // Just above resistance
|
||||
};
|
||||
|
||||
if let Some(stop) = technical_stop {
|
||||
stop_candidates.push(("Technical", stop));
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Maximum loss stop (e.g., 5% from entry)
|
||||
let max_loss_stop = if is_long {
|
||||
entry_price * 0.95
|
||||
} else {
|
||||
entry_price * 1.05
|
||||
};
|
||||
stop_candidates.push(("MaxLoss", max_loss_stop));
|
||||
|
||||
// Choose the most conservative stop (closest to entry)
|
||||
let optimal_stop = if is_long {
|
||||
stop_candidates.iter()
|
||||
.map(|(_, stop)| *stop)
|
||||
.max_by(|a, b| a.partial_cmp(b).unwrap())
|
||||
.unwrap_or(vol_stop)
|
||||
} else {
|
||||
stop_candidates.iter()
|
||||
.map(|(_, stop)| *stop)
|
||||
.min_by(|a, b| a.partial_cmp(b).unwrap())
|
||||
.unwrap_or(vol_stop)
|
||||
};
|
||||
|
||||
optimal_stop
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PerformanceStats {
|
||||
pub total_trades: u32,
|
||||
pub win_rate: f64,
|
||||
pub avg_win: f64,
|
||||
pub avg_loss: f64,
|
||||
pub sharpe_ratio: f64,
|
||||
pub max_consecutive_losses: u32,
|
||||
}
|
||||
|
||||
/// Dynamic position sizing based on market conditions
|
||||
pub struct DynamicSizer {
|
||||
base_sizer: BetSizer,
|
||||
regime_detector: MarketRegimeDetector,
|
||||
performance_tracker: PerformanceTracker,
|
||||
}
|
||||
|
||||
impl DynamicSizer {
|
||||
pub fn new(capital: f64, base_risk: f64) -> Self {
|
||||
Self {
|
||||
base_sizer: BetSizer::new(capital, base_risk),
|
||||
regime_detector: MarketRegimeDetector::new(),
|
||||
performance_tracker: PerformanceTracker::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_market_data(&mut self, volatility: f64, volume: f64, trend_strength: f64) {
|
||||
self.regime_detector.update(volatility, volume, trend_strength);
|
||||
}
|
||||
|
||||
pub fn record_trade(&mut self, pnl: f64, holding_period: i64) {
|
||||
self.performance_tracker.record_trade(pnl, holding_period);
|
||||
}
|
||||
|
||||
pub fn get_sizing_parameters(&self) -> BetSizingParameters {
|
||||
BetSizingParameters {
|
||||
signal_strength: 0.0, // To be filled by strategy
|
||||
signal_confidence: 0.0, // To be filled by strategy
|
||||
market_regime: self.regime_detector.current_regime(),
|
||||
volatility: self.regime_detector.current_volatility(),
|
||||
liquidity_score: 0.0, // To be filled from orderbook
|
||||
correlation_exposure: 0.0, // To be filled from portfolio
|
||||
current_drawdown: self.performance_tracker.current_drawdown(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct MarketRegimeDetector {
|
||||
volatility_history: Vec<f64>,
|
||||
volume_history: Vec<f64>,
|
||||
trend_history: Vec<f64>,
|
||||
window_size: usize,
|
||||
}
|
||||
|
||||
impl MarketRegimeDetector {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
volatility_history: Vec::new(),
|
||||
volume_history: Vec::new(),
|
||||
trend_history: Vec::new(),
|
||||
window_size: 20,
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, volatility: f64, volume: f64, trend_strength: f64) {
|
||||
self.volatility_history.push(volatility);
|
||||
self.volume_history.push(volume);
|
||||
self.trend_history.push(trend_strength);
|
||||
|
||||
// Keep only recent history
|
||||
if self.volatility_history.len() > self.window_size {
|
||||
self.volatility_history.remove(0);
|
||||
self.volume_history.remove(0);
|
||||
self.trend_history.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn current_regime(&self) -> MarketRegime {
|
||||
if self.volatility_history.len() < 5 {
|
||||
return MarketRegime::Transitioning;
|
||||
}
|
||||
|
||||
let avg_vol = self.volatility_history.iter().sum::<f64>() / self.volatility_history.len() as f64;
|
||||
let avg_trend = self.trend_history.iter().sum::<f64>() / self.trend_history.len() as f64;
|
||||
|
||||
if avg_vol > 0.02 {
|
||||
MarketRegime::HighVolatility
|
||||
} else if avg_vol < 0.01 {
|
||||
MarketRegime::LowVolatility
|
||||
} else if avg_trend.abs() > 0.7 {
|
||||
MarketRegime::Trending
|
||||
} else if avg_trend.abs() < 0.3 {
|
||||
MarketRegime::RangeBound
|
||||
} else {
|
||||
MarketRegime::Transitioning
|
||||
}
|
||||
}
|
||||
|
||||
fn current_volatility(&self) -> f64 {
|
||||
if self.volatility_history.is_empty() {
|
||||
return 0.015; // Default 1.5% daily vol
|
||||
}
|
||||
self.volatility_history.iter().sum::<f64>() / self.volatility_history.len() as f64
|
||||
}
|
||||
}
|
||||
|
||||
struct PerformanceTracker {
|
||||
trades: Vec<(f64, i64)>, // (pnl, holding_period)
|
||||
peak_capital: f64,
|
||||
current_capital: f64,
|
||||
}
|
||||
|
||||
impl PerformanceTracker {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
trades: Vec::new(),
|
||||
peak_capital: 100000.0,
|
||||
current_capital: 100000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn record_trade(&mut self, pnl: f64, holding_period: i64) {
|
||||
self.trades.push((pnl, holding_period));
|
||||
self.current_capital += pnl;
|
||||
if self.current_capital > self.peak_capital {
|
||||
self.peak_capital = self.current_capital;
|
||||
}
|
||||
}
|
||||
|
||||
fn current_drawdown(&self) -> f64 {
|
||||
if self.peak_capital > 0.0 {
|
||||
(self.peak_capital - self.current_capital) / self.peak_capital
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
195
apps/stock/engine/src/risk/mod.rs
Normal file
195
apps/stock/engine/src/risk/mod.rs
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
pub mod portfolio;
|
||||
pub mod bet_sizing;
|
||||
|
||||
use crate::{Order, Side};
|
||||
use dashmap::DashMap;
|
||||
use parking_lot::RwLock;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use portfolio::{PortfolioRisk, RiskModel, CorrelationMatrix, ConcentrationMetrics};
|
||||
pub use bet_sizing::{BetSizer, BetSizingParameters, PositionSize, MarketRegime, DynamicSizer};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RiskLimits {
|
||||
pub max_position_size: f64,
|
||||
pub max_order_size: f64,
|
||||
pub max_daily_loss: f64,
|
||||
pub max_gross_exposure: f64,
|
||||
pub max_symbol_exposure: f64,
|
||||
}
|
||||
|
||||
impl Default for RiskLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_position_size: 100_000.0,
|
||||
max_order_size: 10_000.0,
|
||||
max_daily_loss: 5_000.0,
|
||||
max_gross_exposure: 1_000_000.0,
|
||||
max_symbol_exposure: 50_000.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RiskCheckResult {
|
||||
pub passed: bool,
|
||||
pub violations: Vec<String>,
|
||||
pub checks: RiskChecks,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RiskChecks {
|
||||
pub order_size: bool,
|
||||
pub position_size: bool,
|
||||
pub daily_loss: bool,
|
||||
pub gross_exposure: bool,
|
||||
pub symbol_exposure: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RiskMetrics {
|
||||
pub current_exposure: f64,
|
||||
pub daily_pnl: f64,
|
||||
pub position_count: usize,
|
||||
pub gross_exposure: f64,
|
||||
pub max_position_size: f64,
|
||||
pub utilization_pct: f64,
|
||||
}
|
||||
|
||||
pub struct RiskEngine {
|
||||
limits: Arc<RwLock<RiskLimits>>,
|
||||
symbol_exposures: DashMap<String, f64>,
|
||||
daily_pnl: Arc<RwLock<f64>>,
|
||||
}
|
||||
|
||||
impl RiskEngine {
|
||||
pub fn new() -> Self {
|
||||
Self::with_limits(RiskLimits::default())
|
||||
}
|
||||
|
||||
pub fn with_limits(limits: RiskLimits) -> Self {
|
||||
Self {
|
||||
limits: Arc::new(RwLock::new(limits)),
|
||||
symbol_exposures: DashMap::new(),
|
||||
daily_pnl: Arc::new(RwLock::new(0.0)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_limits(&self, new_limits: RiskLimits) {
|
||||
*self.limits.write() = new_limits;
|
||||
}
|
||||
|
||||
pub fn check_order(&self, order: &Order, current_position: Option<f64>) -> RiskCheckResult {
|
||||
let mut violations = Vec::new();
|
||||
let limits = self.limits.read();
|
||||
|
||||
// Check order size
|
||||
if order.quantity > limits.max_order_size {
|
||||
violations.push(format!(
|
||||
"Order size {} exceeds limit {}",
|
||||
order.quantity, limits.max_order_size
|
||||
));
|
||||
}
|
||||
|
||||
// Check position size after order
|
||||
let current_pos = current_position.unwrap_or(0.0);
|
||||
let new_position = match order.side {
|
||||
Side::Buy => current_pos + order.quantity,
|
||||
Side::Sell => current_pos - order.quantity,
|
||||
};
|
||||
|
||||
if new_position.abs() > limits.max_position_size {
|
||||
violations.push(format!(
|
||||
"Position size {} would exceed limit {}",
|
||||
new_position.abs(), limits.max_position_size
|
||||
));
|
||||
}
|
||||
|
||||
// Check symbol exposure
|
||||
let symbol_exposure = self.symbol_exposures
|
||||
.get(&order.symbol)
|
||||
.map(|e| *e)
|
||||
.unwrap_or(0.0);
|
||||
|
||||
let new_exposure = symbol_exposure + order.quantity;
|
||||
if new_exposure > limits.max_symbol_exposure {
|
||||
violations.push(format!(
|
||||
"Symbol exposure {} would exceed limit {}",
|
||||
new_exposure, limits.max_symbol_exposure
|
||||
));
|
||||
}
|
||||
|
||||
// Check daily loss
|
||||
let daily_pnl = *self.daily_pnl.read();
|
||||
if daily_pnl < -limits.max_daily_loss {
|
||||
violations.push(format!(
|
||||
"Daily loss {} exceeds limit {}",
|
||||
-daily_pnl, limits.max_daily_loss
|
||||
));
|
||||
}
|
||||
|
||||
// Calculate gross exposure
|
||||
let gross_exposure = self.calculate_gross_exposure();
|
||||
if gross_exposure > limits.max_gross_exposure {
|
||||
violations.push(format!(
|
||||
"Gross exposure {} exceeds limit {}",
|
||||
gross_exposure, limits.max_gross_exposure
|
||||
));
|
||||
}
|
||||
|
||||
RiskCheckResult {
|
||||
passed: violations.is_empty(),
|
||||
violations,
|
||||
checks: RiskChecks {
|
||||
order_size: order.quantity <= limits.max_order_size,
|
||||
position_size: new_position.abs() <= limits.max_position_size,
|
||||
daily_loss: daily_pnl >= -limits.max_daily_loss,
|
||||
gross_exposure: gross_exposure <= limits.max_gross_exposure,
|
||||
symbol_exposure: new_exposure <= limits.max_symbol_exposure,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_position(&self, symbol: &str, new_position: f64) {
|
||||
if new_position.abs() < 0.0001 {
|
||||
self.symbol_exposures.remove(symbol);
|
||||
} else {
|
||||
self.symbol_exposures.insert(symbol.to_string(), new_position.abs());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_daily_pnl(&self, pnl_change: f64) {
|
||||
let mut daily_pnl = self.daily_pnl.write();
|
||||
*daily_pnl += pnl_change;
|
||||
}
|
||||
|
||||
pub fn reset_daily_metrics(&self) {
|
||||
*self.daily_pnl.write() = 0.0;
|
||||
}
|
||||
|
||||
fn calculate_gross_exposure(&self) -> f64 {
|
||||
self.symbol_exposures
|
||||
.iter()
|
||||
.map(|entry| *entry.value())
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn calculate_total_exposure(&self) -> f64 {
|
||||
self.calculate_gross_exposure()
|
||||
}
|
||||
|
||||
pub fn get_risk_metrics(&self) -> RiskMetrics {
|
||||
let limits = self.limits.read();
|
||||
let gross_exposure = self.calculate_gross_exposure();
|
||||
|
||||
RiskMetrics {
|
||||
current_exposure: 0.0,
|
||||
daily_pnl: *self.daily_pnl.read(),
|
||||
position_count: self.symbol_exposures.len(),
|
||||
gross_exposure,
|
||||
max_position_size: limits.max_position_size,
|
||||
utilization_pct: (gross_exposure / limits.max_gross_exposure * 100.0).min(100.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
533
apps/stock/engine/src/risk/portfolio.rs
Normal file
533
apps/stock/engine/src/risk/portfolio.rs
Normal file
|
|
@ -0,0 +1,533 @@
|
|||
use std::collections::HashMap;
|
||||
use nalgebra::{DMatrix, DVector};
|
||||
use crate::positions::Position;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PortfolioRisk {
|
||||
pub total_var_95: f64,
|
||||
pub total_var_99: f64,
|
||||
pub total_cvar_95: f64,
|
||||
pub marginal_var: HashMap<String, f64>,
|
||||
pub component_var: HashMap<String, f64>,
|
||||
pub correlation_matrix: CorrelationMatrix,
|
||||
pub concentration_risk: ConcentrationMetrics,
|
||||
pub stress_test_results: HashMap<String, f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CorrelationMatrix {
|
||||
pub symbols: Vec<String>,
|
||||
pub matrix: Vec<Vec<f64>>,
|
||||
pub average_correlation: f64,
|
||||
pub max_correlation: (String, String, f64),
|
||||
pub clustering_score: f64, // How clustered the portfolio is
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ConcentrationMetrics {
|
||||
pub herfindahl_index: f64,
|
||||
pub effective_number_of_positions: f64,
|
||||
pub top_5_concentration: f64,
|
||||
pub sector_concentration: HashMap<String, f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RiskModel {
|
||||
returns_history: HashMap<String, Vec<f64>>,
|
||||
lookback_period: usize,
|
||||
confidence_levels: Vec<f64>,
|
||||
}
|
||||
|
||||
impl RiskModel {
|
||||
pub fn new(lookback_period: usize) -> Self {
|
||||
Self {
|
||||
returns_history: HashMap::new(),
|
||||
lookback_period,
|
||||
confidence_levels: vec![0.95, 0.99],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_returns(&mut self, symbol: &str, returns: Vec<f64>) {
|
||||
self.returns_history.insert(symbol.to_string(), returns);
|
||||
}
|
||||
|
||||
pub fn calculate_portfolio_risk(
|
||||
&self,
|
||||
positions: &HashMap<String, Position>,
|
||||
current_prices: &HashMap<String, f64>,
|
||||
) -> Result<PortfolioRisk, String> {
|
||||
// Get active symbols and their weights
|
||||
let (symbols, weights) = self.get_portfolio_weights(positions, current_prices)?;
|
||||
|
||||
// Calculate covariance matrix
|
||||
let cov_matrix = self.calculate_covariance_matrix(&symbols)?;
|
||||
|
||||
// Portfolio variance
|
||||
let portfolio_variance = self.calculate_portfolio_variance(&weights, &cov_matrix);
|
||||
let portfolio_vol = portfolio_variance.sqrt();
|
||||
|
||||
// VaR calculations
|
||||
let total_portfolio_value = self.calculate_total_value(positions, current_prices);
|
||||
let total_var_95 = total_portfolio_value * portfolio_vol * 1.645; // 95% confidence
|
||||
let total_var_99 = total_portfolio_value * portfolio_vol * 2.326; // 99% confidence
|
||||
|
||||
// CVaR (Conditional VaR)
|
||||
let total_cvar_95 = self.calculate_cvar(&symbols, &weights, 0.95)?;
|
||||
|
||||
// Marginal and Component VaR
|
||||
let (marginal_var, component_var) = self.calculate_var_decomposition(
|
||||
&symbols,
|
||||
&weights,
|
||||
&cov_matrix,
|
||||
portfolio_vol,
|
||||
total_portfolio_value,
|
||||
)?;
|
||||
|
||||
// Correlation analysis
|
||||
let correlation_matrix = self.calculate_correlation_matrix(&symbols)?;
|
||||
|
||||
// Concentration metrics
|
||||
let concentration_risk = self.calculate_concentration_metrics(positions, current_prices);
|
||||
|
||||
// Stress tests
|
||||
let stress_test_results = self.run_stress_tests(positions, current_prices, &cov_matrix)?;
|
||||
|
||||
Ok(PortfolioRisk {
|
||||
total_var_95,
|
||||
total_var_99,
|
||||
total_cvar_95,
|
||||
marginal_var,
|
||||
component_var,
|
||||
correlation_matrix,
|
||||
concentration_risk,
|
||||
stress_test_results,
|
||||
})
|
||||
}
|
||||
|
||||
fn get_portfolio_weights(
|
||||
&self,
|
||||
positions: &HashMap<String, Position>,
|
||||
current_prices: &HashMap<String, f64>,
|
||||
) -> Result<(Vec<String>, DVector<f64>), String> {
|
||||
let mut symbols = Vec::new();
|
||||
let mut values = Vec::new();
|
||||
let mut total_value = 0.0;
|
||||
|
||||
for (symbol, position) in positions {
|
||||
if let Some(&price) = current_prices.get(symbol) {
|
||||
let position_value = position.quantity * price;
|
||||
symbols.push(symbol.clone());
|
||||
values.push(position_value.abs());
|
||||
total_value += position_value.abs();
|
||||
}
|
||||
}
|
||||
|
||||
if total_value == 0.0 {
|
||||
return Err("Portfolio has zero value".to_string());
|
||||
}
|
||||
|
||||
let weights = DVector::from_vec(values.iter().map(|v| v / total_value).collect());
|
||||
|
||||
Ok((symbols, weights))
|
||||
}
|
||||
|
||||
fn calculate_covariance_matrix(&self, symbols: &[String]) -> Result<DMatrix<f64>, String> {
|
||||
let n = symbols.len();
|
||||
let mut matrix = DMatrix::zeros(n, n);
|
||||
|
||||
for (i, symbol_i) in symbols.iter().enumerate() {
|
||||
for (j, symbol_j) in symbols.iter().enumerate() {
|
||||
if i <= j {
|
||||
let cov = self.calculate_covariance(symbol_i, symbol_j)?;
|
||||
matrix[(i, j)] = cov;
|
||||
matrix[(j, i)] = cov; // Symmetric
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(matrix)
|
||||
}
|
||||
|
||||
fn calculate_covariance(&self, symbol1: &str, symbol2: &str) -> Result<f64, String> {
|
||||
let returns1 = self.returns_history.get(symbol1)
|
||||
.ok_or_else(|| format!("No returns data for {}", symbol1))?;
|
||||
let returns2 = self.returns_history.get(symbol2)
|
||||
.ok_or_else(|| format!("No returns data for {}", symbol2))?;
|
||||
|
||||
if returns1.len() != returns2.len() {
|
||||
return Err("Mismatched returns length".to_string());
|
||||
}
|
||||
|
||||
let n = returns1.len() as f64;
|
||||
let mean1 = returns1.iter().sum::<f64>() / n;
|
||||
let mean2 = returns2.iter().sum::<f64>() / n;
|
||||
|
||||
let covariance = returns1.iter()
|
||||
.zip(returns2.iter())
|
||||
.map(|(r1, r2)| (r1 - mean1) * (r2 - mean2))
|
||||
.sum::<f64>() / (n - 1.0);
|
||||
|
||||
Ok(covariance)
|
||||
}
|
||||
|
||||
fn calculate_portfolio_variance(&self, weights: &DVector<f64>, cov_matrix: &DMatrix<f64>) -> f64 {
|
||||
let variance = weights.transpose() * cov_matrix * weights;
|
||||
variance[(0, 0)]
|
||||
}
|
||||
|
||||
fn calculate_var_decomposition(
|
||||
&self,
|
||||
symbols: &[String],
|
||||
weights: &DVector<f64>,
|
||||
cov_matrix: &DMatrix<f64>,
|
||||
portfolio_vol: f64,
|
||||
total_value: f64,
|
||||
) -> Result<(HashMap<String, f64>, HashMap<String, f64>), String> {
|
||||
let mut marginal_var = HashMap::new();
|
||||
let mut component_var = HashMap::new();
|
||||
|
||||
// Marginal VaR = ∂VaR/∂w_i
|
||||
let cov_weights = cov_matrix * weights;
|
||||
|
||||
for (i, symbol) in symbols.iter().enumerate() {
|
||||
let marginal = (cov_weights[i] / portfolio_vol) * 1.645 * total_value;
|
||||
let component = marginal * weights[i];
|
||||
|
||||
marginal_var.insert(symbol.clone(), marginal);
|
||||
component_var.insert(symbol.clone(), component);
|
||||
}
|
||||
|
||||
Ok((marginal_var, component_var))
|
||||
}
|
||||
|
||||
fn calculate_cvar(&self, symbols: &[String], weights: &DVector<f64>, confidence: f64) -> Result<f64, String> {
|
||||
// Simulate portfolio returns
|
||||
let portfolio_returns = self.simulate_portfolio_returns(symbols, weights, 10000)?;
|
||||
|
||||
// Sort returns
|
||||
let mut sorted_returns = portfolio_returns.clone();
|
||||
sorted_returns.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
|
||||
// Find VaR threshold
|
||||
let var_index = ((1.0 - confidence) * sorted_returns.len() as f64) as usize;
|
||||
let var_threshold = sorted_returns[var_index];
|
||||
|
||||
// Calculate expected loss beyond VaR
|
||||
let tail_losses: Vec<f64> = sorted_returns.iter()
|
||||
.take(var_index)
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if tail_losses.is_empty() {
|
||||
return Ok(0.0);
|
||||
}
|
||||
|
||||
let cvar = -tail_losses.iter().sum::<f64>() / tail_losses.len() as f64;
|
||||
|
||||
Ok(cvar)
|
||||
}
|
||||
|
||||
fn simulate_portfolio_returns(
|
||||
&self,
|
||||
symbols: &[String],
|
||||
weights: &DVector<f64>,
|
||||
num_simulations: usize,
|
||||
) -> Result<Vec<f64>, String> {
|
||||
let mut portfolio_returns = Vec::with_capacity(num_simulations);
|
||||
|
||||
// Use historical simulation
|
||||
let min_length = symbols.iter()
|
||||
.map(|s| self.returns_history.get(s).map(|r| r.len()).unwrap_or(0))
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
|
||||
if min_length == 0 {
|
||||
return Err("No returns data available".to_string());
|
||||
}
|
||||
|
||||
// Bootstrap from historical returns
|
||||
use rand::prelude::*;
|
||||
let mut rng = thread_rng();
|
||||
|
||||
for _ in 0..num_simulations {
|
||||
let idx = rng.gen_range(0..min_length);
|
||||
let mut portfolio_return = 0.0;
|
||||
|
||||
for (i, symbol) in symbols.iter().enumerate() {
|
||||
if let Some(returns) = self.returns_history.get(symbol) {
|
||||
portfolio_return += weights[i] * returns[idx];
|
||||
}
|
||||
}
|
||||
|
||||
portfolio_returns.push(portfolio_return);
|
||||
}
|
||||
|
||||
Ok(portfolio_returns)
|
||||
}
|
||||
|
||||
fn calculate_correlation_matrix(&self, symbols: &[String]) -> Result<CorrelationMatrix, String> {
|
||||
let n = symbols.len();
|
||||
let mut matrix = vec![vec![0.0; n]; n];
|
||||
let mut sum_correlation = 0.0;
|
||||
let mut count = 0;
|
||||
let mut max_correlation = ("".to_string(), "".to_string(), 0.0);
|
||||
|
||||
for (i, symbol_i) in symbols.iter().enumerate() {
|
||||
for (j, symbol_j) in symbols.iter().enumerate() {
|
||||
if i <= j {
|
||||
let corr = if i == j {
|
||||
1.0
|
||||
} else {
|
||||
self.calculate_correlation(symbol_i, symbol_j)?
|
||||
};
|
||||
|
||||
matrix[i][j] = corr;
|
||||
matrix[j][i] = corr;
|
||||
|
||||
if i != j {
|
||||
sum_correlation += corr.abs();
|
||||
count += 1;
|
||||
|
||||
if corr.abs() > max_correlation.2 {
|
||||
max_correlation = (symbol_i.clone(), symbol_j.clone(), corr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let average_correlation = if count > 0 {
|
||||
sum_correlation / count as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Calculate clustering score (higher = more clustered)
|
||||
let clustering_score = self.calculate_clustering_score(&matrix);
|
||||
|
||||
Ok(CorrelationMatrix {
|
||||
symbols: symbols.to_vec(),
|
||||
matrix,
|
||||
average_correlation,
|
||||
max_correlation,
|
||||
clustering_score,
|
||||
})
|
||||
}
|
||||
|
||||
fn calculate_correlation(&self, symbol1: &str, symbol2: &str) -> Result<f64, String> {
|
||||
let returns1 = self.returns_history.get(symbol1)
|
||||
.ok_or_else(|| format!("No returns data for {}", symbol1))?;
|
||||
let returns2 = self.returns_history.get(symbol2)
|
||||
.ok_or_else(|| format!("No returns data for {}", symbol2))?;
|
||||
|
||||
let cov = self.calculate_covariance(symbol1, symbol2)?;
|
||||
let std1 = self.calculate_std_dev(returns1);
|
||||
let std2 = self.calculate_std_dev(returns2);
|
||||
|
||||
if std1 == 0.0 || std2 == 0.0 {
|
||||
return Ok(0.0);
|
||||
}
|
||||
|
||||
Ok(cov / (std1 * std2))
|
||||
}
|
||||
|
||||
fn calculate_std_dev(&self, returns: &[f64]) -> f64 {
|
||||
let n = returns.len() as f64;
|
||||
let mean = returns.iter().sum::<f64>() / n;
|
||||
let variance = returns.iter()
|
||||
.map(|r| (r - mean).powi(2))
|
||||
.sum::<f64>() / (n - 1.0);
|
||||
|
||||
variance.sqrt()
|
||||
}
|
||||
|
||||
fn calculate_clustering_score(&self, correlation_matrix: &[Vec<f64>]) -> f64 {
|
||||
// Use average linkage clustering metric
|
||||
let n = correlation_matrix.len();
|
||||
if n < 2 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let mut cluster_sum = 0.0;
|
||||
let mut cluster_count = 0;
|
||||
|
||||
// Look for groups of highly correlated assets
|
||||
for i in 0..n {
|
||||
for j in i+1..n {
|
||||
for k in j+1..n {
|
||||
let corr_ij = correlation_matrix[i][j].abs();
|
||||
let corr_ik = correlation_matrix[i][k].abs();
|
||||
let corr_jk = correlation_matrix[j][k].abs();
|
||||
|
||||
// If all three are highly correlated, they form a cluster
|
||||
let min_corr = corr_ij.min(corr_ik).min(corr_jk);
|
||||
if min_corr > 0.5 {
|
||||
cluster_sum += min_corr;
|
||||
cluster_count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if cluster_count > 0 {
|
||||
cluster_sum / cluster_count as f64
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_concentration_metrics(
|
||||
&self,
|
||||
positions: &HashMap<String, Position>,
|
||||
current_prices: &HashMap<String, f64>,
|
||||
) -> ConcentrationMetrics {
|
||||
let mut position_values: Vec<(String, f64)> = Vec::new();
|
||||
let mut total_value = 0.0;
|
||||
|
||||
for (symbol, position) in positions {
|
||||
if let Some(&price) = current_prices.get(symbol) {
|
||||
let value = (position.quantity * price).abs();
|
||||
position_values.push((symbol.clone(), value));
|
||||
total_value += value;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by value descending
|
||||
position_values.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
|
||||
|
||||
// Herfindahl Index
|
||||
let herfindahl_index = position_values.iter()
|
||||
.map(|(_, value)| {
|
||||
let weight = value / total_value;
|
||||
weight * weight
|
||||
})
|
||||
.sum();
|
||||
|
||||
// Effective number of positions
|
||||
let effective_number_of_positions = if herfindahl_index > 0.0 {
|
||||
1.0 / herfindahl_index
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Top 5 concentration
|
||||
let top_5_value: f64 = position_values.iter()
|
||||
.take(5)
|
||||
.map(|(_, value)| value)
|
||||
.sum();
|
||||
let top_5_concentration = top_5_value / total_value;
|
||||
|
||||
// Sector concentration (simplified - would need sector mapping)
|
||||
let sector_concentration = HashMap::new(); // TODO: Implement with sector data
|
||||
|
||||
ConcentrationMetrics {
|
||||
herfindahl_index,
|
||||
effective_number_of_positions,
|
||||
top_5_concentration,
|
||||
sector_concentration,
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_total_value(
|
||||
&self,
|
||||
positions: &HashMap<String, Position>,
|
||||
current_prices: &HashMap<String, f64>,
|
||||
) -> f64 {
|
||||
positions.iter()
|
||||
.filter_map(|(symbol, position)| {
|
||||
current_prices.get(symbol).map(|&price| (position.quantity * price).abs())
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn run_stress_tests(
|
||||
&self,
|
||||
positions: &HashMap<String, Position>,
|
||||
current_prices: &HashMap<String, f64>,
|
||||
cov_matrix: &DMatrix<f64>,
|
||||
) -> Result<HashMap<String, f64>, String> {
|
||||
let mut results = HashMap::new();
|
||||
|
||||
// Market crash scenario
|
||||
let market_crash_loss = self.calculate_scenario_loss(
|
||||
positions,
|
||||
current_prices,
|
||||
-0.20, // 20% market drop
|
||||
);
|
||||
results.insert("market_crash_20pct".to_string(), market_crash_loss);
|
||||
|
||||
// Flight to quality
|
||||
let flight_to_quality = self.calculate_correlation_stress(
|
||||
positions,
|
||||
current_prices,
|
||||
cov_matrix,
|
||||
0.9, // High correlation scenario
|
||||
)?;
|
||||
results.insert("flight_to_quality".to_string(), flight_to_quality);
|
||||
|
||||
// Volatility spike
|
||||
let vol_spike = self.calculate_volatility_stress(
|
||||
positions,
|
||||
current_prices,
|
||||
cov_matrix,
|
||||
2.0, // Double volatility
|
||||
)?;
|
||||
results.insert("volatility_spike_2x".to_string(), vol_spike);
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
fn calculate_scenario_loss(
|
||||
&self,
|
||||
positions: &HashMap<String, Position>,
|
||||
current_prices: &HashMap<String, f64>,
|
||||
shock: f64,
|
||||
) -> f64 {
|
||||
let current_value = self.calculate_total_value(positions, current_prices);
|
||||
current_value * shock.abs()
|
||||
}
|
||||
|
||||
fn calculate_correlation_stress(
|
||||
&self,
|
||||
positions: &HashMap<String, Position>,
|
||||
current_prices: &HashMap<String, f64>,
|
||||
cov_matrix: &DMatrix<f64>,
|
||||
target_correlation: f64,
|
||||
) -> Result<f64, String> {
|
||||
// Adjust correlation matrix to stress scenario
|
||||
let n = cov_matrix.nrows();
|
||||
let mut stressed_cov = cov_matrix.clone();
|
||||
|
||||
for i in 0..n {
|
||||
for j in 0..n {
|
||||
if i != j {
|
||||
let current_corr = cov_matrix[(i, j)] / (cov_matrix[(i, i)].sqrt() * cov_matrix[(j, j)].sqrt());
|
||||
let stress_factor = target_correlation / current_corr.abs().max(0.1);
|
||||
stressed_cov[(i, j)] *= stress_factor;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (_, weights) = self.get_portfolio_weights(positions, current_prices)?;
|
||||
let stressed_variance = self.calculate_portfolio_variance(&weights, &stressed_cov);
|
||||
let stressed_vol = stressed_variance.sqrt();
|
||||
|
||||
Ok(self.calculate_total_value(positions, current_prices) * stressed_vol * 2.326) // 99% VaR
|
||||
}
|
||||
|
||||
fn calculate_volatility_stress(
|
||||
&self,
|
||||
positions: &HashMap<String, Position>,
|
||||
current_prices: &HashMap<String, f64>,
|
||||
cov_matrix: &DMatrix<f64>,
|
||||
vol_multiplier: f64,
|
||||
) -> Result<f64, String> {
|
||||
let stressed_cov = cov_matrix * vol_multiplier.powi(2);
|
||||
let (_, weights) = self.get_portfolio_weights(positions, current_prices)?;
|
||||
let stressed_variance = self.calculate_portfolio_variance(&weights, &stressed_cov);
|
||||
let stressed_vol = stressed_variance.sqrt();
|
||||
|
||||
Ok(self.calculate_total_value(positions, current_prices) * stressed_vol * 2.326) // 99% VaR
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue