Risk management is not optional - it's the difference between long-term success and inevitable ruin. The best predictive models are worthless without proper risk controls.
Never allocate too much capital to a single position
Automatic exit when losses reach predetermined threshold
class StopLossManager:
def __init__(self, stop_pct=0.02):
self.stop_pct = stop_pct # 2% stop loss
def set_stop_loss(self, entry_price, direction):
"""Calculate stop loss price"""
if direction == 'long':
return entry_price * (1 - self.stop_pct)
else: # short
return entry_price * (1 + self.stop_pct)
def check_stop(self, current_price, stop_price, direction):
"""Check if stop loss triggered"""
if direction == 'long':
return current_price <= stop_price
else:
return current_price >= stop_price
Lock in profits as position moves in your favor
Maximum expected loss at given confidence level
def calculate_var(returns, confidence=0.95):
"""Calculate Value at Risk"""
return np.percentile(returns, (1 - confidence) * 100)
# Example: 95% VaR = -2.5% daily loss
# Interpretation: 95% chance daily loss won't exceed 2.5%
Expected loss given that VaR threshold is exceeded
def calculate_cvar(returns, confidence=0.95):
"""Calculate Conditional VaR (Expected Shortfall)"""
var = calculate_var(returns, confidence)
return returns[returns <= var].mean()
# CVaR is always worse than VaR
# Accounts for tail risk beyond VaR threshold
def calculate_leverage_ratio(portfolio_value, gross_exposure):
"""Calculate current leverage"""
return gross_exposure / portfolio_value
def max_safe_leverage(volatility, max_drawdown_tolerance=0.20):
"""Calculate maximum safe leverage given volatility"""
# Higher volatility = lower safe leverage
return max_drawdown_tolerance / (2 * volatility)
# Example: 15% annual vol → max 0.67x leverage for 20% drawdown limit
def portfolio_diversification_ratio(weights, corr_matrix):
"""Measure portfolio diversification"""
# Higher = more diversified
weighted_vol = (weights @ corr_matrix @ weights) ** 0.5
sum_vols = weights.sum()
return sum_vols / weighted_vol
Automated safety mechanisms that halt trading under adverse conditions
class CircuitBreaker:
def __init__(self, daily_loss_limit=0.05, max_drawdown=0.15):
self.daily_loss_limit = daily_loss_limit
self.max_drawdown = max_drawdown
self.trading_enabled = True
def check(self, daily_pnl, current_drawdown):
"""Check if circuit breakers triggered"""
if daily_pnl < -self.daily_loss_limit:
self.trading_enabled = False
return "HALT: Daily loss limit exceeded"
if current_drawdown < -self.max_drawdown:
self.trading_enabled = False
return "HALT: Maximum drawdown exceeded"
return "OK"
Test strategy performance under extreme market conditions
Real-time monitoring is essential for active risk management