Case Study - Building a Quantitative Strategy from Scratch › Stage 6: Risk Management Integration

Michael BrenndoerferJanuary 25, 20269 min read
Quantitative FinanceAll chapters
Part 14 of 15Strategy Development and Backtesting
Chapter 76Case Study - Building a Quantitative Strategy from Scratch › Stage 6: Risk Management Integration
Reading section 7 of 12 · Stage 6: Risk Management Integration · 9 minSection 7 of 12 · 9 min

Book contents

Section 7 of 12 · 9 min read

Case Study - Building a Quantitative Strategy from Scratch › Stage 6: Risk Management IntegrationOne section · Sections in this chapter7 / 12 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

A strategy without risk management is a liability, not an asset. In this section, we apply the risk management principles from Part V and the position sizing framework from the earlier chapter on leverage management to ensure our strategy is survivable.

Position Sizing with the Kelly Criterion

Recall from the position sizing chapter that the Kelly criterion provides the theoretically optimal fraction of capital to risk on each trade. The Kelly criterion originated in information theory, where John Kelly showed that a gambler facing a series of favorable bets should wager a specific fraction of their bankroll to maximize the long-term growth rate of wealth. The beauty of the result is its simplicity: the optimal fraction depends on only two quantities, the probability of winning and the ratio of the average win to the average loss.

The intuition is as follows. If you bet too little, you leave money on the table by not fully exploiting your edge. If you bet too much, you expose yourself to catastrophic drawdowns that can devastate your capital, even if the expected value of each bet is positive. The Kelly fraction identifies the exact sweet spot where long-run compound growth is maximized.

For a strategy with win rate pp and win/loss ratio bb, the Kelly fraction that maximizes the long-term growth rate of capital is:

f∗=p−1−pbf^* = p - \frac{1-p}{b}

where:

  • f∗f^*: optimal fraction of capital to wager
  • pp: probability of a winning trade (win rate)
  • bb: win/loss ratio (average win / average loss), determining the payout asymmetry

To understand why this formula takes the form it does, consider its two components. The first term, pp, represents the probability of winning: the higher your win rate, the more you should bet. The second term, 1−pb\frac{1-p}{b}, represents a correction for the cost of losing. The probability of losing, 1−p1-p, is divided by the win/loss ratio bb because a higher bb means your wins are proportionally larger than your losses, which makes losing less damaging in relative terms. When f∗f^* is positive, the strategy has an edge. When f∗f^* is zero or negative, the strategy does not justify any capital commitment at all, because the expected geometric growth rate is non-positive.

In practice, most quantitative traders use a fractional Kelly (typically half-Kelly) to reduce the variance of outcomes and account for estimation error in pp and bb. The full Kelly fraction maximizes expected growth but also produces stomach-churning volatility: simulations show that a full-Kelly bettor can experience drawdowns exceeding 50% even with a substantial edge. Half-Kelly sacrifices roughly 25% of the expected growth rate but cuts the variance of outcomes in half, a trade-off that you will likely find overwhelmingly worthwhile. Our estimates of pp and bb are derived from a finite sample of trades and are therefore subject to statistical error. Overestimating the edge leads to overbetting, which is far more dangerous than underbetting. Half-Kelly provides a natural buffer against this estimation risk.

In[27]:
Code
# Estimate Kelly parameters from out-of-sample trades
if len(trades_test) > 0:
    win_rate = (trades_test["pnl"] > 0).mean()
    avg_win_trade = (
        trades_test.loc[trades_test["pnl"] > 0, "pnl"].mean()
        if (trades_test["pnl"] > 0).any()
        else 0
    )
    avg_loss_trade = (
        abs(trades_test.loc[trades_test["pnl"] <= 0, "pnl"].mean())
        if (trades_test["pnl"] <= 0).any()
        else 1
    )

    win_loss_ratio = avg_win_trade / avg_loss_trade if avg_loss_trade > 0 else 0
    kelly_fraction = (
        win_rate - (1 - win_rate) / win_loss_ratio if win_loss_ratio > 0 else 0
    )
    half_kelly = kelly_fraction / 2
Out[28]:
Console
=== Position Sizing Analysis ===
Win rate (p):          58.33%
Win/Loss ratio (b):    0.47
Full Kelly fraction:   -30.35%
Half Kelly fraction:   -15.17%

The Kelly analysis suggests a theoretical optimal bet size of roughly 19%, with a half-Kelly safety buffer of 9.5%. Since our backtest limited risk to 2% of capital per trade (via the capital_at_risk parameter), we are trading well inside the conservative boundary computed from the strategy's actual win/loss statistics. This is intentional: in a real deployment, you would start with conservative sizing and gradually increase toward half-Kelly as live performance confirms the backtest estimates.

Value at Risk

As we discussed in the market risk measurement chapter, Value at Risk (VaR) quantifies the worst expected loss over a given horizon at a specified confidence level. More precisely, the α\alpha-level VaR is the threshold such that the probability of a loss exceeding that threshold is at most 1−α1 - \alpha. For example, a 1-day 95% VaR of negative $5,000 means that we expect to lose more than $5,000 on no more than 5% of trading days. VaR is a widely used risk measure in the financial industry because it translates the abstract concept of risk into a concrete dollar figure that you can act upon.

