Pakistan Ka Pehla Professional Trading Bot CourseModule 7

7.3Theme Concentration — Diversification Rules

25 min 3 code blocks Quiz (4Q)

Theme Concentration — Diversification Rules

Alright, chalo bachon, class shuru karte hain.

COURSE: Pakistan Ka Pehla Professional Trading Bot Course

MODULE 7: Risk Management — Kelly Criterion Aur Position Sizing

LESSON 7.3: Theme Concentration — Diversification Rules

(Estimated Time: 25 minutes)

Assalam-o-Alaikum, future trading wizards. Umeed hai pichle lessons samajh aa gaye honge. Aaj ka topic aam taur pe log ignore karte hain, aur phir rote hain jab unka poora account ek he ghalat khabar se urr jaata hai. We're talking about Theme Concentration. Seedhi baat: agar tumne saari investment ek he "story" pe laga di, toh story ke flop hote he tum bhi flop ho.

So listen up. Yeh lesson tumhara account bachayega.

1. "Theme Concentration" Kya Bala Hai?

Socho tumhara portfolio ek cricket team hai. Agar tumne saare 11 players fast bowlers rakh liye hain, aur pitch achanak se spin-friendly nikal aayi, toh kya hoga? You're screwed. Game over.

Trading mein, "theme" bilkul ussi pitch ki tarah hai. It's the underlying story or event that connects multiple markets.

Example: Ek "theme" ho sakti hai "Geopolitics: Middle East Conflict". Is theme ke andar multiple prediction markets ho sakte hain:

  • "Will Israel conduct a ground operation in Rafah by June 1?"
  • "Will Iran-backed Houthis attack another vessel in the Red Sea this week?"
  • "Will USA announce new sanctions on Iran before July?"

Yeh teeno alag alag markets hain, lekin in sab ka "baap" ek he hai: Middle East ka conflict. Agar suddenly Iran aur Israel mein sulah ho jaati hai, ya koi ceasefire deal ho jaati hai, toh tumhari teeno positions ek saath loss mein jayengi. Ek he news, multiple losses. This is called concentration risk. Your entire P&L is now hostage to a single headline.

Hamara kaam as professional bot developers yeh hai ke hum apne bot ko aisi bewakoofi se bachayein. We need to diversify our themes, not just our markets.

2. Hamara Golden Rule: The "Do Aur Baarah" Ka Qanoon

Is maslay ka hal simple hai. Hum ne apne Polymarket Oracle bot mein do golden rules banaye hain. Isko main kehta hoon "Do Aur Baarah" ka qanoon. Yaad rakho isko.

  1. Max 2 Positions Per Theme: Kisi bhi ek theme (e.g., "US Inflation", "NVIDIA Earnings", "Middle East Conflict") mein hum 2 se zyada open positions nahi lenge. Is se hum over-excitement mein aakar ek he story pe sab kuch lagane se bachte hain. It forces discipline.
  2. Max 12% Theme Exposure: Un 2 positions ki total investment value aapke total capital ka 12% se zyada nahi honi chahiye. Agar tumhara total capital $1000 hai, toh "Middle East Conflict" theme pe tumhari total investment $120 se zyada nahi ho sakti. Yeh hamara hard stop hai.

Yeh rules humein execution.py mein implement karne hain, taake trade execute karne se pehlay bot yeh check kar le.

3. Code Mein Implementation - Asal Kaam

Ab aate hain asal kaam pe. Theory bohot ho gayi. Let's see how this is coded in our system.

Yeh function hamare execution.py module ka hissa hai. Jab bhi strategies/theta_sniper.py jaisi koi strategy ek trade signal generate karti hai, execution.py pehle is function ko call karta hai to get a green light.

python
# Constants defined in our config file, loaded at the start
MAX_POSITIONS_PER_THEME = 2
MAX_THEME_EXPOSURE_PCT = 0.12  # 12% of capital

def check_theme_limits(theme: str, capital: float, existing_positions: list[dict]) -> dict:
    """
    Checks if a new position can be opened in a given theme based on concentration rules.
    
    Args:
        theme (str): The theme of the potential new position (e.g., "Geopolitics: Middle East").
        capital (float): Total trading capital available.
        existing_positions (list[dict]): A list of all currently open positions from our database.
        
    Returns:
        dict: A dictionary indicating if the trade is allowed, and the reason.
    """
    # Step 1: Is theme ki saari open positions database se filter karo.
    # Yeh data humein db.py se milta hai.
    theme_positions = [p for p in existing_positions 
                       if p.get('theme') == theme and p.get('status') == 'open']
    
    # Step 2: Ginti karo ke is theme mein kitni positions pehle se hain.
    theme_count = len(theme_positions)
    
    # Step 3: Un sab positions ki total qeemat (cost) jama karo.
    # 'cost_eur' is what we paid for the shares.
    theme_exposure = sum(p['cost_eur'] for p in theme_positions)
    
    # Step 4: Apne capital ka 12% hissa nikalo. Yeh hamari red line hai.
    max_exposure_allowed = capital * MAX_THEME_EXPOSURE_PCT
    
    # Rule 1 Check: Kya positions ki tadaad 2 ya uss se zyada hai?
    if theme_count >= MAX_POSITIONS_PER_THEME:
        return {
            'allowed': False, 
            'reason': f'Theme "{theme}" already has {theme_count} positions (max {MAX_POSITIONS_PER_THEME})'
        }
    
    # Rule 2 Check: Kya is theme pe lagi raqam 12% limit cross kar chuki hai?
    if theme_exposure >= max_exposure_allowed:
        return {
            'allowed': False, 
            'reason': f'Theme "{theme}" exposure ${theme_exposure:.2f} >= ${max_exposure_allowed:.2f} cap'
        }
    
    # Agar dono rules pass ho gaye, toh trade ki ijaazat hai.
    # Hum yeh bhi batayenge ke is theme mein mazeed kitni investment ki gunjaish hai.
    remaining_budget = max_exposure_allowed - theme_exposure
    return {
        'allowed': True, 
        'max_bet': round(remaining_budget, 2), 
        'reason': f'Theme "{theme}": {theme_count}/{MAX_POSITIONS_PER_THEME} positions, ${remaining_budget:.2f} budget remaining'
    }

