Portfolio & Risk·Position Sizing Models·Intermediate

Optimal F Sizing

Optimal f position sizing. A complete hands-on Jupyter notebook with production-ready Python implementation, best practices, and step-by-step walkthrough for risk workflows in quantitative cryptocurrency trading.

position-sizingrisk-management

Optimal F Sizing: Maximizing Growth with Risk Management

Optimal f sizing, often referred to as 'optimal leverage' or 'Kelly Criterion sizing,' is a strategy used in finance and trading to determine the optimal proportion of capital to risk on a single trade or investment. The goal is to maximize long-term wealth growth while managing risk effectively. It's a critical component of robust risk management and portfolio allocation, preventing both under-leveraging (leaving potential profits on the table) and over-leveraging (risking ruin).

Why is Optimal F Sizing Important?

  • Maximizing Growth: When applied correctly, optimal f sizing can significantly accelerate the growth of a trading or investment portfolio over time.
  • Risk Management: It provides a mathematically sound approach to avoid excessive risk-taking, which can lead to catastrophic losses or 'gambler's ruin.'
  • Systematic Approach: It offers a disciplined, quantitative method for capital allocation, removing emotional biases from sizing decisions.

The Kelly Criterion: The Foundation of Optimal F Sizing

The most widely recognized mathematical framework for optimal f sizing is the Kelly Criterion. Developed by J.L. Kelly Jr., it is a formula used to determine the optimal fraction of capital to bet on an outcome with a positive expected value. The criterion aims to maximize the expected value of the logarithm of wealth, which in turn maximizes the long-term growth rate of the portfolio.

Formula for Simple Bets (Binary Outcomes)

For a simple bet where there are only two outcomes (win or loss) with a known probability and fixed payoffs, the Kelly Criterion is calculated as:

$$ f = p - \frac{q}{b} $$

Where:

  • f (optimal fraction) is the fraction of the current bankroll to wager.
  • p is the probability of winning.
  • q is the probability of losing (1 - p).
  • b is the payoff ratio (profit received for a win / amount lost for a loss).

Breakdown of Components:

  • Probability of Winning (p): This is your estimated edge or success rate for a given trade or investment strategy. It's crucial for this to be accurately estimated.
  • Probability of Losing (q): This is simply 1 - p.
  • Payoff Ratio (b): This represents your average potential profit for a winning trade divided by your average potential loss for a losing trade. For example, if you expect to win $2 for every $1 you risk, b = 2.

Key Principles of Kelly Criterion:

  • Positive Expectancy: The Kelly Criterion should only be applied when (p * b) - q > 0, meaning the expected value of the bet is positive. If the expectancy is negative or zero, the optimal f will be zero or negative, suggesting no bet should be placed.
  • Long-Term Growth: It optimizes for long-term growth, not short-term maximum profit or minimum volatility.
  • Risk Aversion: While aggressive, it also inherently manages risk by suggesting smaller bets as p or b decrease, and never betting more than your bankroll allows.

Let's implement a function to calculate the Kelly fraction.

[1]
import numpy as np
import matplotlib.pyplot as plt

def calculate_kelly_fraction(p: float, b: float) -> float:
    """
    Calculates the optimal Kelly fraction for a simple binary bet.

    Args:
        p (float): Probability of winning (between 0 and 1).
        b (float): Payoff ratio (profit on win / loss on loss, must be > 0).

    Returns:
        float: The optimal Kelly fraction. Returns 0 if no positive edge exists.
    """
    if not (0 <= p <= 1):
        raise ValueError("Probability of winning (p) must be between 0 and 1.")
    if not b > 0:
        raise ValueError("Payoff ratio (b) must be greater than 0.")

    q = 1 - p

    # Check for positive expectancy before calculating Kelly
    if (p * b) - q <= 0: # If expected value is not positive
        return 0.0 # No bet should be placed

    f = p - (q / b)

    # Kelly fraction should not be negative or greater than 1
    return max(0.0, min(1.0, f))

