Metadata-Version: 2.4
Name: stratevo
Version: 6.0.4
Summary: AI-native quantitative finance engine with genetic algorithm strategy evolution
Author-email: NeuZhou <neuzhou@users.noreply.github.com>
License-Expression: AGPL-3.0-only
Project-URL: Homepage, https://github.com/NeuZhou/stratevo
Project-URL: Documentation, https://github.com/NeuZhou/stratevo/tree/master/docs
Project-URL: Repository, https://github.com/NeuZhou/stratevo
Project-URL: Issues, https://github.com/NeuZhou/stratevo/issues
Keywords: quantitative-finance,trading,backtesting,mcp,ai-agent,crypto,bitcoin,genetic-algorithm,ccxt,algorithmic-trading,paper-trading,stock-screening,factor-investing,walk-forward,evolution-strategy
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiohttp>=3.8.0
Requires-Dist: numpy>=1.21.0
Requires-Dist: pandas>=1.3.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: requests>=2.28.0
Requires-Dist: scipy>=1.9.0
Provides-Extra: cn
Requires-Dist: akshare>=1.10.0; extra == "cn"
Provides-Extra: us
Requires-Dist: yfinance>=0.2.0; extra == "us"
Provides-Extra: crypto
Requires-Dist: ccxt>=4.0.0; extra == "crypto"
Provides-Extra: hmm
Requires-Dist: hmmlearn>=0.3.0; extra == "hmm"
Provides-Extra: full
Requires-Dist: aiohttp; extra == "full"
Requires-Dist: websockets; extra == "full"
Requires-Dist: ccxt>=4.0.0; extra == "full"
Requires-Dist: akshare>=1.10.0; extra == "full"
Requires-Dist: yfinance>=0.2.0; extra == "full"
Requires-Dist: pymoo>=0.6.0; extra == "full"
Requires-Dist: hmmlearn>=0.3.0; extra == "full"
Provides-Extra: ml
Requires-Dist: numpy; extra == "ml"
Requires-Dist: scikit-learn; extra == "ml"
Provides-Extra: pareto
Requires-Dist: pymoo>=0.6.0; extra == "pareto"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5; extra == "docs"
Requires-Dist: mkdocs-material>=9.0; extra == "docs"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: pytest-aiohttp>=1.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Dynamic: license-file

<div align="center">
<br>
<p align="center">
<img src="assets/hero-stratevo.png" alt="StratEvo" width="480">
</p>

**Stop writing trading strategies. Evolve them.**

An open-source genetic algorithm engine that evolves and walk-forward tests trading strategies across 484 market factors. No manual rules, no API keys, no PhD required.

<p align="center">
  <a href="https://pypi.org/project/stratevo/"><img src="https://img.shields.io/pypi/v/stratevo?color=blue" alt="PyPI"></a>
  <a href="https://github.com/NeuZhou/stratevo/actions/workflows/ci.yml"><img src="https://github.com/NeuZhou/stratevo/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
  <a href="https://codecov.io/gh/NeuZhou/stratevo"><img src="https://codecov.io/gh/NeuZhou/stratevo/graph/badge.svg" alt="codecov"></a>
  <img src="https://img.shields.io/badge/evolvable_factors-484-orange" alt="484 Evolvable Factors">
  <img src="https://img.shields.io/badge/tests-10,850+-brightgreen" alt="10850+ Tests">
  <a href="https://discord.gg/kAQD7Cj8"><img src="https://img.shields.io/discord/1488800950696284272?color=7289da&label=Discord&logo=discord&logoColor=white" alt="Discord"></a>
  <a href="https://github.com/NeuZhou/stratevo/stargazers"><img src="https://img.shields.io/github/stars/NeuZhou/stratevo?style=social" alt="Stars"></a>
</p>

<p>
  <a href="#30-second-demo">Demo</a> ·
  <a href="#real-results">Results</a> ·
  <a href="LIVE_PERFORMANCE.md"><strong>📊 Live Performance</strong></a> ·
  <a href="#docker">Docker</a> ·
  <a href="#strategy-styles">Styles</a> ·
  <a href="#multi-dna-voting">Ensemble</a> ·
  <a href="#anti-overfitting">Robustness</a> ·
  <a href="#for-contributors">Contribute</a> ·
  <a href="https://discord.gg/kAQD7Cj8">Discord</a>
</p>

</div>

---

## 30-Second Demo

