Pakistan Ka Pehla Professional Trading Bot CourseModule 7

7.1Kelly Criterion — Kitna Lagana Chahiye?

30 min 3 code blocks Quiz (4Q)

Kelly Criterion — Kitna Lagana Chahiye?

Assalam-o-Alaikum, bot developers! Umeed hai sab khairiyat se honge.

Chalo bhai, Module 7 shuru karte hain. Ab tak humne strategies aur AI models pe kafi kaam kar liya hai. Lekin sab se important sawal abhi baaqi hai: Trade pe paisa lagana kitna hai? Ye woh sawal hai jo ek profitable strategy ko zero kar sakta hai agar iska jawab aapse ajeeb ho.

Yeh lesson sirf theory nahi hai. Yeh woh zinda sach hai jo aapke account ko blow up hone se bachayega. Let's get this right.

COURSE: Pakistan Ka Pehla Professional Trading Bot Course

MODULE 7: Risk Management — Kelly Criterion Aur Position Sizing

LESSON 7.1: Kelly Criterion — Kitna Lagana Chahiye?

Hook: The Million Rupee Question

Aapke paas duniya ki best trading strategy hai. Aapka AI model 90% accurate hai. Market mein ek zabardast opportunity hai. Aapke account mein 10 lakh PKR paray hain.

Kitna lagaoge?

1 lakh? 5 lakh? Ya poora 10 lakh laga ke "YOLO" karoge? Agar trade aagay chala gaya, to aap hero. Agar peechay aagaya, to aap zero. Trading mein long-term survival is sab se ahem cheez. Kelly Criterion is maslay ka a mathematical, no-BS jawab hai. Ye aapko batata hai ke apni edge ke hisaab se capital ka kitna percentage risk karna hai taake long run mein aapka growth maximum ho.

Taqi, hamara star trader, apni har trade ka size Kelly se decide karta hai. Aaj aap bhi seekhein ge.

Kelly Criterion Hai Kya? The Formula

Simple lafzon mein, Kelly Criterion ek formula hai jo optimal bet size calculate karta hai. Optimal ka matlab hai woh size jo aapke capital ko waqt ke saath sab se tezi se grow karega, assuming aapki edge (winning probability) aapse ajeeb nahi hai.

Formula yeh hai:

f = (bp - q) / b

Ghabrana nahi hai. Ek ek cheez ko toRte hain:

  • f: Yeh woh fraction ya percentage hai aapke total capital ka jo aapko is trade pe lagana chahiye. Yehi hamara jawab hai.
  • p: Probability of winning. Aapke jeetne ka chance kitna hai? Yeh number hamare AI models (gemini.py, haiku.py) se aata hai.
  • q: Probability of losing. Simple hai, 1 - p.
  • b: Payout odds. Agar aap 1 rupaya lagate hain, to jeetne pe kitna profit milega? Isko aam taur pe "B-to-1" odds kehte hain.

Calculation of b is critical. b = Potential Profit / Potential Loss. Agar aap 80 rupay laga kar 20 rupay jeet sakte ho, to b = 20 / 80 = 0.25.

Code Breakdown: Let's Get Practical

Ab theory ko code mein daalte hain. Yeh function hamari poori trading bot ki risk management ki buniyad hai. Isko ghaur se samjho.

python
import math

def kelly_criterion(win_prob: float, win_payout: float, loss_amount: float = 1.0):
    """
    Kelly Criterion — optimal bet size calculate karo.
    
    Yeh function batata hai ke apni edge aur odds ke hisaab se 
    capital ka kitna percentage ek trade pe risk karna chahiye.

    Args:
        win_prob: Jeetne ki probability (0 se 1 ke darmiyan). Example: 0.75 for 75%
        win_payout: Agar jeete to kitna profit hoga per unit of risk.
        loss_amount: Agar haare to kitna loss hoga. Default 1.0 hai.
    """
    # Formula components: f = (bp - q) / b
    
    # 1. Calculate 'b' - the payout odds
    # b = potential profit / potential loss
    if loss_amount <= 0:
        # Loss amount zero ya negative nahi ho sakta
        return {
            'full_kelly_pct': 0,
            'half_kelly_pct': 0,
            'recommended': 'NO BET (Invalid Loss Amount)',
            'edge': 0
        }
    b = win_payout / loss_amount
    
    # 2. Define 'p' and 'q'
    p = win_prob
    q = 1 - p
    
    # 3. Calculate full Kelly fraction
    # Agar b zero hai, to divide by zero error se bachna hai
    if b == 0:
        kelly = -1 # No payout means no reason to bet
    else:
        kelly = (b * p - q) / b
    
    # 4. Calculate half Kelly (safer, recommended version)
    half_kelly = kelly / 2
    
    # 5. Calculate your "edge"
    # Edge = (Probability of Winning * What You Win) - (Probability of Losing * What You Lose)
    # Yeh batata hai ke on average, har 1 rupay ke bet pe aap kitna kamaoge.
    edge = (p * win_payout) - (q * loss_amount)

    return {
        'full_kelly_pct': round(max(0, kelly * 100), 2),
        'half_kelly_pct': round(max(0, half_kelly * 100), 2),
        'recommended': 'BET' if kelly > 0 else 'NO BET',
        'edge_pct': round(edge * 100, 2)
    }

