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

  1. Setup: Configure development environment
  2. Data: Prepare required data
  3. Implementation: Build core functionality
  4. Testing: Verify correctness
  5. 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

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!