```bash
pip install stratevo
stratevo analyze AAPL          # Quick analysis with evolved strategies
stratevo evolve --quick        # See evolution in ~2 minutes
```

That's it. No config files, no API keys, no exchange accounts, no LLM required. Pure Python + math.

<p align="center">
  <img src="docs/images/crypto_evolution.gif" alt="Strategy Evolution" width="640">
</p>

<sub><strong>Real evolution run:</strong> 9 crypto assets, 600 generations. Fitness goes from random noise to 33% annual return, 6.06 Sharpe, 5.6% max drawdown. (Backtest only, not live trading)</sub>

---

## Docker

Zero-setup. No Python version issues, no dependency conflicts.

```bash
# See evolution in 30 seconds (built-in demo data)
docker compose up demo

# Run a quick evolution (~2 minutes)
docker compose up quick

# Full crypto evolution: auto-downloads data + evolves
docker compose up evolve-crypto

# Analyze any symbol
docker compose run --rm analyze analyze BTC
```

<details>
<summary>Manual install (without Docker)</summary>

```bash
pip install stratevo
stratevo evolve --demo            # 30-second demo
stratevo evolve --quick           # ~2 minute evolution
stratevo download-crypto          # Download BTC/ETH/SOL data
stratevo evolve --market crypto   # Full evolution run
```

</details>

---

## What's Different Here

Most quant tools make you **write** the strategy. You pick indicators, set thresholds, run a backtest, tweak, repeat. It works — if you already know what to look for.

StratEvo takes the opposite approach: it **evolves** strategies. A genetic algorithm searches across 484 factors and finds weight combinations that actually work out-of-sample.

You don't pick the indicators. The algorithm does. You decide how long to let it search.

```
You write the rules        →  StratEvo discovers the rules
You tune parameters        →  GA tunes parameters  
You test on one period     →  Walk-forward tests on multiple windows
You hope it generalizes    →  Monte Carlo measures if it does
```

### Why Genetic Algorithms?

GAs are good at problems where the search space is huge and the relationship between inputs isn't obvious — which is exactly what trading strategy design looks like. With 484 factors, the number of weight combinations is absurd. Grid search won't cut it. Manual tuning takes forever. GAs get around this by keeping what works and mutating what doesn't, generation after generation.

---

## Strategy Styles

When StratEvo evolves a strategy, the resulting "DNA" (a vector of 484 factor weights) falls into a recognizable style based on which factors dominate:

| Style | Heavy Factors | What the Algorithm Found |
|-------|-------------|-------------|
| **Value Seeker** | P/E, P/B, earnings yield | Buys cheap, holds patient. Benjamin Graham would recognize this DNA. |
| **Momentum Rider** | ROC, acceleration, trend strength | Chases what's moving, cuts what isn't. The DNA learned that trends persist. |
| **Mean Reverter** | Z-score, Keltner position, %B | Bets on bounce-backs. Statistical arbitrage without the PhD. |
| **Flow Reader** | OBV, smart money flow, Wyckoff VSA | Follows the money. Volume precedes price — the DNA figured that out. |
| **Volatility Hunter** | ATR squeeze, vol-of-vol | Profits from volatility expansion. Sits during calm, strikes during storms. |
| **Crypto Native** | Funding rate, liquidation cascade | 200 factors built for a 24/7 market that doesn't follow TradFi rules. |

These aren't made up — they're what the algorithm actually converged on.

---

## Multi-DNA Voting

Instead of betting on a single evolved strategy, run **multiple DNAs** and aggregate their signals:

```bash
stratevo analyze AAPL --ensemble 5    # 5 strategies vote on one stock
```

```
  Multi-DNA Analysis: AAPL
  ═══════════════════════════════════════
  
  Strategy Votes:
    Value Seeker       → BUY   (score: 0.72, confidence: high)
    Momentum Rider     → BUY   (score: 0.85, confidence: high)  
    Mean Reverter      → HOLD  (score: 0.45, confidence: medium)
    Flow Reader        → BUY   (score: 0.68, confidence: medium)
    Volatility Hunter  → HOLD  (score: 0.51, confidence: low)

  Consensus: BUY (3/5 bullish, 0/5 bearish)
  Combined Score: 0.64
  
  This is a research tool, not financial advice.
```

Each strategy was independently evolved. Agreement = stronger signal. Disagreement = mixed picture, worth looking closer.

---

## How It Works