# --- Example Usage ---
# Scenario 1: High win rate, decent payoff
p1 = 0.6 # 60% chance of winning
b1 = 1.5 # Win $1.5 for every $1 risked (1.5:1 reward-to-risk)
f1 = calculate_kelly_fraction(p1, b1)
print(f"Scenario 1 (p={p1}, b={b1}): Optimal Kelly Fraction = {f1:.4f}")

# Scenario 2: Lower win rate, higher payoff
p2 = 0.4 # 40% chance of winning
b2 = 3.0 # Win $3 for every $1 risked (3:1 reward-to-risk)
f2 = calculate_kelly_fraction(p2, b2)
print(f"Scenario 2 (p={p2}, b={b2}): Optimal Kelly Fraction = {f2:.4f}")

# Scenario 3: Negative expectancy - should return 0
p3 = 0.4 # 40% chance of winning
b3 = 1.0 # Win $1 for every $1 risked (1:1 reward-to-risk)
f3 = calculate_kelly_fraction(p3, b3)
print(f"Scenario 3 (p={p3}, b={b3}, negative expectancy): Optimal Kelly Fraction = {f3:.4f}")

# Scenario 4: Aggressive Kelly (high win prob, high payoff)
p4 = 0.7
b4 = 2.0
f4 = calculate_kelly_fraction(p4, b4)
print(f"Scenario 4 (p={p4}, b={b4}): Optimal Kelly Fraction = {f4:.4f}")
Scenario 1 (p=0.6, b=1.5): Optimal Kelly Fraction = 0.3333
Scenario 2 (p=0.4, b=3.0): Optimal Kelly Fraction = 0.2000
Scenario 3 (p=0.4, b=1.0, negative expectancy): Optimal Kelly Fraction = 0.0000
Scenario 4 (p=0.7, b=2.0): Optimal Kelly Fraction = 0.5500

Interpretation of the Kelly Fraction

The calculated f value represents the proportion of your current capital that you should bet on each instance of a trading opportunity. For example:

  • If f = 0.10, you should risk 10% of your current portfolio on the next trade.
  • If f = 0.02, you should risk 2%.
  • If f = 0.00, it implies that, based on your p and b, there is no positive edge, and you should not bet at all.

It's important to note that the Kelly Criterion is often used in a 'fractional Kelly' approach (e.g., half-Kelly) in practice, as full Kelly can be very aggressive and lead to high volatility, which some investors find uncomfortable.

Visualizing Kelly Criterion: Impact of Win Probability and Payoff Ratio

Let's visualize how the optimal Kelly fraction changes based on variations in the win probability (p) and the payoff ratio (b). This will help us understand the sensitivity of the optimal bet size to these two critical parameters.

[2]
# Generate a range of probabilities and payoff ratios
p_values = np.linspace(0.01, 0.99, 100) # Probabilities from 1% to 99%
b_values = [0.5, 1.0, 1.5, 2.0, 3.0, 5.0] # Different payoff ratios

plt.figure(figsize=(12, 7))

for b_val in b_values:
    kelly_fractions = [calculate_kelly_fraction(p, b_val) for p in p_values]
    plt.plot(p_values, kelly_fractions, label=f'Payoff Ratio (b) = {b_val:.1f}')

plt.title('Optimal Kelly Fraction vs. Win Probability for Various Payoff Ratios')
plt.xlabel('Win Probability (p)')
plt.ylabel('Optimal Kelly Fraction (f)')
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend(title='Payoff Ratio')
plt.axhline(0, color='grey', linestyle='--', linewidth=0.8)
plt.axvline(0.5, color='grey', linestyle=':', linewidth=0.8, label='p=0.5 (Fair Bet)')
plt.xlim(0, 1)
plt.ylim(-0.1, 1.0)
plt.tight_layout()
plt.show()