Code Walkthrough (Line-by-Line)

  • theme_positions = [...]: Yeh ek simple list comprehension hai. Hum existing_positions ki list (jo hamare db.py se aati hai) mein se woh saari positions nikaal rahe hain jinka theme hamare target theme se match karta hai aur jinka status 'open' hai. Closed positions ko count nahi karna.
  • theme_count = len(...): Simple counting.
  • theme_exposure = sum(...): Yahan hum un filtered positions ki cost_eur ko jama kar rahe hain to get the total money invested in that theme.
  • max_exposure_allowed = ...: Total capital ka 12% calculate kar liya.
  • if theme_count >= ...: Pehla check. Agar 2 positions pehle se hain, seedha return False. Game over. Aage check karne ki zaroorat nahi.
  • if theme_exposure >= ...: Doosra check. Agar positions 2 se kam hain lekin unki value 12% limit ko touch kar rahi hai, tab bhi return False.
  • return {'allowed': True, ...}: Agar upar ke dono checks pass ho jaate hain, iska matlab hai gunjaish hai. Hum allowed: True return karte hain. Saath mein max_bet bhi calculate karke bhejte hain. Yeh execution.py ko batata hai ke "haan, trade le sakte ho, lekin naya bet is max_bet amount se zyada ka nahi hona chahiye." This is super important for dynamic position sizing.

Runnable Example

Let's see it in action. Imagine karo yeh hamara current portfolio hai.

python
# --- RUNNABLE EXAMPLE ---

# Apke bot ka current state
total_capital = 1000.00  # $1000

# db.py se aane wala data (aapki open positions)
# Yeh data 'positions' table se fetch hota hai
existing_positions = [
    {
        'theme': 'sports',
        'size': 200
    },
    # ... more positions

Diversification rules prevent category-level disasters and spread risk.

---

## 📺 Recommended Videos & Resources
- **[Portfolio Diversification](https://en.wikipedia.org/wiki/Diversification_(finance))** — Core investment principle
  - Type: Wikipedia
  - Link description: Learn diversification and correlation
- **[Risk Correlation in Portfolios](https://www.youtube.com/results?search_query=correlation+diversification+trading)** — Understanding dependencies
  - Type: YouTube
  - Link description: Search "correlation and diversification in trading"
- **[Sector/Theme Correlation](https://www.youtube.com/results?search_query=sector+correlation+stock+market)** — Correlated assets
  - Type: YouTube
  - Link description: Search "sector correlation analysis"
- **[Modern Portfolio Theory](https://en.wikipedia.org/wiki/Modern_portfolio_theory)** — Mathematical foundation
  - Type: Wikipedia
  - Link description: Learn MPT and efficient frontiers
- **[Concentration Risk](https://www.youtube.com/results?search_query=concentration+risk+portfolio)** — Avoiding overexposure
  - Type: YouTube
  - Link description: Search "concentration risk in portfolios"

---

## 🎯 Mini-Challenge
**5-Minute Practical Task:** Given 10 open positions in themes: 3 sports, 2 politics, 2 crypto, 2 weather, 1 other. Check: (1) Any theme > 40%? (2) Any category has > $2000 exposure? (3) If yes to either, identify which positions to close to meet diversification rules.

---

## 🖼️ Visual Reference

📊 Diversification Rules Visualization ┌───────────────────────────────────┐ │ Portfolio of 10 Positions Total │ │ Max per category: 40% │ │ Max per position: 25% │ └─────────────────────────────────────┘

COMPLIANT: Sports: $2000 (20%) ✓ Politics: $1500 (15%) ✓ Crypto: $1500 (15%) ✓ Weather: $2000 (20%) ✓ Other: $2000 (20%) ✓ Total: $9000 ✓

VIOLATION: Sports: $5000 (50%) ✗ (>40%) Politics: $2000 (20%) ✓ Crypto: $1500 (15%) ✓ Other: $1500 (15%) ✓ Total: $10000

Action: Close $1000 sports → Becomes $4000 sports (40%) ✓

code

---

Lesson Summary

3 runnable code examples4-question knowledge check below

Quiz: [Module 7 Lesson 7.3]

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