```
  Random DNA population (484 factor weights + risk parameters)
       │
       ▼
  ┌──────────────────────┐
  │  Walk-Forward Test   │  Multi-window out-of-sample validation
  │  each DNA candidate  │  Real fees, slippage, position caps
  └──────────┬───────────┘
             │
             ▼
  Keep the survivors (Sharpe × Return / MaxDD)
             │
             ▼
  Mutate + Crossover → next generation
             │
             ▼
  Repeat for N generations
```

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

| Parameter | Range | What it controls |
|-----------|-------|-----------------|
| Factor weights (×484) | 0.0–1.0 | Which factors matter and how much |
| `hold_days` | 2–60 | Day trades through swing trades |
| `trailing_stop` | % | Lock in profits, trail below peak |
| `market_regime` | sensitivity | Auto-reduce exposure in bear markets |
| `kelly_fraction` | 0–1 | Position sizing based on recent win rate |

The GA tries combinations you wouldn't. That's the point.

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

---

## Anti-Overfitting

We learned the hard way. An early version showed 25,000% returns — it was a bug (look-ahead bias). Here's what prevents that now:

| Defense | What it does |
|---------|-------------|
| **Walk-Forward** | Multi-window OOS validation. Must profit on data it never trained on. |
| **Monte Carlo** | 1,000 shuffled iterations. p-value < 0.05 or it's luck. |
| **Arena Mode** | Multiple strategies compete simultaneously. Crowded signals get penalized. |
| **Correlation Guard** | Rejects picks correlated above 0.85. No fake diversification. |
| **Factor Diversity** | HHI-based penalty for over-relying on one factor group. |
| **Turnover Penalty** | Excessive trading gets punished in fitness. Real transaction costs modeled. |
| **Bias Detection** | Look-ahead, snooping, survivorship — flagged automatically. |

```bash
stratevo check-backtest    # Verify any result's integrity
```

**Transparency note:** Our early versions had inflated returns from look-ahead bias. We fixed it, disclosed it publicly, and added `check-backtest` so you can verify results yourself. Honest 45% beats fabricated 25,000%.

---

## Real Results

> **Actual numbers** from our running evolution engines. Not cherry-picked. Updated live.

### 🇺🇸 US Stocks (50 S&P 500 stocks, V3 — Gen 31)

| Metric | Best DNA |
|:------:|:--------:|
| Annual Return | **45.0%** |
| Sharpe Ratio | **1.67** |
| Max Drawdown | 16.2% |
| Win Rate | 59.2% |
| Profit Factor | 1.63 |
| Total Trades | 232 |

#### Walk-Forward Validation — All 4 Windows Profitable ✅

| Window | Period | OOS Annual Return | AAPL Buy&Hold | OOS Sharpe | Trades | Win Rate |
|:------:|:------:|:-----------------:|:-------------:|:----------:|:------:|:--------:|
| W0 | Dec 2022 – Jul 2023 | **+80.1%** | +88.9% | 2.36 | 55 | 60.0% |
| W1 | Jul 2023 – Feb 2024 | **+24.1%** | -8.9% | 1.62 | 45 | 60.0% |
| W2 | Feb 2024 – Sep 2024 | **+23.2%** | +39.6% | 0.88 | 69 | 56.5% |
| W3 | Sep 2024 – Apr 2025 | **+60.5%** | -18.0% | 1.83 | 63 | 60.3% |

<sub>All 4 windows OOS-profitable. W0 trailed AAPL buy-and-hold during the 2023 rally; W1 and W3 significantly outperformed in flat/down markets — where active strategies should add value.</sub>

---

### ₿ Crypto (20 assets, V12 — Gen 108)

<p align="center">
  <img src="docs/images/evolution_crypto.png" alt="Crypto Strategy Evolution" width="720">
</p>

| Metric | Best DNA |
|:------:|:--------:|
| Annual Return | **105.6%** |
| Sharpe Ratio | **2.89** |
| Max Drawdown | 14.8% |
| Win Rate | 44.0% |
| Profit Factor | 1.89 |
| Total Trades | 150 |

#### Walk-Forward Validation — 4 of 5 Windows Profitable

| Window | Period | OOS Annual Return | BTC Buy&Hold | OOS Sharpe | Trades | Win Rate |
|:------:|:------:|:-----------------:|:------------:|:----------:|:------:|:--------:|
| W0 | Jan 2025 – Mar 2025 | -42.8% | -62.2% | -1.87 | 30 | 16.7% |
| W1 | Mar 2025 – May 2025 | **+10.4%** | +195.7% | 0.84 | 30 | 43.3% |
| W2 | May 2025 – Jul 2025 | **+98.2%** | +111.0% | 2.83 | 30 | 43.3% |
| W3 | Jul 2025 – Sep 2025 | **+524.0%** | +2.4% | 6.50 | 30 | 53.3% |
| W4 | Sep 2025 – Oct 2025 | **+370.3%** | +20.5% | 6.13 | 30 | 63.3% |