# --- Interpretation ---
print("\nInterpretation:")
print("1.  **Positive Expectancy Threshold:** The Kelly fraction only becomes positive when the win probability (p) is sufficient to overcome the payoff ratio (b). For b=1 (1:1), p must be > 0.5. For b=0.5 (0.5:1), p must be > 0.66.")
print("2.  **Increasing Returns:** As the win probability (p) increases, the optimal Kelly fraction (f) generally increases, suggesting a larger bet size.")
print("3.  **Impact of Payoff Ratio:** Higher payoff ratios (b) allow for a positive Kelly fraction even with lower win probabilities, and lead to a more aggressive 'f' for the same 'p'. Conversely, lower payoff ratios require a significantly higher win probability to justify any bet.")
print("4.  **Maximum F:** The optimal f can approach 1 (betting 100% of capital) only with extremely high win probabilities and payoff ratios, which is rarely practical or advisable due to real-world complexities and the risks of over-optimization.")
cell output

Interpretation:
1.  **Positive Expectancy Threshold:** The Kelly fraction only becomes positive when the win probability (p) is sufficient to overcome the payoff ratio (b). For b=1 (1:1), p must be > 0.5. For b=0.5 (0.5:1), p must be > 0.66.
2.  **Increasing Returns:** As the win probability (p) increases, the optimal Kelly fraction (f) generally increases, suggesting a larger bet size.
3.  **Impact of Payoff Ratio:** Higher payoff ratios (b) allow for a positive Kelly fraction even with lower win probabilities, and lead to a more aggressive 'f' for the same 'p'. Conversely, lower payoff ratios require a significantly higher win probability to justify any bet.
4.  **Maximum F:** The optimal f can approach 1 (betting 100% of capital) only with extremely high win probabilities and payoff ratios, which is rarely practical or advisable due to real-world complexities and the risks of over-optimization.

Simulation: Comparing F-Sizing Strategies

Let's simulate a series of trades to demonstrate the long-term impact of different f-sizing strategies on portfolio growth. We will compare:

  1. Fixed Fractional Sizing (Sub-Optimal): A fixed percentage that is not necessarily Kelly optimal.
  2. Optimal Kelly Sizing: The theoretically optimal fraction.
  3. Half-Kelly Sizing: A more conservative approach, often preferred in practice to mitigate volatility.
  4. Over-Leveraging (e.g., 2x Kelly): To show the detrimental effects of risking too much.
  5. Fixed Bet Size (Absolute): A simple fixed dollar amount bet.

We'll use a hypothetical trading system with a positive expectancy.

[3]
# Simulation Parameters
initial_capital = 10000.0
num_trades = 1000
win_probability = 0.55  # 55% chance of winning
payoff_ratio = 1.25     # Win $1.25 for every $1 risked (1.25:1 R:R)

# Calculate optimal Kelly fraction
optimal_f = calculate_kelly_fraction(win_probability, payoff_ratio)

# Define different sizing strategies
sizing_strategies = {
    "Fixed 0.05 (5%)": 0.05,
    "Optimal Kelly": optimal_f,
    "Half Kelly": optimal_f / 2,
    "Double Kelly (Over-leveraged)": optimal_f * 2, # Dangerous!
}

# Store portfolio history for each strategy
portfolio_histories = {name: [initial_capital] for name in sizing_strategies}

# Run the simulation for each strategy
for strategy_name, f_size in sizing_strategies.items():
    current_capital = initial_capital
    for _ in range(num_trades):
        # Determine bet size
        bet_amount = current_capital * f_size

        # Simulate trade outcome
        if np.random.rand() < win_probability:
            # Win
            current_capital += bet_amount * payoff_ratio
        else:
            # Loss
            current_capital -= bet_amount

        # Ensure capital doesn't go below zero (gambler's ruin)
        if current_capital <= 0:
            current_capital = 0
            break

        portfolio_histories[strategy_name].append(current_capital)

# Plotting the results
plt.figure(figsize=(14, 8))
for strategy_name, history in portfolio_histories.items():
    plt.plot(history, label=f'{strategy_name} (f={sizing_strategies[strategy_name]:.4f})')

