Some checks are pending
Documentation / build-docs (push) Waiting to run
Tests / test (macos-latest, 3.11) (push) Waiting to run
Tests / test (macos-latest, 3.12) (push) Waiting to run
Tests / test (macos-latest, 3.13) (push) Waiting to run
Tests / test (macos-latest, 3.14) (push) Waiting to run
Tests / test (ubuntu-latest, 3.11) (push) Waiting to run
Tests / test (ubuntu-latest, 3.12) (push) Waiting to run
Tests / test (ubuntu-latest, 3.13) (push) Waiting to run
Tests / test (ubuntu-latest, 3.14) (push) Waiting to run
281 lines
7.1 KiB
Markdown
281 lines
7.1 KiB
Markdown
# Risk Management Architecture
|
||
|
||
## Overview
|
||
|
||
The risk management system provides comprehensive risk control mechanisms including position sizing, stop-loss management, drawdown limits, Value at Risk (VaR) calculation, and portfolio correlation analysis.
|
||
|
||
## Components
|
||
|
||
### Position Sizing
|
||
|
||
**Location**: `src/risk/position_sizing.py`
|
||
|
||
**Methods**:
|
||
- **Standard Position Sizing**: Percentage-based with fee accounting
|
||
- **Kelly Criterion**: Optimal position sizing with fractional Kelly (configurable)
|
||
- **Volatility-Adjusted**: ATR-based position sizing (lower vol = larger positions)
|
||
- **Regime-Aware**: Adjusts position size based on market regime
|
||
- **Confidence-Based**: ML model confidence-adjusted position sizing
|
||
|
||
**Usage**:
|
||
```python
|
||
from src.risk.position_sizing import PositionSizingManager
|
||
|
||
sizer = PositionSizingManager()
|
||
|
||
# Standard sizing
|
||
quantity = sizer.calculate_size(symbol, price, balance, risk_percent)
|
||
|
||
# Kelly Criterion (fractional)
|
||
kelly_pct = sizer.calculate_kelly_criterion(win_rate=0.6, avg_win=100, avg_loss=50, fractional=0.25)
|
||
|
||
# Volatility-adjusted
|
||
quantity = sizer.calculate_volatility_adjusted_size(symbol, price, balance, volatility_multiplier=0.8)
|
||
|
||
# Regime-aware
|
||
quantity = sizer.calculate_regime_aware_size(symbol, price, balance, market_regime="trending_up")
|
||
```
|
||
|
||
### Value at Risk (VaR)
|
||
|
||
**Location**: `src/risk/var_calculator.py`
|
||
|
||
**Methods**:
|
||
1. **Historical VaR**: Uses historical portfolio returns distribution
|
||
2. **Parametric VaR**: Assumes normal distribution (variance-covariance method)
|
||
3. **Monte Carlo VaR**: Simulates future returns using estimated parameters
|
||
4. **Conditional VaR (CVaR)**: Expected loss given that loss exceeds VaR
|
||
|
||
**Usage**:
|
||
```python
|
||
from src.risk.var_calculator import get_var_calculator
|
||
|
||
var_calc = get_var_calculator()
|
||
|
||
# Calculate all methods
|
||
results = await var_calc.calculate_all_var_methods(
|
||
portfolio_value=Decimal("10000.0"),
|
||
confidence_level=0.95,
|
||
holding_period_days=1
|
||
)
|
||
|
||
# Individual methods
|
||
historical_var = await var_calc.calculate_historical_var(...)
|
||
parametric_var = await var_calc.calculate_parametric_var(...)
|
||
monte_carlo_var = await var_calc.calculate_monte_carlo_var(...)
|
||
cvar = await var_calc.calculate_cvar(...)
|
||
```
|
||
|
||
### Portfolio Correlation Analysis
|
||
|
||
**Location**: `src/portfolio/correlation_analyzer.py`
|
||
|
||
**Features**:
|
||
- Correlation matrix calculation for portfolio symbols
|
||
- Diversification scoring (lower correlation = better)
|
||
- Concentration risk analysis
|
||
- Correlation-based position limits
|
||
|
||
**Usage**:
|
||
```python
|
||
from src.portfolio.correlation_analyzer import get_correlation_analyzer
|
||
|
||
analyzer = get_correlation_analyzer()
|
||
|
||
# Analyze current portfolio
|
||
analysis = await analyzer.analyze_portfolio_correlation(paper_trading=True)
|
||
|
||
# Check correlation limits before adding position
|
||
allowed, reason = await analyzer.check_correlation_limits(
|
||
symbol="ETH/USD",
|
||
new_position_value=Decimal("1000.0"),
|
||
max_correlation=0.8
|
||
)
|
||
```
|
||
|
||
### Stop-Loss Management
|
||
|
||
**Location**: `src/risk/stop_loss.py`
|
||
|
||
Provides dynamic stop-loss adjustment and management.
|
||
|
||
### Risk Limits
|
||
|
||
**Location**: `src/risk/limits.py`
|
||
|
||
Manages:
|
||
- Daily loss limits
|
||
- Maximum drawdown limits
|
||
- Portfolio allocation limits
|
||
|
||
### Risk Manager
|
||
|
||
**Location**: `src/risk/manager.py`
|
||
|
||
Orchestrates all risk management components and provides unified risk checking interface.
|
||
|
||
|
||
This document describes the risk management system.
|
||
|
||
## Risk Management Components
|
||
|
||
```
|
||
Risk Manager
|
||
├──► Pre-Trade Checks
|
||
│ │
|
||
│ ├──► Position Sizing
|
||
│ ├──► Daily Loss Limit
|
||
│ └──► Portfolio Allocation
|
||
│
|
||
├──► Real-Time Monitoring
|
||
│ │
|
||
│ ├──► Drawdown Monitoring
|
||
│ ├──► Position Monitoring
|
||
│ └──► Portfolio Monitoring
|
||
│
|
||
└──► Stop Loss Management
|
||
│
|
||
├──► Stop Loss Orders
|
||
└──► Trailing Stops
|
||
```
|
||
|
||
## Pre-Trade Risk Checks
|
||
|
||
Before executing any trade:
|
||
|
||
1. **Position Sizing Check**
|
||
- Verify position size within limits
|
||
- Check portfolio allocation
|
||
- Validate against risk parameters
|
||
|
||
2. **Daily Loss Limit Check**
|
||
- Calculate current daily P&L
|
||
- Compare against daily loss limit
|
||
- Block trades if limit exceeded
|
||
|
||
3. **Drawdown Check**
|
||
- Calculate current drawdown
|
||
- Compare against max drawdown limit
|
||
- Block trades if limit exceeded
|
||
|
||
4. **Portfolio Allocation Check**
|
||
- Verify total exposure within limits
|
||
- Check per-asset allocation
|
||
- Validate diversification requirements
|
||
|
||
## Position Sizing Methods
|
||
|
||
### Fixed Percentage
|
||
|
||
```python
|
||
position_size = capital * percentage
|
||
```
|
||
|
||
### Kelly Criterion
|
||
|
||
```python
|
||
f = (bp - q) / b
|
||
position_size = capital * f
|
||
```
|
||
|
||
### Volatility-Based
|
||
|
||
```python
|
||
position_size = (capital * risk_percentage) / (stop_loss_distance * price)
|
||
```
|
||
|
||
## Risk Limits
|
||
|
||
Configurable limits:
|
||
|
||
- **Max Drawdown**: Maximum allowed drawdown percentage
|
||
- **Daily Loss Limit**: Maximum daily loss percentage
|
||
- **Position Size Limit**: Maximum position value
|
||
- **Portfolio Exposure**: Maximum portfolio exposure percentage
|
||
|
||
## Stop Loss Management
|
||
|
||
### Stop Loss Types
|
||
|
||
- **Fixed Stop Loss**: Fixed price level
|
||
- **Trailing Stop**: Adjusts with price movement
|
||
- Percentage-based: Adjusts by fixed percentage
|
||
- ATR-based: Adjusts based on volatility (Average True Range)
|
||
- **Percentage Stop**: Percentage below entry
|
||
- **ATR-based Stop**: Based on Average True Range (volatility-adjusted)
|
||
- Automatically calculates stop distance using ATR multiplier
|
||
- Adapts to market volatility conditions
|
||
- Configurable ATR period (default: 14) and multiplier (default: 2.0)
|
||
- Works with both fixed and trailing stops
|
||
|
||
### ATR-Based Dynamic Stops
|
||
|
||
ATR-based stops provide better risk management in volatile markets:
|
||
|
||
```python
|
||
stop_loss_manager.set_stop_loss(
|
||
position_id=1,
|
||
stop_price=entry_price,
|
||
use_atr=True,
|
||
atr_multiplier=Decimal('2.0'),
|
||
atr_period=14,
|
||
ohlcv_data=market_data,
|
||
trailing=True
|
||
)
|
||
```
|
||
|
||
**Benefits:**
|
||
- Adapts to market volatility
|
||
- Tighter stops in low volatility, wider in high volatility
|
||
- Reduces stop-outs during normal market noise
|
||
- Better risk-adjusted returns
|
||
|
||
**Calculation:**
|
||
- Stop distance = ATR × multiplier
|
||
- For long positions: stop_price = entry_price - (ATR × multiplier)
|
||
- For short positions: stop_price = entry_price + (ATR × multiplier)
|
||
|
||
### Stop Loss Execution
|
||
|
||
```
|
||
Price Update
|
||
│
|
||
▼
|
||
Stop Loss Check
|
||
│
|
||
├──► Stop Loss Triggered?
|
||
│ │
|
||
│ └──► Execute Market Sell
|
||
│
|
||
└──► Update Trailing Stop (if applicable)
|
||
```
|
||
|
||
## Real-Time Monitoring
|
||
|
||
Continuous monitoring of:
|
||
|
||
- Portfolio value
|
||
- Unrealized P&L
|
||
- Drawdown levels
|
||
- Position sizes
|
||
- Risk metrics
|
||
|
||
## Risk Alerts
|
||
|
||
Automatic alerts for:
|
||
|
||
- Drawdown threshold exceeded
|
||
- Daily loss limit reached
|
||
- Position size exceeded
|
||
- Portfolio exposure exceeded
|
||
|
||
## Integration Points
|
||
|
||
Risk management integrates with:
|
||
|
||
- **Trading Engine**: Pre-trade validation
|
||
- **Order Manager**: Position tracking
|
||
- **Portfolio Tracker**: Real-time monitoring
|
||
- **Alert System**: Risk alerts
|
||
|