Algorithmic Trading & Indicators Beginner

Calculate Kelly Criterion & Half-Kelly Optimal Trade Allocation in Python

Compute optimal capital allocation per trade from your backtest trade log using the Kelly Criterion and Half-Kelly formula in Python.

#numpy#pandas

Problem Statement

Betting too little underperforms compounding potential, while betting too much guarantees account ruin during losing streaks. This script analyses a strategy's win rate and payoff ratio to output Half-Kelly allocation.

Formula / Core Logic

Kelly % (f*) = W - [(1 - W) / R] where W = Win Probability, R = Avg_Win / abs(Avg_Loss)

Installation

pip install numpy pandas
kelly-criterion-optimal-bet-size-calculator-python.py
import numpy as np
import pandas as pd

def calculate_kelly_fraction(pnl_series: pd.Series):
    wins = pnl_series[pnl_series > 0]
    losses = pnl_series[pnl_series < 0]
    if len(wins) == 0 or len(losses) == 0:
        return {'Full_Kelly_Pct': 0.0, 'Half_Kelly_Pct': 0.0}
        
    win_rate = len(wins) / len(pnl_series)
    reward_risk = wins.mean() / abs(losses.mean())
    kelly = win_rate - ((1 - win_rate) / reward_risk)
    
    return {'Win_Rate_Pct': round(win_rate * 100, 2), 'Reward_to_Risk': round(reward_risk, 2), 'Full_Kelly_Pct': round(max(0, kelly) * 100, 2), 'Half_Kelly_Pct': round(max(0, kelly * 0.5) * 100, 2)}

Get the Complete 100+ Python Quant & Automation Bundle

Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).

Buy Full Bundle on Gumroad ($19) →

Frequently Asked Questions

Q: Why do professional quants prefer Half-Kelly over Full-Kelly?

Half-Kelly captures 75% of the theoretical compound growth rate while cutting portfolio volatility and drawdown risk in half.