plt.title('Portfolio Growth Simulation with Different F-Sizing Strategies')
plt.xlabel('Number of Trades')
plt.ylabel('Portfolio Value')
plt.yscale('log') # Use log scale for better visualization of exponential growth
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend()
plt.ylim(initial_capital / 10, plt.ylim()[1]) # Adjust y-axis for better visibility
plt.tight_layout()
plt.show()

print(f"\nInitial Capital: ${initial_capital:,.2f}")
print(f"Number of Trades: {num_trades}")
print(f"Win Probability (p): {win_probability*100:.2f}%")
print(f"Payoff Ratio (b): {payoff_ratio:.2f}")
print(f"Calculated Optimal Kelly Fraction (f): {optimal_f:.4f}")

print("\nFinal Portfolio Values:")
for strategy_name, history in portfolio_histories.items():
    print(f"  {strategy_name}: ${history[-1]:,.2f}")
cell output

Initial Capital: $10,000.00
Number of Trades: 1000
Win Probability (p): 55.00%
Payoff Ratio (b): 1.25
Calculated Optimal Kelly Fraction (f): 0.1900

Final Portfolio Values:
  Fixed 0.05 (5%): $74,692,101.05
  Optimal Kelly: $1,015,182,212,255,822.25
  Half Kelly: $1,643,924,665,624.31
  Double Kelly (Over-leveraged): $1,085.10

Interpretation of the Simulation Results

  • Optimal Kelly (and Half-Kelly) Performance: The strategies using the Kelly Criterion (especially Half-Kelly) show significantly better long-term growth compared to arbitrary fixed fractional sizing, demonstrating the power of dynamically adjusting bet sizes based on current capital.
  • Volatility: Full Kelly can lead to significant swings in portfolio value. Half-Kelly often provides a smoother growth curve with less drawdown, which is why it's a popular practical choice.
  • Over-Leveraging Danger: The 'Double Kelly' strategy (or any over-leveraged approach) often leads to rapid ruin. Even if it starts well, a series of losses can quickly decimate the capital, reinforcing the importance of not risking too much per trade.
  • Fixed Fractional (Sub-Optimal): While better than over-leveraging, a fixed fractional size that isn't optimized won't achieve the same growth potential as Kelly sizing.

This simulation vividly illustrates that even with a positive edge, improper sizing can severely hinder portfolio growth or lead to ruin. Optimal f sizing helps to navigate this balance.

Practical Considerations and Limitations

While the Kelly Criterion is a powerful theoretical tool, its practical application comes with several challenges and considerations:

  1. Accurate Estimation of p and b: The biggest challenge is accurately estimating the win probability (p) and payoff ratio (b). These are rarely fixed and can change over time. Misestimation can lead to sub-optimal or even ruinous results.
  2. Assumptions: The Kelly Criterion assumes independent bets, no transaction costs, infinite divisibility of capital, and known probabilities, which are often not perfectly met in real-world trading.
  3. Risk Tolerance: Full Kelly can be highly volatile and lead to significant drawdowns. Many traders opt for a fractional Kelly (e.g., 0.5 * Kelly) to balance growth with personal risk tolerance and psychological comfort.
  4. Portfolio of Assets: For a portfolio of multiple uncorrelated assets or strategies, the multivariate Kelly Criterion is more appropriate, though more complex to implement.
  5. Dynamic Adaptation: p and b may change as your trading strategy evolves or market conditions shift. Regular re-evaluation and adaptation of your f-sizing are necessary.

Despite these limitations, understanding the principles of optimal f sizing provides a robust framework for capital allocation and risk management, encouraging a data-driven approach to position sizing.

Conclusion

Optimal f sizing, rooted in the Kelly Criterion, is a fundamental concept for maximizing long-term wealth growth while diligently managing risk. By calculating the optimal fraction of capital to risk per trade based on win probability and payoff ratio, traders and investors can systematically approach their capital allocation decisions.

While the theoretical model provides a strong foundation, practical implementation requires careful estimation of probabilities and payoffs, and often a more conservative 'fractional Kelly' approach to align with personal risk tolerance and real-world market dynamics. Mastering optimal f sizing is a crucial step towards disciplined and profitable trading and investing.