<sub>W3/W4 massively outperformed BTC buy-and-hold. W1 missed the Mar–May 2025 rally (BTC +195% annualized vs strategy +10%). W0 lost money but less than BTC itself (-42.8% vs -62.2%). We're working on cross-regime robustness (GT-Score fitness function, <a href="https://arxiv.org/abs/2602.00080">arXiv:2602.00080</a>).</sub>

---

**Caveats:** These are backtests, not live trades. Real results will differ. We hide nothing.

---

## Paper Trading

Test strategies with real market data, simulated execution:

```bash
stratevo paper start --exchange okx --balance 100000
stratevo paper status
stratevo paper report
```

Track P&L, win rates, and drawdowns before risking real money.

---

## 484 Factors

<details>
<summary>Click to expand full factor list</summary>

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 |
| DRL Signal | 2 | Q-learning buy probability |

All factor weights are discovered by evolution — no manual tuning required.

</details>

---

## Data Sources

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

---

## MCP Server

StratEvo exposes its tools to any MCP-compatible AI client (Claude Desktop, Cursor, etc.). The MCP server itself doesn't need an LLM — your AI client provides the intelligence, StratEvo provides the data and computation:

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

10 tools: `get_quote`, `run_backtest`, `analyze_portfolio`, `screen_stocks`, and more.

---

## AI Copilot (Optional)

StratEvo includes an optional AI copilot for natural-language strategy exploration. **This is the only feature that requires an LLM API key** — everything else (evolve, analyze, backtest, paper trading) works without one.

```bash
# Set any ONE of these — StratEvo auto-detects the provider
export OPENAI_API_KEY="sk-..."           # OpenAI (GPT-4o-mini)
export GEMINI_API_KEY="AIza..."          # Google Gemini
export ANTHROPIC_API_KEY="sk-ant-..."    # Anthropic Claude
export DEEPSEEK_API_KEY="sk-..."         # DeepSeek
export GROQ_API_KEY="gsk_..."            # Groq (Llama 3)
# Or run local models — no API key needed:
# export OLLAMA_BASE_URL="http://localhost:11434/v1"

stratevo copilot
```

Supported: OpenAI, Anthropic, Gemini, DeepSeek, Groq, Mistral, Moonshot, Azure OpenAI, Ollama (local).

---

## For Contributors

StratEvo's plugin architecture makes contributing easy. Adding a new factor is often one file, one function, one PR:

```bash
stratevo scaffold factor --name my_signal --category momentum
# Edit the generated file, implement compute(), submit PR
```

| Component | Difficulty |
|-----------|:----------:|
| Factors | Easy |
| Fitness functions | Medium |
| Data sources | Medium |
| Strategy DNA configs | Advanced |

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

[CONTRIBUTING.md](CONTRIBUTING.md) · [Discord](https://discord.gg/kAQD7Cj8) · [Issues](https://github.com/NeuZhou/stratevo/issues)

---

## Roadmap

- [x] 484-factor evolution engine
- [x] Walk-forward + Monte Carlo + Arena mode
- [x] Multi-DNA ensemble voting
- [x] Strategy style classification
- [x] Paper trading
- [x] MCP server for AI tools
- [x] Plugin architecture
- [ ] Streamlit dashboard (live evolution tracking)
- [ ] DEX execution (Uniswap V3)
- [ ] Multi-timeframe evolution
- [ ] Community strategy marketplace

---

## License

**Dual-licensed** under [AGPL-3.0](LICENSE) and a [Commercial License](COMMERCIAL.md).

- 🆓 **Open Source (AGPL-3.0):** Free for personal use, research, education, and open source projects
- 💼 **Commercial License:** Required for paid signal services, proprietary SaaS, or closed-source commercial use

👉 See [COMMERCIAL.md](COMMERCIAL.md) for details or contact [neuzhou@outlook.com](mailto:neuzhou@outlook.com) for licensing.

---

<div align="center">

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

[English](README.md) · [中文](README.zh-CN.md) · [한국어](README.ko.md) · [日本語](README.ja.md)

</div>