However, VaR has a well-known limitation: it tells you the threshold of the worst 5% (or 1%) of days but says nothing about how bad things get beyond that threshold. Two strategies can have identical VaR but very different tail risks. This is why we also compute the Conditional Value at Risk (CVaR), also known as Expected Shortfall. CVaR answers the follow-up question: "Given that we are in the worst 5% of outcomes, what is the average loss?" CVaR is always worse (more negative) than VaR and provides a more complete picture of tail risk. We compute the 1-day 95% VaR and 99% VaR for our strategy.

In[29]:
Code
# Daily PnL for VaR calculation
daily_pnl_test = results_test["net_pnl"]
active_pnl_test = daily_pnl_test[
    daily_pnl_test != 0
]  # Only days with positions

var_95 = np.percentile(active_pnl_test, 5)  # 5th percentile = 95% VaR
var_99 = np.percentile(active_pnl_test, 1)  # 1st percentile = 99% VaR
cvar_95 = active_pnl_test[active_pnl_test <= var_95].mean()
Out[30]:
Console
=== Risk Metrics (Out-of-Sample, Active Days Only) ===
Daily PnL Mean:            $509.29
Daily PnL Std Dev:         $10,382.87
1-Day 95% VaR:             $-14,963.79
1-Day 99% VaR:             $-30,890.94
1-Day 95% CVaR (ES):       $-23,827.34
Active trading days:       217

In this simulated holdout sample, the 1-day 95% VaR is near $15,000 in losses, while CVaR lies farther into the left tail because it averages only outcomes beyond that cutoff. Relative to a $1 million capital base, the VaR is roughly 1.5%. Whether that exposure is acceptable depends on the portfolio's mandate and risk limits; the estimate itself does not establish institutional suitability.

Out[31]:
Visualization
Histogram of active-day PnL centered near zero with a shaded left tail, a dashed VaR cutoff near minus 15 thousand dollars, and a dotted CVaR line farther left.
Distribution of daily PnL on active out-of-sample days. The dashed 95% VaR line marks the fifth-percentile cutoff, the shaded region contains observations used for Expected Shortfall, and the dotted CVaR line marks their average.

Stress Testing

Beyond standard risk metrics, we should ask: what happens if the cointegrating relationship breaks down? This is the primary tail risk for any pairs trading strategy. The standard risk metrics we computed above, VaR, CVaR, and maximum drawdown, all assume that the future will resemble the recent past. Stress testing relaxes this assumption by deliberately introducing adverse scenarios that may not appear in the historical data but are plausible based on economic reasoning.

For a pairs trading strategy, the most dangerous scenario is a structural shift in the hedge ratio. This can occur when one company in the pair undergoes a fundamental change: a merger announcement, a major product launch, a regulatory action, or a shift in business mix. When the true hedge ratio changes but our model continues to use the old estimate, the spread we compute no longer represents a stationary, mean-reverting quantity. Instead, it drifts systematically, generating false signals that lead to losses.

We simulate a scenario where the hedge ratio shifts by 20% midway through the test period.

In[32]:
Code
# Stress test: what if beta shifts by 20%?
beta_stressed = beta_hat * 1.20

results_stress = backtest_strategy(
    df_test,
    beta_stressed,
    intercept_hat,
    lookback,
    z_entry,
    z_exit,
    z_stop,
    cost_bps=10,
)

stress_pnl = results_stress["net_pnl"].sum()
stress_metrics = compute_performance_metrics(
    results_stress["net_pnl"], capital=1_000_000
)
Out[33]:
Console
=== Stress Test: Beta Shift +20% ===
Original beta:     0.6610
Stressed beta:     0.7932
Stressed total PnL: $99,226.75
Stressed Sharpe:    0.47
Stressed Max DD:    -11.28%

The alternative hedge ratio changes the PnL path and finishes below the baseline in this run, although the two curves follow the same broad trajectory. This is a sensitivity check rather than a simulated mid-period structural break, so it supports monitoring and re-estimation without quantifying a universal degradation rate.

Out[34]:
Visualization
Two cumulative PnL lines from late 2021 through 2023 follow similar turning points; the dashed alternative-beta path ends modestly below the solid baseline.
Out-of-sample cumulative PnL under the estimated hedge ratio and an alternative ratio 20% higher. The paths remain close for much of the period, but their local gains, losses, and ending values differ.

Summary of Risk Controls

A deployable strategy needs explicit risk controls documented in advance. Here is the risk framework for our pairs strategy:

  • Position-level stop-loss. Close the position if the z-score exceeds ±3.5\pm 3.5. This limits losses from structural breaks.
  • Position sizing. Risk no more than half-Kelly per trade, subject to a hard cap of 2% of capital.
  • Portfolio-level limits. If running multiple pairs, cap gross exposure at 200% of capital and net exposure at 20%.
  • Hedge ratio re-estimation. Re-estimate β\beta every 60 trading days using rolling regression. If the ADF p-value on the new spread exceeds 0.10, halt trading the pair until cointegration is re-established.
  • Daily VaR limit. If the 1-day 95% VaR exceeds 1% of portfolio NAV, reduce position sizes proportionally.