240 lines
7.7 KiB
Rust
240 lines
7.7 KiB
Rust
pub mod bet_sizing;
|
|
pub mod portfolio;
|
|
use crate::{Order, Side};
|
|
pub use bet_sizing::{BetSizer, BetSizingParameters, DynamicSizer, MarketRegime, PositionSize};
|
|
use dashmap::DashMap;
|
|
use parking_lot::RwLock;
|
|
pub use portfolio::{ConcentrationMetrics, CorrelationMatrix, PortfolioRisk, RiskModel};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::sync::Arc;
|
|
|
|
#[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 RiskLimits {
|
|
pub fn valid(&self) -> bool {
|
|
[
|
|
self.max_position_size,
|
|
self.max_order_size,
|
|
self.max_daily_loss,
|
|
self.max_gross_exposure,
|
|
self.max_symbol_exposure,
|
|
]
|
|
.iter()
|
|
.all(|v| v.is_finite() && *v > 0.0)
|
|
}
|
|
}
|
|
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,
|
|
}
|
|
|
|
/// Position/order size limits are shares; exposure/loss limits are currency notional.
|
|
pub struct RiskEngine {
|
|
limits: Arc<RwLock<RiskLimits>>,
|
|
positions: DashMap<String, (f64, f64)>,
|
|
daily_pnl: Arc<RwLock<f64>>,
|
|
day: RwLock<Option<chrono::NaiveDate>>,
|
|
}
|
|
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)),
|
|
positions: DashMap::new(),
|
|
day: RwLock::new(None),
|
|
daily_pnl: Arc::new(RwLock::new(0.0)),
|
|
}
|
|
}
|
|
pub fn update_limits(&self, limits: RiskLimits) {
|
|
*self.limits.write() = limits;
|
|
}
|
|
pub fn check_order(
|
|
&self,
|
|
order: &Order,
|
|
current_position: Option<f64>,
|
|
price: f64,
|
|
) -> RiskCheckResult {
|
|
let limits = self.limits.read();
|
|
let current = current_position.unwrap_or(0.0);
|
|
let signed = if order.side == Side::Buy {
|
|
order.quantity
|
|
} else {
|
|
-order.quantity
|
|
};
|
|
let next = current + signed;
|
|
let reducing = current * signed < 0.0 && order.quantity <= current.abs();
|
|
let valid = limits.valid()
|
|
&& order.quantity.is_finite()
|
|
&& order.quantity > 0.0
|
|
&& current.is_finite()
|
|
&& price.is_finite()
|
|
&& price > 0.0;
|
|
let other_gross: f64 = self
|
|
.positions
|
|
.iter()
|
|
.filter(|p| p.key() != &order.symbol)
|
|
.map(|p| p.value().0.abs() * p.value().1)
|
|
.sum();
|
|
let exposure = next.abs() * price;
|
|
let gross = other_gross + exposure;
|
|
let checks = RiskChecks {
|
|
order_size: valid && order.quantity <= limits.max_order_size,
|
|
position_size: valid && (next.abs() <= limits.max_position_size || reducing),
|
|
daily_loss: valid && (*self.daily_pnl.read() > -limits.max_daily_loss || reducing),
|
|
gross_exposure: valid && (gross <= limits.max_gross_exposure || reducing),
|
|
symbol_exposure: valid && (exposure <= limits.max_symbol_exposure || reducing),
|
|
};
|
|
let mut violations = Vec::new();
|
|
for (passed, label) in [
|
|
(checks.order_size, "Order size/validity"),
|
|
(checks.position_size, "Projected position size"),
|
|
(checks.daily_loss, "Daily loss"),
|
|
(checks.gross_exposure, "Projected gross notional"),
|
|
(checks.symbol_exposure, "Projected symbol notional"),
|
|
] {
|
|
if !passed {
|
|
violations.push(label.to_string());
|
|
}
|
|
}
|
|
RiskCheckResult {
|
|
passed: violations.is_empty(),
|
|
violations,
|
|
checks,
|
|
}
|
|
}
|
|
pub fn update_position(&self, symbol: &str, quantity: f64, price: f64) {
|
|
if quantity.abs() < 1e-8 {
|
|
self.positions.remove(symbol);
|
|
} else {
|
|
self.positions.insert(symbol.to_string(), (quantity, price));
|
|
}
|
|
}
|
|
pub fn mark_price(&self, symbol: &str, price: f64) {
|
|
if let Some(mut p) = self.positions.get_mut(symbol) {
|
|
if price.is_finite() && price > 0.0 {
|
|
p.1 = price;
|
|
}
|
|
}
|
|
}
|
|
pub fn update_daily_pnl(&self, change: f64) {
|
|
*self.daily_pnl.write() += change;
|
|
}
|
|
pub fn roll_day(&self, day: chrono::NaiveDate) {
|
|
let mut previous = self.day.write();
|
|
if previous.map(|p| day > p).unwrap_or(true) {
|
|
self.reset_daily_metrics();
|
|
*previous = Some(day);
|
|
}
|
|
}
|
|
pub fn reset_daily_metrics(&self) {
|
|
*self.daily_pnl.write() = 0.0;
|
|
}
|
|
fn calculate_gross_exposure(&self) -> f64 {
|
|
self.positions
|
|
.iter()
|
|
.map(|p| p.value().0.abs() * p.value().1)
|
|
.sum()
|
|
}
|
|
pub fn get_risk_metrics(&self) -> RiskMetrics {
|
|
let limits = self.limits.read();
|
|
let gross = self.calculate_gross_exposure();
|
|
RiskMetrics {
|
|
current_exposure: gross,
|
|
daily_pnl: *self.daily_pnl.read(),
|
|
position_count: self.positions.len(),
|
|
gross_exposure: gross,
|
|
max_position_size: limits.max_position_size,
|
|
utilization_pct: gross / limits.max_gross_exposure * 100.0,
|
|
}
|
|
}
|
|
}
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
fn order(side: Side, quantity: f64) -> Order {
|
|
Order {
|
|
id: "test".into(),
|
|
symbol: "A".into(),
|
|
side,
|
|
quantity,
|
|
order_type: crate::OrderType::Market,
|
|
time_in_force: crate::TimeInForce::Day,
|
|
}
|
|
}
|
|
fn engine() -> RiskEngine {
|
|
RiskEngine::with_limits(RiskLimits {
|
|
max_position_size: 100.0,
|
|
max_order_size: 100.0,
|
|
max_daily_loss: 10.0,
|
|
max_gross_exposure: 1000.0,
|
|
max_symbol_exposure: 800.0,
|
|
})
|
|
}
|
|
#[test]
|
|
fn projected_notional_includes_new_order_and_other_symbols() {
|
|
let risk = engine();
|
|
risk.update_position("B", 5.0, 100.0);
|
|
assert!(!risk.check_order(&order(Side::Buy, 6.0), None, 100.0).passed);
|
|
assert!(risk.check_order(&order(Side::Buy, 5.0), None, 100.0).passed);
|
|
assert!(
|
|
!risk
|
|
.check_order(&order(Side::Buy, 1.0), None, f64::NAN)
|
|
.passed
|
|
);
|
|
}
|
|
#[test]
|
|
fn covers_reduce_short_exposure_and_daily_loss_blocks_new_risk() {
|
|
let risk = engine();
|
|
risk.update_position("A", -8.0, 100.0);
|
|
risk.update_daily_pnl(-10.0);
|
|
assert!(
|
|
risk.check_order(&order(Side::Buy, 8.0), Some(-8.0), 100.0)
|
|
.passed
|
|
);
|
|
assert!(
|
|
!risk
|
|
.check_order(&order(Side::Sell, 1.0), Some(-8.0), 100.0)
|
|
.passed
|
|
);
|
|
risk.mark_price("A", 120.0);
|
|
assert_eq!(risk.get_risk_metrics().gross_exposure, 960.0);
|
|
}
|
|
}
|