Risk Management & Real Cases

Options are high-leverage instruments โ€” they can make you rich overnight or wipe you out just as fast. Risk management matters more than trading strategy.

๐Ÿ”ฅ Vibe Prompt

"Build an options risk management system: Kelly Criterion position sizing, scenario analysis and stress testing, Greek hedging strategies, and three real market cases (TSLA earnings, VIX panic, market crash hedge)."

Risk Management Principles

| Principle | Description | |-----------|-------------| | 1% Rule | Single trade risk โ‰ค 1% of capital | | Max Leverage | Option leverage โ‰ค 5x | | Diversify Expiry | Don't expire all positions at same time | | Delta Hedge | Keep portfolio Delta neutral | | Stop Loss | Set max loss for each trade |

Real Cases

Case 1: TSLA Earnings

  • Situation: IV spiked to 80%+ before earnings
  • Strategy: Sell Iron Condor to collect high volatility premium
  • Result: Volatility collapsed after earnings, Iron Condor profitable
  • Lesson: High volatility environments favor option sellers

Case 2: VIX Panic

  • Situation: VIX surged from 15 to 40
  • Strategy: Buy VIX Calls or VIX futures
  • Result: Options prices exploded during panic
  • Lesson: Black swan events favor option buyers

Case 3: Market Crash Hedge

  • Situation: March 2020 COVID-19 crash
  • Strategy: Buy OTM Puts as protective puts
  • Result: Stock losses offset by Put gains
  • Lesson: Options are the best insurance tool

Practice Exercise

๐Ÿ’ก Vibe Coding Practice: Ask AI to build an "Options Risk Management Dashboard":

  1. Kelly Criterion position size calculator
  2. Multi-scenario P&L simulation
  3. Delta hedge recommendation generator
  4. Portfolio Greeks overview
  5. VaR (Value at Risk) calculator
  6. Stop-loss and alert system

Visualizing Option Prices

import matplotlib.pyplot as plt
import numpy as np

stock_prices = np.linspace(50, 150, 100)
prices = [black_scholes(S, 100, 0.5, 0.05, 0.2, 'call') for S in stock_prices]
plt.plot(stock_prices, prices)
plt.axvline(100, color='gray', linestyle='--', alpha=0.5)
plt.title('Call Option Price vs Stock Price')
plt.xlabel('Stock Price')
plt.ylabel('Option Price')
plt.grid(True, alpha=0.3)
plt.show()

Common Issues & Solutions

| Problem | Cause | Solution | |---------|-------|----------| | Unexpected results | Wrong parameters | Check defaults and edge cases | | Slow execution | Inefficient algorithm | Use better data structures | | Out of memory | Too much data | Use batch processing | | Hard to debug | No logging | Add detailed logging |

Further Learning

  • Read official documentation
  • Browse open-source examples on GitHub
  • Join community discussions
  • Practice by modifying code and observing results

Performance Considerations

When working with large datasets or complex computations:

  1. Time Complexity: Analyze and optimize Big O
  2. Space Complexity: Balance memory vs speed
  3. Caching: Store computed results to avoid recalculation
  4. Parallelism: Use multi-threading for independent tasks
  5. Profiling: Measure before optimizing - use profilers

Real-World Application

This concept is widely used in:

  • Web development (routing, authentication)
  • Data science (feature engineering, model training)
  • Game development (pathfinding, physics)
  • Mobile apps (state management, caching)

Position Sizing

Position sizing determines how much capital to allocate to each trade.

Fixed Percentage Method

class PositionSizer:
    def __init__(self, total_capital: float, risk_per_trade: float = 0.02):
        """
        total_capital: Total account value
        risk_per_trade: Maximum risk per trade (2% default)
        """
        self.total_capital = total_capital
        self.risk_per_trade = risk_per_trade
    
    def calculate_position(self, entry_price: float, stop_loss: float) -> dict:
        """Calculate position size based on risk."""
        risk_amount = self.total_capital * self.risk_per_trade
        risk_per_share = entry_price - stop_loss
        
        if risk_per_share <= 0:
            return {"error": "Stop loss must be below entry"}
        
        shares = int(risk_amount / risk_per_share)
        position_value = shares * entry_price
        
        return {
            "shares": shares,
            "position_value": position_value,
            "risk_amount": risk_amount,
            "risk_percentage": self.risk_per_trade * 100
        }

# Example
sizer = PositionSizer(total_capital=100000, risk_per_trade=0.02)
result = sizer.calculate_position(entry_price=50.0, stop_loss=48.0)
print(f"Buy {result['shares']} shares at ${result['position_value']:.2f}")

Kelly Criterion