Polymarket Example - Real World Application

Chalo is function ko ek real-world Polymarket scenario mein use karte hain.

Scenario: Ek market hai, "Will Pakistan reach the T20 World Cup Final?". Market price "Yes" ka 82c (ya 0.82 PKR) chal raha hai. Iska matlab:

  • Agar aap "Yes" khareedte ho, to aap 82 paisay de rahe ho.
  • Agar Pakistan final mein pohanch gaya, to aapka contract 1 rupay ka ho jayega. Aapka profit: 1.00 - 0.82 = 0.18 PKR.
  • Agar Pakistan bahar ho gaya, to aapka contract 0 ka ho jayega. Aapka loss: 0.82 PKR.

Ab, hamara AI model (ai/sonnet.py) kehta hai ke Pakistan ke final mein jaane ka chance 90% hai.

Let's plug these numbers into our function.

  • win_prob (p): 0.90 (hamare AI model se)
  • win_payout: 0.18 (1.00 - 0.82)
  • loss_amount: 0.82 (jo hum risk kar rahe hain)

Ab code run karte hain:

python
# Example: Market at 82c, you think 90% chance
# Win: pay 82c, get 1 PKR = profit 18c (win_payout = 0.18)
# Lose: lose 82c (loss_amount = 0.82)
result = kelly_criterion(win_prob=0.90, win_payout=0.18, loss_amount=0.82)

print(f"--- Polymarket Scenario ---")
print(f"Market Price: 82c | Our Probability: 90%")
print(f"Edge: {result['edge_pct']}%")
print(f"Full Kelly Suggestion: {result['full_kelly_pct']}% of capital")
print(f"Half Kelly Suggestion: {result['half_kelly_pct']}% of capital")
print(f"Verdict: {result['recommended']}")

# Agar aapka capital 500,000 PKR hai:
total_capital = 500000
suggested_bet_size_pkr = total_capital * (result['half_kelly_pct'] / 100)
print(f"\nWith a capital of {total_capital:,} PKR, your suggested position size is: {math.ceil(suggested_bet_size_pkr):,} PKR")

Kelly Criterion optimizes position sizing to maximize growth while minimizing bankruptcy risk.

---

## 📺 Recommended Videos & Resources
- **[Kelly Criterion Explained](https://en.wikipedia.org/wiki/Kelly_criterion)** — The mathematical principle
  - Type: Wikipedia
  - Link description: Learn the formula and its derivation
- **[Position Sizing with Kelly](https://www.youtube.com/results?search_query=kelly+criterion+trading+position+sizing)** — Practical application
  - Type: YouTube
  - Link description: Search "Kelly criterion trading position sizing"
- **[Fractional Kelly for Safety](https://en.wikipedia.org/wiki/Kelly_criterion#Concerns_and_criticism)** — Risk reduction variants
  - Type: Wikipedia
  - Link description: Learn about fractional Kelly (0.5K) strategies
- **[Bankroll Management](https://en.wikipedia.org/wiki/Bankroll_management)** — Long-term capital preservation
  - Type: Wikipedia
  - Link description: Learn professional bankroll management
- **[Expected Value Calculation](https://www.youtube.com/results?search_query=expected+value+calculation+trading)** — Core concept
  - Type: YouTube
  - Link description: Search "expected value in trading"

---

## 🎯 Mini-Challenge
**5-Minute Practical Task:** Given: win rate 60%, average win $100, average loss $80. Calculate: (1) Expected value per trade, (2) Kelly % (optimal bet size), (3) Position size for $10,000 bankroll. Explain whether Kelly or fractional Kelly is safer.

---

## 🖼️ Visual Reference

📊 Kelly Criterion Capital Growth Comparison Full Kelly vs Conservative Approach ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Starting: $10,000 Win %: 60% | Avg Win: +$100 | Avg Loss: -$80 Expected Value: +$28 per trade

FULL KELLY (23% per trade = $2,300): Trade 1: Win → $12,300 Trade 2: Win → $14,829 Trade 3: Loss → $11,422 Trade 4: Win → $13,760 ...grows fast BUT huge drawdowns possible

HALF KELLY (11.5% per trade = $1,150): Trade 1: Win → $11,150 Trade 2: Win → $12,376 Trade 3: Loss → $11,178 Trade 4: Win → $12,455 ...more stable, slower growth

RECOMMENDATION: Use Half Kelly (0.5K) for living systems. Full Kelly is theoretical maximum but too risky.

code

---

Lesson Summary

3 runnable code examples4-question knowledge check below

Quiz: Kelly Criterion — Kitna Lagana Chahiye?

4 questions to test your understanding. Score 60% or higher to pass.