diff --git a/README.md b/README.md index 208a58b..3622211 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Multi_Swarm_Coevolutive -Proof-of-concept di sistema co-evolutivo multi-agente per trading quantitativo. Un genetic algorithm fa evolvere una popolazione di agenti LLM (Hypothesis swarm) che generano strategie di trading espresse in JSON strutturato; un layer Falsification deterministico le backtesta su dati storici BTC-PERPETUAL via Cerbero MCP; un layer Adversarial euristico le sottopone a red-team checks; la fitness combina Deflated Sharpe Ratio (Bailey & López 2014), Sharpe normalizzato e penalizzazione di drawdown. Il tutto è ispirato alla filosofia di Renaissance Technologies adattata a un contesto retail single-author con LLM agents. +Proof-of-concept di sistema co-evolutivo multi-agente per trading quantitativo. Un genetic algorithm fa evolvere una popolazione di agenti LLM (Hypothesis swarm) che generano strategie di trading espresse in JSON strutturato; un layer Falsification deterministico le backtesta su dati storici (default BTC-PERPETUAL Deribit) via Cerbero MCP; un layer Adversarial euristico le sottopone a red-team checks; la fitness combina Deflated Sharpe Ratio (Bailey & López 2014), Sharpe normalizzato e penalizzazione di drawdown, con opzioni v2 soft-kill e combined IS/OOS per Walk-Forward Validation. Il tutto è ispirato alla filosofia di Renaissance Technologies adattata a un contesto retail single-author con LLM agents. ## Repository @@ -12,22 +12,22 @@ git clone ssh://git@git.tielogic.xyz:222/Adriano/Multi_Swarm_Coevolutive.git ## Stato del progetto -**Phase 1 (lean spike) completata** il 10 maggio 2026 con tutti i 5 hard gate passati (loop convergence, parse success 100%, top-5 ratio 1116x, entropy 0.914, costo $0.069 vs cap $700). Decisione strategica: **GO Phase 2** con tre aggiustamenti (Adversarial soglie più strette, speciation, walk-forward 70/30). +**Phase 3 (paper-trading forward-test) in corso** dal 13 maggio 2026 su VPS. Runner `scripts/run_paper_trading.py` live 24/7 in Docker (`https://swarm.tielogic.xyz` per la dashboard) con due strategie freezate: -**Phase 1.5 (tactical hardening) in corso**: Adversarial layer rinforzato con soglie più strette (`overtrading` a `n_bars/20`, `undertrading` HIGH se `n<10`) e due nuovi check HIGH (`flat_too_long` se signal flat >95% bar, `fees_eat_alpha` se fees > 50% del gross PnL). Killa le strategie degeneri del run v5 (top-1 era flat 99.8% del tempo e ha sottoperformato BTC B&H di −103 punti percentuali). +- `strategies/btc_fb63e851.json` — BTC-PERPETUAL, true alpha hour-gated (RSI estremi + ATR vs SMA + filtro orario 9-17), Sharpe OOS +0,26 su 7,33 anni di storia. +- `strategies/eth_facd6af85d5d.json` — ETH-PERPETUAL, trend-following long-bias + vol regime, Sharpe OOS +0,19 su 6,75 anni. -Documenti chiave: +Phase 1 → 2.7 tutte chiuse (30 run GA, $3.74 cumulato LLM, cap originale $700 → margine 99%+). Vedi il documento di sintesi consolidato per il dettaglio: + +- [**Stato progetto e roadmap (14 maggio 2026)**](docs/reports/2026-05-14-stato-progetto-e-roadmap.md) — riepilogo di tutte le fasi, decisioni, caveat aperti, roadmap. + +Documenti chiave per fase: - [Decisione strategica](docs/superpowers/specs/2026-05-09-decisione-strategica-design.md) — perché Phase 1 prima, Phase 2 poi, Phase 3 forward-test. -- [Piano implementativo Phase 1](docs/superpowers/plans/2026-05-09-phase1-lean-spike.md) — 38 task TDD-driven. -- [Decision memo gate Phase 1](docs/decisions/2026-05-10-gate-phase1.md) — valutazione formale dei 5 hard gate. -- [Technical report Phase 1](docs/reports/2026-05-10-phase1-technical-report.md) — risultati, ispezione top genomi, threats to validity. +- [Decision memo gate Phase 1](docs/decisions/2026-05-10-gate-phase1.md), [Technical report Phase 1](docs/reports/2026-05-10-phase1-technical-report.md), [Decision memo Phase 1.5 nemotron](docs/decisions/2026-05-11-phase1-5-nemotron-run.md). +- [Piano Phase 2.5 prompt-mutator](docs/superpowers/plans/2026-05-11-mutate-prompt-llm-phase-2-5.md), [Piano feature temporali](docs/superpowers/plans/2026-05-11-temporal-features.md). -Documenti di contesto pre-implementazione: - -- `00_documento_zero.md` — framework concettuale (Renaissance → swarm co-evolutivo LLM). -- `coevolutive_swarm_system.md` — design Filone A (sistema completo, 12-18 mesi). -- `poc_trading_swarm.md` — design Filone B (PoC trading, fonte di Phase 1). +Documenti di contesto pre-implementazione: `00_documento_zero.md` (framework concettuale Renaissance → swarm), `coevolutive_swarm_system.md` (Filone A, sistema completo), `poc_trading_swarm.md` (Filone B, PoC trading). ## Architettura @@ -36,57 +36,73 @@ src/multi_swarm/ ├── config.py Settings Pydantic (.env) ├── data/ │ ├── cerbero_ohlcv.py OHLCV loader via Cerbero MCP + cache parquet -│ └── splits.py Walk-forward expanding splits +│ └── splits.py Walk-forward expanding splits (Phase 2.6) ├── backtest/ │ ├── orders.py Side/Order/Position/Trade │ └── engine.py Event-driven backtest, 1-bar exec delay ├── metrics/ │ ├── basic.py Sharpe, max drawdown, total return -│ └── dsr.py Deflated Sharpe Ratio (Bailey & López 2014) +│ ├── dsr.py Deflated Sharpe Ratio (Bailey & López 2014) +│ └── diversity.py Entropy/diversity metrics popolazione (Phase 2.5) ├── cerbero/ │ ├── client.py HTTP client (bearer + bot-tag + retry tenacity) │ └── tools.py Wrapper tool MCP (sma/rsi/atr/macd/realized_vol/funding) ├── protocol/ -│ ├── grammar.py Vocabolario operatori, indicatori, feature +│ ├── grammar.py Vocabolario operatori, indicatori, feature (incl. hour/dow/is_weekend) │ ├── parser.py json.loads → AST dataclass tipizzato │ ├── validator.py Arity checks, no-nesting indicators, whitelist │ └── compiler.py AST → Callable[[df], Series[Side]] ├── genome/ │ ├── hypothesis.py HypothesisAgentGenome (id deterministico) -│ ├── mutation.py 4 operatori (temp, lookback, features, style) +│ ├── mutation.py 4 operatori scalari (temp, lookback, features, style) +│ ├── mutation_prompt_llm.py 5° operatore: riscrittura system_prompt via LLM tier B │ └── crossover.py Uniform crossover ├── llm/ │ ├── client.py Unified LLMClient via OpenRouter (tier S/A/B/C/D) -│ └── cost_tracker.py Pricing per tier, breakdown +│ └── cost_tracker.py Pricing per tier, breakdown + call_kind tracking ├── agents/ │ ├── hypothesis.py LLM call + JSON extract + retry-with-feedback │ ├── falsification.py Compile → backtest → DSR -│ ├── adversarial.py Red-team heuristics (no_trades/degenerate/over/under) +│ ├── adversarial.py Red-team heuristics (5 check HIGH parametrici via CLI) │ └── market_summary.py Stats di mercato per il prompt ├── ga/ │ ├── selection.py Tournament + elitism -│ ├── fitness.py v1 continua: dsr + tanh(sharpe) × penalty(dd) +│ ├── fitness.py v1 continua + v2 soft-kill + combined IS/OOS opt-in │ ├── loop.py next_generation step │ ├── summary.py median/max/p90/entropy per gen │ └── initial.py Popolazione iniziale (6 cognitive style) ├── persistence/ -│ ├── schema.py SQLite DDL: 6 tabelle + 3 indici +│ ├── schema.py SQLite DDL: 6 tabelle GA + 5 tabelle paper_trading_* │ └── repository.py CRUD per runs/genomes/evals/cost/findings/gen_summary +├── paper_trading/ Phase 3 +│ ├── portfolio.py Multi-asset portfolio con sleeve uguali per asset +│ ├── executor.py PaperExecutor: carica strategia JSON, valuta ultimo bar +│ └── persistence.py PaperRepository (paper_trading_runs/ticks/equity/trades/positions) ├── orchestrator/ -│ └── run.py End-to-end pipeline + persistence +│ └── run.py End-to-end pipeline GA + persistence └── dashboard/ ├── nicegui_app.py NiceGUI dashboard (overview / convergence / genomes) └── data.py Lettura runs.db per le pagine ``` -Stack: Python 3.13, uv, pytest+pytest-mock+responses, openai SDK (verso OpenRouter), requests+tenacity, pandas+numpy+scipy, sqlmodel+sqlite, nicegui+plotly. +Stack: Python 3.13, uv, pytest+pytest-mock+responses, openai SDK (verso OpenRouter), requests+tenacity, pandas+numpy+scipy, sqlmodel+sqlite, nicegui+plotly, yfinance (test cross-asset non-crypto). + +CLI knobs accumulati (Phase 2.5 → 2.7): + +- `--prompt-mutation-weight FLOAT` (peso del 5° operatore, sweet spot 0.20-0.30) +- `--fees-eat-alpha-threshold FLOAT` (default 0.5, suggerito 0.7) +- `--flat-too-long-threshold FLOAT` (default 0.95) +- `--undertrading-threshold INT` (default 20) +- `--fitness-v2` + `--fitness-soft-penalty FLOAT` +- `--fitness-combined-alpha FLOAT` (multi-obiettivo IS/OOS) +- `--min-trades-threshold INT` (filtro OOS in WFA) ## Setup ```bash uv sync cp .env.example .env # compilare CERBERO_*_TOKEN e OPENROUTER_API_KEY -uv run pytest # verifica che tutto installi (141 test attesi) +uv run pytest # ~180 test attesi (unit + integration) ``` ### Variabili .env richieste @@ -102,17 +118,17 @@ CERBERO_BOT_TAG=swarm-poc-phase1 OPENROUTER_API_KEY= OPENROUTER_BASE_URL=https://openrouter.ai/api/v1 -# Modelli per tier (override dei default se serve) -LLM_MODEL_TIER_S=anthropic/claude-opus-4-7 -LLM_MODEL_TIER_A=anthropic/claude-sonnet-4-6 -LLM_MODEL_TIER_B=anthropic/claude-sonnet-4-6 +# Modelli per tier (default Phase 2.5+: qwen-2.5-72b per tier C, vedi .env.example per gli altri) LLM_MODEL_TIER_C=qwen/qwen-2.5-72b-instruct -LLM_MODEL_TIER_D=meta-llama/llama-3.3-70b-instruct + +# Deploy Docker (vedi sezione Deploy) +DOMAIN_NAME=tielogic.xyz +SWARM_DASHBOARD_PORT=8080 ``` ### Cerbero MCP -Phase 1 fetcha OHLCV via Cerbero MCP (sostituisce ccxt). Avviare Cerbero locale prima di un run reale: +Tutti i fetch OHLCV passano da Cerbero MCP (sostituisce ccxt). In sviluppo locale: ```bash cd /home/adriano/Documenti/Git_XYZ/CerberoSuite/Cerbero_mcp @@ -120,30 +136,41 @@ uv sync uv run cerbero-mcp # ascolta su porta da .env (default 9001 se 9000 è occupato) ``` -In alternativa usare il VPS esistente `https://cerbero-mcp.tielogic.xyz` (richiede bearer). +In produzione/integrazione: VPS `https://cerbero-mcp.tielogic.xyz` (richiede bearer) — o internal docker `http://cerbero-mcp:9000` se si gira nella stessa rete Traefik. ## Comandi principali ```bash # Quality gates -uv run pytest # tutti i test (141 PASSED attesi) +uv run pytest # tutti i test uv run pytest tests/unit -v # solo unit -uv run pytest tests/integration -v # solo integration +uv run pytest tests/integration -v # solo integration (richiedono Cerbero + OpenRouter) uv run ruff check src/ tests/ scripts/ uv run mypy src/ scripts/ # Smoke run (MockLLM + OHLCV sintetico, no API calls) uv run python scripts/smoke_run.py -# Run reale Phase 1 (Cerbero + OpenRouter, ~$0.07 per run K=20 10gen) +# Run reale Phase 1/2 (Cerbero + OpenRouter, ~$0.07 per run K=20 10gen) uv run python scripts/run_phase1.py \ - --name phase1-run-XXX \ + --name run-XXX \ --exchange deribit --symbol BTC-PERPETUAL --timeframe 1h \ --start 2024-01-01T00:00:00+00:00 \ --end 2026-01-01T00:00:00+00:00 \ - --population-size 20 --n-generations 10 + --population-size 20 --n-generations 10 \ + --prompt-mutation-weight 0.30 --fitness-v2 -# Dashboard +# Backtest standalone di una strategia JSON su range esteso +uv run python scripts/backtest_strategy.py \ + --strategy strategies/btc_fb63e851.json \ + --start 2018-09-01 --end 2026-01-01 + +# Paper-trading forward-test (Phase 3) +uv run python scripts/run_paper_trading.py \ + --name phase3-papertrade-XXX \ + --initial-capital 1000 --poll-seconds 300 + +# Dashboard NiceGUI locale DB_PATH=./runs.db uv run python -m multi_swarm.dashboard.nicegui_app ``` @@ -155,16 +182,45 @@ NiceGUI dashboard (dark/neon palette) su `http://localhost:8080` (override con e - **GA Convergence** (`/convergence`): fitness median/max/p90 per generazione, entropy con hline a soglia gate (0.5). - **Genomes** (`/genomes`): top-K ordinati per fitness, click su riga per ispezione system_prompt + raw_text JSON strategy. -In produzione gira dentro Docker dietro Traefik su `https://swarm.${DOMAIN_NAME}` — vedi `docker-compose.yml`. +In produzione gira dentro Docker dietro Traefik su `https://swarm.${DOMAIN_NAME}` — vedi sezione Deploy. -## Costi tipici Phase 1 +## Deploy -Tier C (qwen-2.5-72b via OpenRouter): ~$0.40/1M token. Run K=20 × 10gen ≈ $0.07. Phase 1 totale (5 run incluse iterazioni bug-fix): $0.19. +`docker-compose.yml` definisce due servizi che condividono la stessa immagine `multi-swarm:dev`: -Per Phase 2 con tier mix B/C (Sonnet 4.6 = $3/$15 input/output) stima: $3-15 per ablation completa. +- **`multi-swarm-paper`** — runner `scripts/run_paper_trading.py` long-running (`restart: unless-stopped`). +- **`multi-swarm-dashboard`** — NiceGUI esposta via Traefik su `https://swarm.${DOMAIN_NAME}`. + +Entrambi joinano la rete external `traefik` per parlare direttamente con `cerbero-mcp:9000` senza giro pubblico+TLS. Persistenza via bind mount: + +- `./data/`, `./series/` — cache OHLCV (parquet) +- `./state/` — `runs.db` (+ WAL/SHM) +- `./strategies/` — `btc_*.json` / `eth_*.json` (read-only nel container) + +Bring-up: + +```bash +docker compose up -d --build +docker compose logs -f multi-swarm-paper # segui i tick +docker compose ps # stato +``` + +Note operative: + +- Le bind-mount dir devono essere `chown 1000:1000` (uid utente `app` nel container). +- Override del command paper-trading via env (`PAPER_RUN_NAME`, `PAPER_INITIAL_CAPITAL`, `PAPER_POLL_SECONDS`, ecc.) — vedi `.env.example`. +- `SWARM_DASHBOARD_PORT` controlla la porta interna del container (Traefik fa il TLS davanti). + +## Costi + +Costo cumulato LLM progetto a oggi: **≈ $3.74** su 30 run GA (Phase 1 → 2.7). Cap originale Phase 1: $700 → margine residuo abbondante. + +- Tier C (qwen-2.5-72b via OpenRouter): ~$0.40/1M token. +- Run base K=20 × 10gen ≈ $0.07. Con `--prompt-mutation-weight 0.30` overhead mutator 3-9%. +- **Phase 3 paper-trading**: $0 incrementali LLM (strategie fisse), solo costi Cerbero (servizio esistente). ## Sviluppo Conventional commits con prefix `feat:` `fix:` `chore:` `docs:` `refactor:` `test:`. Body italiano. Footer `Co-Authored-By: Claude Opus 4.7 (1M context) ` su ogni commit collaborativo. -Branch attuale: `main`. Nessun feature branch in Phase 1 (single author, lean spike). Phase 2 valuterà feature branch per ablation paralleli. +Branch attuale: `main`. Single-author retail R&D, nessun feature branch attivo. Ablation paralleli si gestiscono via CLI knobs sullo stesso branch.