Skip to content

NeuZhou/stratevo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

552 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

English | 中文 | 한국어 | 日本語

StratEvo

Genetic algorithms evolve trading strategies so you don't have to write them.

Genetic algorithm breeds and walk-forward tests trading strategies from 484 factors.

StratEvo

484+ factors · Genetic evolution · Walk-forward validated · No API keys needed

Strategy Evolution — Fitness climbing from random to optimized over 600 generations

⬆️ Real evolution run: 9 crypto assets × 600 generations. Fitness climbs from random (-0.95) to optimized (37.5) — 33% annual return, 6.06 Sharpe, 5.6% max drawdown. (backtest result, not live trading)

PyPI CI codecov License Python 3.10+ 484 Factors 7960+ Tests Discord GitHub Stars

Quick Start · Why StratEvo? · How It Works · MCP Server · Discord


Quick Start

pip install stratevo
stratevo evolve --quick            # See results in ~2 minutes
stratevo evolve --market crypto    # Full evolution (deeper search)

No API keys. No exchange accounts. No config files. From install to first evolved strategy in under 2 minutes.

What does it look like? (click to expand)
$ stratevo evolve --quick

  ⚡ Quick mode — small dataset, fast iterations
     Results in ~2 minutes. Use without --quick for full evolution.

============================================================
 StratEvo Auto Evolution Engine
============================================================
  [factors] loaded 480 dynamic factors
  Population: 15 | Elite: 3 | Mutation rate: 0.5
  ------------------------------------------------------------
  Gen    0 | fitness=   -1.00 | return=   0.0% | sharpe=-0.74 | trades=   0 | 28s
  Gen    5 | fitness=    1.23 | return=  12.4% | sharpe= 0.85 | trades=  14 | 25s
  Gen   10 | fitness=    3.60 | return=  18.7% | sharpe= 1.40 | trades=  23 | 27s

  ═══════════════════════════════════════════
  🏆 Best Strategy Found
  ═══════════════════════════════════════════
  Generation:    10
  Fitness:       3.60
  Annual Return: 18.7%
  Sharpe Ratio:  1.40
  Max Drawdown:  12.3%

  Walk-Forward OOS Results:
    Window 0: +6.4%  (6 trades) ✅
    Window 1: -2.1%  (17 trades) ❌
    Window 2: +17.2%  (14 trades) ✅
    Profitable: 2/3 windows

  Top Factors:
    crypto_bollinger_fast                    0.0226 ████
    momentum_3d                              0.0187 ███
    previous_low_test                        0.0252 █████

  👉 Ready for more? Run full evolution:
     stratevo evolve --market crypto

Why StratEvo?

Other tools: Write a strategy → Code → Backtest → Tweak → Repeat
StratEvo: Define the search space → GA evolves strategies → Walk-forward filters survivors

Most quant tools expect you to write the strategy. StratEvo skips that — a genetic algorithm breeds strategies from 484 factors, then walk-forward tests them on unseen data. You get strategies that survived out-of-sample, not just curve-fitted backtests.

StratEvo Freqtrade FinRL / Qlib
Strategy creation GA evolves 484-dim DNA You write rules DRL trains agent
Continuous evolution ✅ Strategies keep evolving ❌ Strategy fixed ❌ Training offline
Walk-forward validation ✅ Multi-window + Monte Carlo ❌ Plugin needed ⚠️ Partial
Trailing stop ✅ Evolvable (activation + trail %) ✅ Manual config
Position sizing ✅ Signal-strength weighted ⚠️ Fixed or stake_amount
Market regime adaptation ✅ Auto-reduce in bear market
Portfolio correlation guard ✅ Rejects correlated picks ⚠️ Partial
Zero API keys to start ❌ Needs exchange keys ❌ Needs data setup
Markets Crypto + A-shares + US Crypto only A-shares (Qlib)
MCP server for AI agents
Community & ecosystem 🆕 Small, early-stage ✅ Large, mature ✅ Active (Qlib)
Documentation ⚠️ Growing ✅ Comprehensive ✅ Extensive
Live trading maturity ⚠️ Paper trading only ✅ Production-tested ⚠️ Research-focused

How Evolution Works

   Seed population (random factor weights)
         │
         ▼
   ┌─────────────┐
   │  Backtest    │  Walk-forward: multi-window OOS validation
   │  each DNA    │  Slippage modeled, position caps, real fees
   └──────┬──────┘
          │
          ▼
   Select top performers (Sharpe × Return / MaxDrawdown)
          │
          ▼
   ┌─────────────────────────────────────────┐
   │  Cross-sectional neutralization (P0-2)  │
   │  Correlation-aware selection    (P0-1)  │
   │  Factor diversity bonus         (P0-3)  │
   │  Turnover cost penalty          (P0-4)  │
   └──────┬──────────────────────────────────┘
          │
          ▼
   Mutate + Crossover → next generation
          │
          ▼
        Repeat

Evolution Flow

StratEvo Architecture
System architecture: data ingestion → factor computation → genetic evolution → walk-forward validation

