Metadata-Version: 2.4
Name: finclaw-ai
Version: 5.6.1
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/finclaw
Project-URL: Documentation, https://github.com/NeuZhou/finclaw/tree/master/docs
Project-URL: Repository, https://github.com/NeuZhou/finclaw
Project-URL: Issues, https://github.com/NeuZhou/finclaw/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

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

<div align="center">

# FinClaw

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

**Vibe Evolving** — Stop writing strategies. Let them evolve.

<p align="center">
  <img src="assets/hero-finclaw.png" alt="FinClaw" width="720">
</p>

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

<p align="center">
  <img src="docs/images/crypto_evolution.gif" alt="Strategy Evolution — Fitness climbing from random to optimized over 600 generations" width="720">
</p>

<sub>⬆️ 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.</sub>

<p>
  <a href="https://pypi.org/project/finclaw-ai/"><img src="https://img.shields.io/pypi/v/finclaw-ai?color=blue" alt="PyPI"></a>
  <a href="https://github.com/NeuZhou/finclaw/actions/workflows/ci.yml"><img src="https://github.com/NeuZhou/finclaw/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
  <a href="https://codecov.io/gh/NeuZhou/finclaw"><img src="https://codecov.io/gh/NeuZhou/finclaw/graph/badge.svg" alt="codecov"></a>
  <a href="https://opensource.org/licenses/AGPL-3.0"><img src="https://img.shields.io/badge/License-AGPL--3.0-blue.svg" alt="License"></a>
  <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.10+-blue" alt="Python 3.10+"></a>
  <img src="https://img.shields.io/badge/factors-484-orange" alt="484 Factors">
  <img src="https://img.shields.io/badge/tests-7,960+-brightgreen" alt="7960+ 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/finclaw/stargazers"><img src="https://img.shields.io/github/stars/NeuZhou/finclaw?style=social" alt="GitHub Stars"></a>
</p>

<p>
  <a href="#quick-start">Quick Start</a> ·
  <a href="#why-finclaw">Why FinClaw?</a> ·
  <a href="#how-evolution-works">How It Works</a> ·
  <a href="#mcp-server">MCP Server</a> ·
  <a href="https://discord.gg/kAQD7Cj8">Discord</a>
</p>

</div>

---

## Quick Start

```bash
pip install finclaw-ai
finclaw evolve --quick            # See results in ~2 minutes
finclaw 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.

<details>
<summary>What does it look like? (click to expand)</summary>

```
$ finclaw evolve --quick

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

============================================================
 FinClaw 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:
     finclaw evolve --market crypto
```

</details>

---

## Why FinClaw?

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

Most quant tools expect you to write the strategy. FinClaw 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.

| | FinClaw | 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 | ✅ | ❌ | ❌ |

---

## 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
```

<p align="center">
  <img src="docs/images/evolution-flow.png" alt="Evolution Flow" width="720">
</p>

<!-- architecture diagram -->

<p align="center">
<p align="center">
  <img src="docs/images/finclaw-architecture.png" alt="FinClaw Architecture" width="720">
  <br>
  <em>System architecture: data ingestion → factor computation → genetic evolution → walk-forward validation</em>
</p>

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.

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

---

<details>
<summary>📊 484 Factors — 284 general + 200 crypto-native (click to expand)</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 + momentum |
| DRL Signal *(experimental)* | 2 | Q-learning buy probability + state value |

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

</details>

---

## Anti-Overfitting

FinClaw 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)

---

## MCP Server

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

```json
{
  "mcpServers": {
    "finclaw": {
      "command": "finclaw",
      "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 |
|---------|-------------|
| `finclaw demo` | See all features in action |
| `finclaw quote AAPL` | Real-time US stock quote |
| `finclaw quote BTC/USDT` | Crypto quote via ccxt |
| `finclaw evolve --market crypto` | Run genetic evolution |
| `finclaw evolve --pareto` | Multi-objective Pareto evolution |
| `finclaw backtest -t AAPL` | Backtest a strategy |
| `finclaw check-backtest` | Verify backtest integrity |
| `finclaw analyze TSLA` | Technical analysis |
| `finclaw copilot` | AI financial assistant |
| `finclaw mcp serve` | Start MCP server |
| `finclaw paper` | Paper trading mode |
| `python -m finclaw.viz.evolution_tree <log>` | ASCII evolution timeline |
| `python -m finclaw.viz.parse_evolution_log <log>` | Parse evolution log → JSON |

70+ commands total — run `finclaw --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.

```bash
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

<p align="center">
  <a href="https://www.youtube.com/watch?v=Y3wY9rj0PmE">
    <img src="https://img.youtube.com/vi/Y3wY9rj0PmE/maxresdefault.jpg" alt="FinClaw Demo" width="560">
  </a>
  <br>
  <em>Watch: How FinClaw's Evolution Engine Works (2 min)</em>
</p>

---

## Roadmap

- [x] 484-factor evolution engine
- [x] Walk-forward + Monte Carlo + Arena mode
- [x] Bias detection suite
- [x] MCP server for AI agents
- [x] Multi-objective Pareto evolution (NSGA-III)
- [x] Market Logic Layer (semantically guided mutations)
- [x] Paper trading infrastructure
- [x] Evolution visualization (CLI ASCII tree + interactive HTML dashboard)
- [x] Advanced position sizing (signal-strength weighted)
- [x] Trailing stop loss (evolvable activation + trail %)
- [x] Market regime adaptation (auto-reduce in bear markets)
- [x] Cross-sectional score neutralization
- [x] Portfolio correlation guard
- [x] Factor diversity optimization (HHI-based)
- [x] Swing trading support (hold periods up to 60 days, dynamic trend exits)
- [ ] DEX execution (Uniswap V3 / Arbitrum)
- [ ] Multi-timeframe strategy evolution (1h / 4h / 1d)
- [x] 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](https://github.com/NeuZhou/clawguard)** | AI Agent Immune System — 480+ threat patterns, zero dependencies |
| **[AgentProbe](https://github.com/NeuZhou/agentprobe)** | Playwright for AI Agents — test, record, replay agent behaviors |

---

## Contributing

Want to contribute? Here's the quick path:

1. **Pick an issue** — [`good first issue`](https://github.com/NeuZhou/finclaw/labels/good%20first%20issue) is a good starting point
2. **Fork & clone**
   ```bash
   git clone https://github.com/NeuZhou/finclaw.git
   cd finclaw && pip install -e ".[dev]" && pytest
   ```
3. **Submit a PR** — we'll review it

[CONTRIBUTING.md](CONTRIBUTING.md) · [Discord](https://discord.gg/kAQD7Cj8) · [Report Bug](https://github.com/NeuZhou/finclaw/issues) · [Request Feature](https://github.com/NeuZhou/finclaw/issues)

---

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

---

## License

[AGPL-3.0](LICENSE)

---

## Star History

<a href="https://www.star-history.com/#NeuZhou/finclaw&Date">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=NeuZhou/finclaw&type=Date&theme=dark" />
    <img alt="Star History" src="https://api.star-history.com/svg?repos=NeuZhou/finclaw&type=Date" />
  </picture>
</a>

---

## 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 `finclaw check-backtest` to verify results.
