Risk Management
๐ฅ Vibe Prompt
"Calculate Sharpe Ratio, Sortino Ratio, Calmar Ratio, Max Drawdown, and Kelly Criterion for a trading strategy. Explain what each metric means."
Key Risk Metrics
Sharpe Ratio
$$\text{Sharpe} = \frac{R_p - R_f}{\sigma_p}$$
- Measures risk-adjusted return
-
1: Good, > 2: Great, > 3: Excellent
Sortino Ratio (downside risk only)
$$\text{Sortino} = \frac{R_p - R_f}{\sigma_d}$$
- Only penalizes negative volatility
Max Drawdown
$$\text{Max DD} = \min(\frac{\text{Valley} - \text{Peak}}{\text{Peak}})$$
- Largest peak-to-trough decline
def calculate_metrics(returns, risk_free_rate=0.02):
"""Calculate comprehensive risk metrics"""
cumulative = (1 + returns).cumprod()
# Sharpe
excess_returns = returns - risk_free_rate / 252
sharpe = excess_returns.mean() / excess_returns.std() * (252 ** 0.5)
# Max Drawdown
rolling_max = cumulative.expanding().max()
drawdown = (cumulative - rolling_max) / rolling_max
max_dd = drawdown.min()
# Calmar Ratio
calmar = cumulative.iloc[-1] / abs(max_dd)
return {
'Sharpe Ratio': sharpe,
'Max Drawdown': max_dd,
'Calmar Ratio': calmar,
'Total Return': cumulative.iloc[-1] - 1
}
# Example
returns = pd.Series([0.01, -0.005, 0.02, 0.015, -0.01, 0.03])
metrics = calculate_metrics(returns)
for k, v in metrics.items():
print(f"{k}: {v:.4f}")
Kelly Criterion
$$f^* = \frac{bp - q}{b}$$
def kelly_criterion(win_rate, avg_win, avg_loss):
b = avg_win / abs(avg_loss) # win/loss ratio
p = win_rate
q = 1 - p
f = (b * p - q) / b
return max(0, min(f, 0.25)) # Cap at 25%
# Example
position_size = kelly_criterion(0.55, 200, 100)
print(f"Recommended position: {position_size:.1%} of capital")
Practice Exercise
๐ก Vibe Practice: Ask AI to build a risk dashboard that tracks real-time Sharpe, Drawdown, and VaR for a trading portfolio.
Chapter Summary
- Understand core concepts and principles
- Master implementation methods and techniques
- Familiar with common issues and solutions
- Able to apply in real projects
Further Reading
- Official documentation and API references
- Open source examples on GitHub
- Technical books and online courses
- Community discussions and tech blogs
Implementation Example
Basic Example
# This section provides a complete implementation example
Steps
- Setup: Configure development environment
- Data: Prepare required data
- Implementation: Build core functionality
- Testing: Verify correctness
- Optimization: Improve performance
Common Errors
| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |
Code Example
import sys
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
References
- Official documentation
- API reference
- Open source examples
- Community discussions