Every DNA is a weight vector across 484 factors plus advanced risk/position parameters — all evolvable:

Parameter What it controls
hold_days Hold period per trade (2–60 days — day trades to swing trades)
capital_utilization Fraction of capital deployed (0.3–1.0)
position_sizing_power Signal strength → allocation weight (0=equal, 2=quadratic)
trailing_stop Lock in profits: trail N% below peak price
trend_exit_enabled Exit on MA crossover — cut losses before stop-loss
market_regime_sensitivity Auto-reduce exposure in bear markets
profit_target_scaling Scale take-profit by signal confidence
time_decay_exit Tighten stop-loss as hold period extends
scale_in_tranches Split entry into 1-3 tranches
sector_max_pct Cap sector concentration (diversification)
kelly_fraction Kelly criterion position sizing based on recent win rate

The GA tries combinations you wouldn't think of. Anti-overfitting is built in: Arena mode runs multiple strategies simultaneously and penalizes crowded signals.

stratevo evolve --market crypto --generations 50
stratevo evolve --pareto --market crypto     # Multi-objective (NSGA-III)
stratevo evolve --logic-guided               # Semantically guided mutations

📊 484 Factors — 284 general + 200 crypto-native (click to expand)

All normalized to [0, 1]:

Category Count Examples
Crypto-Native 200 Funding rate, session effects, whale detection, liquidation cascade
Momentum 14 ROC, acceleration, trend strength
Volume & Flow 13 OBV, smart money, Wyckoff VSA
Volatility 13 ATR, Bollinger squeeze, vol-of-vol
Mean Reversion 12 Z-score, Keltner channel position
Trend Following 14 ADX, EMA golden cross, MA fan
Qlib Alpha158 11 KMID, KSFT, CNTD (Microsoft Qlib compatible)
Risk Warning 11 Consecutive losses, death cross, gap-down
Quality Filter 11 Earnings momentum, relative strength
Price Structure 10 Candlestick patterns, support/resistance
Sentiment 2 EN/ZH keyword sentiment + momentum
DRL Signal (experimental) 2 Q-learning buy probability + state value

Weights are determined by the evolution engine — no manual tuning.


Plugin Architecture

StratEvo is designed for extensibility. Every component uses a base class + registry + auto-discovery pattern:

stratevo/
├── factors/           # BaseFactor → add trading factors
│   └── builtin/       # 15 built-in factors (RSI, MACD, ATR, ...)
├── fitness/           # BaseFitness → customize "what's a good strategy"
│   └── builtin/       # 6 built-in (Sharpe, Calmar, Sortino, Composite, ...)
├── datasources/       # BaseDataSource → add data providers
├── exchanges/         # ExchangeAdapter → add exchange connectors
└── cli/commands/
    └── scaffold.py    # Generate boilerplate for any component

Add a factor in 3 minutes:

stratevo scaffold factor --name my_factor --category momentum
# Edit stratevo/factor_registry/builtin/my_factor.py → implement compute()
# Edit tests/test_my_factor.py → verify it works
# PR it!

See CONTRIBUTING.md for the full guide.


Anti-Overfitting

StratEvo doesn't just backtest — it tries to break your strategy:

  • Arena Mode — Multiple strategies compete in the same simulated market. Crowded signals get penalized.
  • Monte Carlo — 1,000 iterations, p-value < 0.05
  • Walk-Forward — Multi-window OOS validation with bootstrap confidence intervals
  • Cross-Sectional Neutralization — Z-score normalize scores to filter market-wide noise
  • Correlation Guard — Rejects highly correlated stock picks (>0.85 Pearson)
  • Factor Diversity — HHI-based bonus rewards diversified factor usage, penalizes concentration
  • Bias Detection — Look-ahead, snooping, survivorship checks
  • Factor Orthogonality — Auto-removes redundant factors
  • Turnover Penalty — Excessive trading gets penalized in fitness (modeled as real cost)

Real Evolution Results

These are actual numbers from our running evolution engines — not cherry-picked backtests.

A-Share Elite (428 stocks, 30-DNA population):

Generation Fitness CAGR Sharpe Max Drawdown Win Rate Trades
Gen 0 4.88 16.5% 0.64 16.3%
Gen 4 18.66 50.1% 0.82 27.9% 32.3% 414
Gen 6 🏆 61.33 58.2% 1.19 36.4% 43.9% 430

Walk-forward out-of-sample (Gen 6 — all 3 windows profitable):

  • Window 0: +13.4% annual (worst)
  • Window 1: +200.0% annual (best)
  • Window 2: +16.4% annual

Crypto (17 assets, 30-DNA population):

Generation Fitness CAGR Sharpe Max Drawdown Win Rate
Gen 0 8.37 26.7% 0.65 18.5%
Gen 19 🏆 31.67 54.8% 1.93 14.3% 51.0%

⚠️ Honest caveats: These are walk-forward backtests, not live trading. Real results will differ. Previous versions had a look-ahead bias bug that was fixed — see Honest Disclosure. Gen 6 is early; we need 100+ generations to draw conclusions.


