DEV Community

Kang
Kang

Posted on

How I Use Genetic Algorithms to Evolve Trading Strategies (With Real Code)

Most quant traders hand-tune strategies. Tweak a moving average here, adjust a threshold there, run a backtest, repeat.

I got tired of that loop. So I built a system that evolves trading strategies on its own - using genetic algorithms.

After 180+ generations, here's what I learned.

The Core Idea

Instead of writing trading strategies by hand, I encode them as "DNA" - YAML configs that describe which indicators to use, what thresholds to set, and how to manage risk.

Then I let evolution do the work:

  1. Generate a population of random strategies
  2. Evaluate each one against real market data
  3. Kill the worst performers
  4. Breed the best ones - mix their DNA
  5. Mutate slightly - swap an indicator, tweak a parameter
  6. Repeat for 100+ generations

The result? Strategies that no human would design, but that actually perform.

The Architecture

The evolution engine has four components:

  • Evaluator - Runs backtests, scores fitness (Sharpe ratio, max drawdown, win rate, profit factor)
  • Proposer - Analyzes why a strategy failed and suggests targeted improvements
  • Mutator - Applies six types of targeted mutations to strategy DNA
  • Frontier - Maintains a Pareto front of the best N strategies

The Proposer: Smart Mutations

This is where it gets interesting. The proposer doesn't just randomly suggest changes. It analyzes why a strategy failed and proposes targeted improvements:

  • High drawdown? ? Propose tighter stop-losses
  • Low win rate? ? Propose indicator swap
  • Correlated losses? ? Propose adding a market regime filter

Six Mutation Types

class MutationType(str, Enum):
    PARAMETER_TUNE = "parameter_tune"
    INDICATOR_SWAP = "indicator_swap"
    ADD_FILTER = "add_filter"
    REMOVE_FILTER = "remove_filter"
    ADJUST_RISK = "adjust_risk"
    COMBINE_STRATEGY = "combine_strategy"
Enter fullscreen mode Exit fullscreen mode

The key insight: mutations are targeted, not random. The proposer tells the mutator what to change and why.

What the DNA Looks Like

Each strategy is a YAML file:

name: evolved_momentum_v47
entry:
  indicator: rsi
  period: 14
  threshold: 30
  direction: long
exit:
  indicator: atr_trailing
  multiplier: 2.5
filters:
  - type: volume_ma
    period: 20
    min_ratio: 1.5
  - type: trend_alignment
    indicator: ema
    period: 200
risk:
  position_size: 0.02
  max_drawdown: 0.15
  stop_loss: 0.03
Enter fullscreen mode Exit fullscreen mode

The evolution engine can mutate any part of this - swap RSI for MACD, change the period from 14 to 21, add a volatility filter, adjust position sizing.

The Biggest Lesson: Overfitting Is Your Enemy

After generation 69, I found a strategy with an incredible Sharpe ratio. I was ready to celebrate.

Then I discovered look-ahead bias had leaked into my backtest. The strategy was secretly using future data to make "predictions."

Gen 69's breakthrough was completely invalid.

This taught me the most important lesson in quant finance: if your backtest looks too good to be true, it is.

I added three safeguards:

  1. Walk-forward validation - test on data the strategy has never seen
  2. Bias detector - automated scan for look-ahead bias, survivorship bias, and return inflation
  3. Monte Carlo simulation - randomize entry timing to check if returns are robust

Results After 180 Generations

After fixing the bias issues and running 180 clean generations:

  • The best strategies consistently found patterns humans wouldn't think to combine
  • Multi-factor strategies dominated single-indicator ones
  • The evolution engine discovered that regime filters (bull/bear market detection) were the single most impactful addition
  • Position sizing mutations had the biggest impact on risk-adjusted returns

Try It Yourself

FinClaw is fully open-source. You can run the evolution engine on your own data:

pip install finclaw-ai
finclaw evolve --symbol AAPL --generations 50
Enter fullscreen mode Exit fullscreen mode

The engine will evolve strategies, track lineage, and save the best DNA to disk.

GitHub: github.com/NeuZhou/finclaw


I'm building FinClaw in the open - an AI-native quant engine where strategies evolve themselves. If you're into algorithmic trading or genetic algorithms, check it out and let me know what you think.

Top comments (0)