System Components
The genetic algorithm trading system is built from several specialized components that work together to enable automated strategy evolution.Component Overview
Core Components
Genome (genome.py)
Defines the genetic representation of trading strategies.
Key Classes:
Genome: Dataclass with 22 floating-point genes (all in [0.0, 1.0])decode_genome(): Converts normalized gene values to actual trading parameters
- Market Selection (5 genes)
- Entry Signals (8 genes)
- Side Selection (2 genes)
- Position Sizing (3 genes)
- Risk Management (4 genes)
Evolution Engine (evolution.py)
Implements genetic operators for creating new generations.
Functions:
Computes fitness = ROI% for a bot. Bots with fewer than 5 settled trades receive a large penalty (-100.0).
Tournament selection: randomly samples 7 bots and returns the best.
Uniform crossover: each gene randomly selected from parent A or B.
Gaussian mutation: each gene has 15% chance of being perturbed by N(0, 0.10), clamped to [0,1].
Main evolution function that creates the next generation:
- Elitism: Top 5 bots survive unchanged
- Breeding: Fill remaining slots via tournament selection + crossover/mutation
- Immigration: Add 5 random new genomes for diversity
Trading Bot (bot.py)
Individual bot that executes trades based on its genome.
Class: GeneticBot
tick()
Called every 30 seconds during the trading period:
Generate Signal
Use the genome’s signal type (price_level, momentum, mean_reversion, value, contrarian)
price_level: Buy when ask is in specific price rangemomentum: Buy based on price direction over lookback windowmean_reversion: Buy when price deviates from mean by z-score thresholdvalue: Buy whichever side is cheapest vs 50/50 fair valuecontrarian: Bet against the crowd when market is very confident
Paper Trading Engine (engine.py)
Simulates trades without real money.
Classes:
PaperTradingEngine
Manages all bot accounts and simulates order fills:
- Passive checks: Every tick, check cached settlement data
- Targeted checks: Every 10 ticks (~5 min), query API for positions that passed close time
- Settlement wait: After trading period, wait up to 4 hours for markets to settle
- Force close: Any remaining unsettled positions closed as losses
Market Data Feed (feed.py)
Centralized, thread-safe market data shared by all bots.
Class: MarketDataFeed
Runs in background thread, continuously fetching:
- Open markets closing within 24 hours
- Price history for momentum/mean-reversion signals
- Settlement data for position closing
- Event categories for market filtering
All bots read from the same shared feed, eliminating redundant API calls. The feed polls Kalshi every 30 seconds.
Data Flow
Configuration
All system parameters inconfig.py:
genetic/config.py
Persistence Layer
Automatic state saving for crash recovery and analysis: Files Created:data/evolution/gen_NNNN.json: Complete generation statedata/evolution/checkpoint_genNNNN.json: Mid-generation snapshotsdata/evolution/hall_of_fame.json: Top 20 performers all-timedata/evolution/latest.json: Pointer to most recent generationdata/evolution/evolution.log: Detailed event log
Performance Optimization
Shared Resources
- Single market data feed shared by all bots (not 100 separate feeds)
- Bulk API queries using pagination and caching
- Thread-safe read-only access to market snapshots
Minimal API Calls
- Background thread polls every 30 seconds
- Targeted settlement checks only for held positions
- Category refresh only every 5 minutes
Efficient Data Structures
- Market snapshots stored in
dict[ticker, MarketSnapshot]for O(1) lookup - Price history limited to 120 ticks (1 hour at 30s intervals)
- Settlement cache expires after 2 hours
Next Steps
Genome Structure
Detailed breakdown of all 22 genes
Fitness Evaluation
How bots are scored and ranked
Evolution Operators
Selection, crossover, and mutation mechanics
Quick Start
Run evolution on your own machine