MCP Server

Expose StratEvo as tools for Claude, Cursor, VS Code, or any MCP client:

{
  "mcpServers": {
    "stratevo": {
      "command": "stratevo",
      "args": ["mcp", "serve"]
    }
  }
}

10 tools: get_quote, get_history, list_exchanges, run_backtest, analyze_portfolio, get_indicators, screen_stocks, get_sentiment, compare_strategies, get_funding_rates.


Key Commands

Command What it does
stratevo demo See all features in action
stratevo quote AAPL Real-time US stock quote
stratevo quote BTC/USDT Crypto quote via ccxt
stratevo evolve --market crypto Run genetic evolution
stratevo evolve --pareto Multi-objective Pareto evolution
stratevo backtest -t AAPL Backtest a strategy
stratevo check-backtest Verify backtest integrity
stratevo analyze TSLA Technical analysis
stratevo copilot AI financial assistant
stratevo mcp serve Start MCP server
stratevo paper Paper trading mode
python -m stratevo.viz.evolution_tree <log> ASCII evolution timeline
python -m stratevo.viz.parse_evolution_log <log> Parse evolution log → JSON

70+ commands total — run stratevo --help for the full list.


Data Sources

Market Source API Key?
Crypto ccxt (100+ exchanges) No
US Stocks Yahoo Finance No
A-Shares AKShare + BaoStock No
Sentiment CryptoCompare + AKShare No

Dashboard

The web dashboard (dashboard/) provides 7 pages: market overview, backtesting, strategy comparison, evolution monitoring, portfolio management, stock screening, and individual stock analysis with technical indicators.

cd dashboard && npm install && npm run dev

Note: Dashboard screenshots are from development builds and may show placeholder data. Run the dashboard locally to see live results from your own evolution runs.


Demo

StratEvo Demo
Watch: How StratEvo's Evolution Engine Works (2 min)


Roadmap

  • 484-factor evolution engine
  • Walk-forward + Monte Carlo + Arena mode
  • Bias detection suite
  • MCP server for AI agents
  • Multi-objective Pareto evolution (NSGA-III)
  • Market Logic Layer (semantically guided mutations)
  • Paper trading infrastructure
  • Evolution visualization (CLI ASCII tree + interactive HTML dashboard)
  • Advanced position sizing (signal-strength weighted)
  • Trailing stop loss (evolvable activation + trail %)
  • Market regime adaptation (auto-reduce in bear markets)
  • Cross-sectional score neutralization
  • Portfolio correlation guard
  • Factor diversity optimization (HHI-based)
  • Swing trading support (hold periods up to 60 days, dynamic trend exits)
  • Plugin architecture (Factor/Fitness/DataSource registries + scaffold CLI)
  • DEX execution (Uniswap V3 / Arbitrum)
  • Multi-timeframe strategy evolution (1h / 4h / 1d)
  • Multi-strategy ensemble (regime-switching)
  • Short selling for crypto
  • Factor decay detection (rolling IC monitoring)
  • Foundation model for price sequences
  • Web dashboard with live P&L tracking
  • QuantConnect-style cloud execution (SaaS)
  • Mobile alerts via Telegram/Discord
  • Community strategy marketplace

Disclaimer

This project is for educational and research purposes only. Not financial advice. Past performance does not guarantee future results. Always paper trade first.


Also Check Out

Project What it does
ClawGuard AI Agent Immune System — 480+ threat patterns, zero dependencies
AgentProbe Playwright for AI Agents — test, record, replay agent behaviors

Contributing

StratEvo is built for contributors. The plugin architecture makes it easy to add new components without touching core code.

Easiest way to contribute: Add a Factor

# 1. Generate boilerplate
stratevo scaffold factor --name bollinger_squeeze --category volatility

# 2. Implement compute() in the generated file
# 3. Run tests
pytest tests/test_bollinger_squeeze.py -v

# 4. Submit a PR ✅

That's it — one file, one function, one PR. The scaffold command generates both the factor and its test template.

What you can contribute

Component Difficulty Command
Factors 🟢 Easy stratevo scaffold factor --name xxx --category momentum
Fitness functions 🟡 Medium stratevo scaffold fitness --name xxx
Data sources 🟡 Medium stratevo scaffold datasource --name xxx
Strategy DNA 🟠 Advanced Share evolved YAML configs
Bug fixes 🟢-🟡 Check good first issue

Get started

git clone https://github.com/NeuZhou/stratevo.git
cd stratevo && pip install -e ".[dev]" && pytest

CONTRIBUTING.md · Discord · Report Bug · Request Feature


If this is useful, a ⭐ helps others find it.


License

AGPL-3.0


Star History

Star History

Honest Disclosure

Previous versions reported inflated backtest returns caused by look-ahead bias and short validation windows. This has been fixed — scoring uses previous-period data, position sizes are capped, slippage is modeled, and walk-forward validation uses year-long OOS windows with OOS return gates (strategies that lose money out-of-sample get zero or negative fitness regardless of in-sample performance). Use stratevo check-backtest to verify results.