$$f^* = \frac{bp - q}{b} = \frac{p(b + 1) - 1}{b}$$

Where:

  • $f^*$ = fraction of capital to bet
  • $p$ = probability of winning
  • $q$ = probability of losing ($1 - p$)
  • $b$ = net odds received on the bet
def kelly_criterion(win_rate: float, avg_win: float, avg_loss: float) -> float:
    """Calculate optimal bet size using Kelly Criterion."""
    b = avg_win / abs(avg_loss)
    p = win_rate
    q = 1 - p
    
    f_star = (b * p - q) / b
    # Use fractional Kelly (25%) for safety
    return max(0, f_star * 0.25)

# Example: 55% win rate, avg win $200, avg loss $100
fraction = kelly_criterion(0.55, 200, 100)
print(f"Suggested position: {fraction:.1%} of capital")

Stop Loss Strategies

| Strategy | Description | Best For | |----------|-------------|----------| | Fixed % | Exit if loss exceeds X% of position | Simple, consistent | | ATR-Based | Exit at 2ร— ATR from entry | Adapts to volatility | | Technical | Exit below support / above resistance | Chart patterns | | Time Stop | Exit after N days | Earnings plays | | Trailing | Stop moves up with price | Trending markets |

ATR-Based Stop

def atr_stop(entry_price: float, atr: float, multiplier: float = 2.0, direction: str = "long"):
    """Calculate stop loss based on Average True Range."""
    if direction == "long":
        stop = entry_price - (atr * multiplier)
    else:
        stop = entry_price + (atr * multiplier)
    return stop

Portfolio Hedging

Protective Put

def protective_put(portfolio_value: float, index_price: float, protection_pct: float = 0.05):
    """Hedge portfolio with index puts."""
    # Buy puts covering portfolio value
    notional = portfolio_value
    contracts = int(notional / (index_price * 100))
    
    # Choose strike ~5% below current price
    strike = index_price * (1 - protection_pct)
    
    return {
        "contracts": contracts,
        "strike": strike,
        "protection_pct": protection_pct,
        "notional_covered": contracts * index_price * 100
    }

Correlation Hedging

| Asset Pair | Correlation | Hedge Ratio | |------------|-------------|-------------| | SPY / QQQ | +0.85 | 0.85 ร— position | | AAPL / XLK | +0.75 | 0.75 ร— position | | Gold / SPY | -0.15 | Small inverse | | Bitcoin / SPY | +0.30 | Low correlation |

Risk Metrics

| Metric | Formula | What It Measures | |--------|---------|-----------------| | Sharpe Ratio | (Return - RiskFree) / StdDev | Risk-adjusted return | | Max Drawdown | Peak-to-trough decline | Worst-case loss | | Win Rate | Wins / Total Trades | Strategy accuracy | | Profit Factor | Gross Profit / Gross Loss | Overall profitability | | Expectancy | Avg Win ร— WinRate - Avg Loss ร— LossRate | Per-trade expected value |

def calculate_metrics(trades: list) -> dict:
    """Calculate key risk metrics from trade history."""
    wins = [t for t in trades if t['pnl'] > 0]
    losses = [t for t in trades if t['pnl'] <= 0]
    
    total_pnl = sum(t['pnl'] for t in trades)
    win_rate = len(wins) / len(trades) if trades else 0
    avg_win = sum(t['pnl'] for t in wins) / len(wins) if wins else 0
    avg_loss = abs(sum(t['pnl'] for t in losses) / len(losses)) if losses else 0
    profit_factor = sum(t['pnl'] for t in wins) / abs(sum(t['pnl'] for t in losses)) if losses else float('inf')
    expectancy = (avg_win * win_rate) - (avg_loss * (1 - win_rate))
    
    return {
        "total_pnl": total_pnl,
        "win_rate": win_rate,
        "avg_win": avg_win,
        "avg_loss": avg_loss,
        "profit_factor": profit_factor,
        "expectancy": expectancy
    }

Summary

Risk management is more important than any trading strategy. Position sizing, stop losses, portfolio hedging, and risk metrics keep you alive in the market.

Key takeaways:

  • Position sizing: risk 1-2% of capital per trade |
  • Kelly Criterion optimizes bet size but use fractional Kelly |
  • Stop losses: fixed %, ATR-based, technical, trailing |
  • Protective puts hedge portfolio against market crashes |
  • Track metrics: Sharpe, drawdown, win rate, profit factor |
  • Correlation hedging diversifies correlated positions |
  • Maximum drawdown is the most important risk metric |
  • Preserve capital first, profits second |

What's Next: Algorithmic Trading

This course continues with algorithmic trading and automated execution systems.

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!