Compare commits
34 Commits
v0.1.0-pre-split
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 23b7273e71 | |||
| 9c871d1d86 | |||
| 8b767da5e7 | |||
| 1c0058ec3b | |||
| 220e510d5e | |||
| 9742df3a1f | |||
| 21b5cf1eae | |||
| a29748e3d8 | |||
| fa11cca2bc | |||
| 6526c6e6e3 | |||
| ccf9f7a33c | |||
| 19a3592a20 | |||
| 5202eb517b | |||
| 898b24b6a3 | |||
| b6f48e46fc | |||
| 0fd31d52ec | |||
| a43157cd44 | |||
| 436613bfde | |||
| f55e4f00c5 | |||
| 96e08ff78f | |||
| 9c3b5ad586 | |||
| f875df31b4 | |||
| 720b2d58d7 | |||
| 96bbd716ec | |||
| 30add35906 | |||
| 8caa526727 | |||
| 289df4b81f | |||
| 2b5da4d1fc | |||
| 37bf64012b | |||
| b02be64831 | |||
| 08f1585ab2 | |||
| cd4c3131d9 | |||
| b6539802e0 | |||
| 7d766173a4 |
+12
-2
@@ -21,13 +21,23 @@ LLM_MODEL_TIER_D=openai/gpt-oss-20b
|
|||||||
RUN_NAME=phase1-spike-001
|
RUN_NAME=phase1-spike-001
|
||||||
DATA_DIR=./data
|
DATA_DIR=./data
|
||||||
SERIES_DIR=./series
|
SERIES_DIR=./series
|
||||||
DB_PATH=./runs.db
|
|
||||||
|
# Database paths (split per dominio):
|
||||||
|
# - GA_DB_PATH: tabelle GA universali (runs, generations, genomes, evaluations)
|
||||||
|
# - STRATEGY_CRYPTO_DB_PATH: tabelle paper_trading_* per la strategia crypto
|
||||||
|
GA_DB_PATH=./state/runs.db
|
||||||
|
STRATEGY_CRYPTO_DB_PATH=./state/strategy_crypto.db
|
||||||
|
|
||||||
# Docker / Traefik (usati SOLO da docker-compose.yml)
|
# Docker / Traefik (usati SOLO da docker-compose.yml)
|
||||||
# Dominio base: traefik espone la dashboard su swarm.${DOMAIN_NAME}
|
# Dominio base: traefik espone le dashboard su swarm.${DOMAIN_NAME}/...
|
||||||
DOMAIN_NAME=tielogic.xyz
|
DOMAIN_NAME=tielogic.xyz
|
||||||
# Porta interna della NiceGUI dashboard (Traefik fa il TLS davanti)
|
# Porta interna della NiceGUI dashboard (Traefik fa il TLS davanti)
|
||||||
SWARM_DASHBOARD_PORT=8080
|
SWARM_DASHBOARD_PORT=8080
|
||||||
|
# Subpath URL del dashboard NiceGUI — ora PER-SERVIZIO nel docker-compose.yml:
|
||||||
|
# strategy-crypto-gui -> DASHBOARD_ROOT_PATH=/strategy_crypto_gui
|
||||||
|
# multi-swarm-core-gui -> DASHBOARD_ROOT_PATH=/multi_swarm_core_gui
|
||||||
|
# In sviluppo locale lascia vuoto (nessun subpath).
|
||||||
|
DASHBOARD_ROOT_PATH=
|
||||||
|
|
||||||
# Paper-trading runner — override del command nel compose (opzionali)
|
# Paper-trading runner — override del command nel compose (opzionali)
|
||||||
PAPER_RUN_NAME=phase3-papertrade-prod
|
PAPER_RUN_NAME=phase3-papertrade-prod
|
||||||
|
|||||||
@@ -24,6 +24,10 @@ venv/
|
|||||||
*.key
|
*.key
|
||||||
|
|
||||||
# Project artefacts (non versionati: troppo grandi o rigenerabili)
|
# Project artefacts (non versionati: troppo grandi o rigenerabili)
|
||||||
|
state/*.db
|
||||||
|
state/*.db-journal
|
||||||
|
state/*.db-wal
|
||||||
|
state/*.db-shm
|
||||||
runs.db
|
runs.db
|
||||||
runs.db-journal
|
runs.db-journal
|
||||||
runs.db-wal
|
runs.db-wal
|
||||||
@@ -36,6 +40,9 @@ checkpoints/
|
|||||||
logs/
|
logs/
|
||||||
*.log
|
*.log
|
||||||
|
|
||||||
|
# OMC state (auto-orchestration)
|
||||||
|
.omc/
|
||||||
|
|
||||||
# Build / dist
|
# Build / dist
|
||||||
build/
|
build/
|
||||||
dist/
|
dist/
|
||||||
|
|||||||
+18
-12
@@ -1,13 +1,15 @@
|
|||||||
# syntax=docker/dockerfile:1.7
|
# syntax=docker/dockerfile:1.7
|
||||||
#
|
#
|
||||||
# Multi-Swarm Coevolutive — immagine unica usata da due servizi:
|
# Multi-Swarm Coevolutive — immagine unica usata da due servizi del compose:
|
||||||
# * paper-trading runner (scripts/run_paper_trading.py)
|
# * paper-trading runner (scripts/run_paper_trading.py)
|
||||||
# * Streamlit dashboard (src/multi_swarm/dashboard/streamlit_app.py)
|
# * NiceGUI dashboard (strategy_crypto.frontend.nicegui_app)
|
||||||
#
|
#
|
||||||
# Builder stage: risolve uv.lock con `uv sync --frozen --no-dev` e produce
|
# uv workspace: pyproject root coordina due member packages
|
||||||
# un venv in /app/.venv. Runtime stage: copia solo /app + scripts/ e gira
|
# (multi-swarm-core + strategy-crypto). Il `uv sync --frozen` installa
|
||||||
# come utente non-root. data/, series/, strategies/, state/ sono bind
|
# entrambi come editable nella venv del builder.
|
||||||
# mount dal compose, quindi non finiscono nell'immagine.
|
# Runtime stage: copia solo /app + scripts/ e gira come utente non-root.
|
||||||
|
# data/, series/, state/ sono bind mount dal compose; strategies/ è
|
||||||
|
# bind-mounted dal path src/strategy_crypto/strategy_crypto/strategies.
|
||||||
|
|
||||||
FROM python:3.13-slim AS builder
|
FROM python:3.13-slim AS builder
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
@@ -21,7 +23,7 @@ RUN uv sync --frozen --no-dev
|
|||||||
|
|
||||||
|
|
||||||
FROM python:3.13-slim AS runtime
|
FROM python:3.13-slim AS runtime
|
||||||
LABEL org.opencontainers.image.title="multi-swarm" \
|
LABEL org.opencontainers.image.title="multi-swarm-coevolutive" \
|
||||||
org.opencontainers.image.version="0.1.0" \
|
org.opencontainers.image.version="0.1.0" \
|
||||||
org.opencontainers.image.source="https://git.tielogic.xyz/Adriano/Multi_Swarm_Coevolutive"
|
org.opencontainers.image.source="https://git.tielogic.xyz/Adriano/Multi_Swarm_Coevolutive"
|
||||||
|
|
||||||
@@ -35,18 +37,22 @@ COPY scripts ./scripts
|
|||||||
|
|
||||||
ENV PATH="/app/.venv/bin:$PATH" \
|
ENV PATH="/app/.venv/bin:$PATH" \
|
||||||
PYTHONUNBUFFERED=1 \
|
PYTHONUNBUFFERED=1 \
|
||||||
PYTHONDONTWRITEBYTECODE=1 \
|
PYTHONDONTWRITEBYTECODE=1
|
||||||
PYTHONPATH=/app/src
|
# NO PYTHONPATH: con uv workspace + layout doppio-nest, PYTHONPATH=/app/src
|
||||||
|
# farebbe ombra alla venv risolvendo le member-dir (multi_swarm_core/,
|
||||||
|
# strategy_crypto/) come namespace packages senza i sub-package del codice.
|
||||||
|
# I pacchetti sono installati come editable dal `uv sync --frozen` del builder
|
||||||
|
# e risolvibili direttamente via /app/.venv/.
|
||||||
|
|
||||||
RUN useradd -m -u 1000 app \
|
RUN useradd -m -u 1000 app \
|
||||||
&& mkdir -p /app/data /app/series /app/state /app/strategies \
|
&& mkdir -p /app/data /app/series /app/state /app/strategies \
|
||||||
&& chown -R app:app /app
|
&& chown -R app:app /app
|
||||||
USER app
|
USER app
|
||||||
|
|
||||||
# Healthcheck di default: import del package — i servizi reali lo
|
# Healthcheck di default: import dei due package del workspace.
|
||||||
# sovrascrivono nel compose (streamlit /_stcore/health).
|
# I servizi reali lo sovrascrivono nel compose (es. NiceGUI HTTP).
|
||||||
HEALTHCHECK --interval=60s --timeout=5s --retries=3 --start-period=10s \
|
HEALTHCHECK --interval=60s --timeout=5s --retries=3 --start-period=10s \
|
||||||
CMD python -c "import multi_swarm" || exit 1
|
CMD python -c "import multi_swarm_core, strategy_crypto" || exit 1
|
||||||
|
|
||||||
# Nessun CMD di default: il compose specifica entrypoint/command
|
# Nessun CMD di default: il compose specifica entrypoint/command
|
||||||
# per ognuno dei due servizi.
|
# per ognuno dei due servizi.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Multi_Swarm_Coevolutive
|
# 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 (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.
|
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.
|
||||||
|
|
||||||
## Repository
|
## Repository
|
||||||
|
|
||||||
@@ -10,99 +10,108 @@ Gitea Tielogic (privato, accesso SSH):
|
|||||||
git clone ssh://git@git.tielogic.xyz:222/Adriano/Multi_Swarm_Coevolutive.git
|
git clone ssh://git@git.tielogic.xyz:222/Adriano/Multi_Swarm_Coevolutive.git
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Layout monorepo (uv workspace)
|
||||||
|
|
||||||
|
Il repo è un **workspace uv** con due member packages indipendenti, principio "**core = framework, strategy = contenuto**":
|
||||||
|
|
||||||
|
```
|
||||||
|
multi_swarm_coevolutive/ repo root (workspace coordinator)
|
||||||
|
├── pyproject.toml workspace + dev deps + ruff/mypy/pytest
|
||||||
|
├── docker-compose.yml 3 servizi su immagine condivisa
|
||||||
|
├── Dockerfile immagine multi-swarm-coevolutive:dev
|
||||||
|
├── uv.lock lock unico del workspace
|
||||||
|
├── data/, series/, state/ cache OHLCV + DB (runtime, gitignored)
|
||||||
|
├── scripts/ CLI entrypoints (run_phase1, run_paper_trading, ...)
|
||||||
|
└── src/
|
||||||
|
├── multi_swarm_core/ WORKSPACE MEMBER (wheel: multi-swarm-core)
|
||||||
|
│ ├── pyproject.toml core deps (pandas, numpy, openai, pydantic, nicegui, ...)
|
||||||
|
│ ├── multi_swarm_core/ GA + genome + protocol + backtest + cerbero +
|
||||||
|
│ │ data + llm + agents + ga + orchestrator +
|
||||||
|
│ │ metrics + persistence + config + dashboard (GA-only)
|
||||||
|
│ ├── tests/ unit + integration
|
||||||
|
│ └── docs/ design/ + decisions/ + reports/
|
||||||
|
│
|
||||||
|
└── strategy_crypto/ WORKSPACE MEMBER (wheel: strategy-crypto)
|
||||||
|
├── pyproject.toml deps: multi-swarm-core (workspace) + nicegui + plotly
|
||||||
|
├── README.md overview strategia + pattern per nuove strategie
|
||||||
|
├── strategy_crypto/
|
||||||
|
│ ├── backend/ paper-trading (executor, portfolio, persistence, schema)
|
||||||
|
│ ├── frontend/ NiceGUI paper-only dashboard
|
||||||
|
│ ├── strategies/ JSON freezate (btc_*.json, eth_*.json)
|
||||||
|
│ └── prompts.json v3.2: agent_role/pattern_guidance/instruction/
|
||||||
|
│ domain_warnings/anti_patterns/output_priorities +
|
||||||
|
│ 7 stili cognitive (directive + focus_metrics)
|
||||||
|
└── tests/ smoke regression
|
||||||
|
```
|
||||||
|
|
||||||
|
**DB separati per dominio:** `state/runs.db` (GA core universale) + `state/strategy_crypto.db` (paper della strategia crypto). Pattern scala a N strategie senza naming collision.
|
||||||
|
|
||||||
|
**Pattern N strategie future:** aggiungere `src/strategy_<asset>/` con stesso scheletro (`backend/`, `frontend/`, `strategies/`, `tests/`, `prompts.json`), DB dedicato `state/strategy_<asset>.db`, servizi Docker `strategy-<asset>-paper` + `strategy-<asset>-gui`, GUI su `/strategy_<asset>_gui`. **Zero modifiche al core** richieste.
|
||||||
|
|
||||||
|
## Architettura prompt (v3.2)
|
||||||
|
|
||||||
|
**Compositor**: il SYSTEM prompt al LLM viene COMPOSTO at-runtime da scaffold core + contenuto strategy:
|
||||||
|
|
||||||
|
```
|
||||||
|
[1] agent_role ← strategy (prompts.json — chi è l'agente)
|
||||||
|
[2] cognitive_style + directive ← genome (evoluti dal GA)
|
||||||
|
[3] GRAMMAR_SPEC ← core scaffold (operatori, indicatori, units rules)
|
||||||
|
[4] pattern_guidance ← strategy (forme di curva astratte, no indicatori prescritti)
|
||||||
|
[5] domain_warnings ← strategy (es. "crypto trada 24/7, NON inferire funding rate")
|
||||||
|
[6] CONSTRAINTS ← core scaffold (validator semantics)
|
||||||
|
[7] anti_patterns ← strategy (7 voci: no >4 AND, no chattering, isteresi, ecc.)
|
||||||
|
[8] output_priorities ← strategy (5 voci, #1 coerenza con lente cognitiva)
|
||||||
|
[9] EXAMPLE ← core scaffold
|
||||||
|
```
|
||||||
|
|
||||||
|
**Input USER (calcolato da `build_market_summary`):**
|
||||||
|
- Base (5): mean, std, skew, kurt, vol_regime
|
||||||
|
- Regime recente rolling 500 (6): autocorr_lag1 (recent + baseline), hurst, vol_percentile, seasonality (hour + dow)
|
||||||
|
- Geometria & frattali (7): efficiency_ratio (Kaufman), tail_index (left + right Hill), structural_uptrend (HH/HL), compression, spectral_entropy, dominant_cycle (gated)
|
||||||
|
- Feature accessibili dal genome + lookback_window
|
||||||
|
- **Focus per la tua lente**: blocco style-aware (4 metriche prioritarie da `focus_metrics` di prompts.json)
|
||||||
|
- Instruction finale (da strategy)
|
||||||
|
|
||||||
|
**Grammar protocol JSON (8 indicatori):**
|
||||||
|
| Indicatore | Output | Range |
|
||||||
|
|------------|--------|-------|
|
||||||
|
| `sma(length)` | media mobile | unità prezzo |
|
||||||
|
| `sma_pct(length)` | (close-sma)/sma | ±0.1 frazione |
|
||||||
|
| `rsi(length)` | oscillator | 0-100 |
|
||||||
|
| `atr(length)` | true range | unità prezzo |
|
||||||
|
| `atr_pct(length)` | atr/close | 0-0.1 frazione |
|
||||||
|
| `realized_vol(window)` | std returns | 0-0.1 frazione |
|
||||||
|
| `macd(fast,slow,signal)` | momentum | unità prezzo |
|
||||||
|
| `macd_pct(...)` | macd/close | ±0.02 frazione |
|
||||||
|
|
||||||
|
**7 stili cognitive** (in `prompts.json`, editable): physicist, biologist, historian, meteorologist, engineer, military_strategist, psychologist. Ognuno con directive 800-950 char, ASCII-strict, archetipo dominante + lookback consigliato + 4 focus_metrics.
|
||||||
|
|
||||||
## Stato del progetto
|
## Stato del progetto
|
||||||
|
|
||||||
**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 3 (paper-trading forward-test) in corso** dal 13 maggio 2026 su VPS. Runner `scripts/run_paper_trading.py` long-running in Docker, dashboard NiceGUI su `https://swarm.tielogic.xyz/strategy_crypto_gui/`. Due strategie freezate in `src/strategy_crypto/strategy_crypto/strategies/`:
|
||||||
|
|
||||||
- `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.
|
- `btc_fb63e851.json` — BTC-PERPETUAL, RSI estremi + ATR vs SMA + filtro orario 9-17 (Sharpe OOS +0,26 su 7,33 anni).
|
||||||
- `strategies/eth_facd6af85d5d.json` — ETH-PERPETUAL, trend-following long-bias + vol regime, Sharpe OOS +0,19 su 6,75 anni.
|
- `eth_facd6af85d5d.json` — ETH-PERPETUAL, regime-based (con `atr_pct` post-fix bug unità).
|
||||||
|
|
||||||
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:
|
Phase 1 → 2.7 chiuse (30 run GA, $3.74 cumulato LLM). Sessione refactor 15 maggio 2026:
|
||||||
|
- Split repo invertito, monorepo unificato come uv workspace
|
||||||
|
- Family `*_pct` completa (atr_pct, sma_pct, macd_pct) per fix bug unità
|
||||||
|
- Dashboard split: core (GA) vs strategy (paper)
|
||||||
|
- Prompt architecture compositor + prompts.json v3.2 (vedi decision log)
|
||||||
|
|
||||||
- [**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:
|
||||||
|
- [**Stato progetto e roadmap (14 maggio 2026)**](src/multi_swarm_core/docs/reports/2026-05-14-stato-progetto-e-roadmap.md)
|
||||||
|
- Decision log: [`src/multi_swarm_core/docs/decisions/`](src/multi_swarm_core/docs/decisions/) (gate Phase 1, nemotron, atr_pct fix)
|
||||||
|
- Design docs concettuali: [`src/multi_swarm_core/docs/design/`](src/multi_swarm_core/docs/design/)
|
||||||
|
|
||||||
Documenti chiave per fase:
|
Stack: Python 3.13, uv workspace, hatchling, pytest+pytest-mock+responses, openai SDK (verso OpenRouter), requests+tenacity, pandas+numpy+scipy, sqlmodel+sqlite, nicegui+plotly, yfinance.
|
||||||
|
|
||||||
- [Decisione strategica](docs/superpowers/specs/2026-05-09-decisione-strategica-design.md) — perché Phase 1 prima, Phase 2 poi, Phase 3 forward-test.
|
|
||||||
- [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), `coevolutive_swarm_system.md` (Filone A, sistema completo), `poc_trading_swarm.md` (Filone B, PoC trading).
|
|
||||||
|
|
||||||
## Architettura
|
|
||||||
|
|
||||||
```
|
|
||||||
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 (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)
|
|
||||||
│ └── 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 (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 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 + call_kind tracking
|
|
||||||
├── agents/
|
|
||||||
│ ├── hypothesis.py LLM call + JSON extract + retry-with-feedback
|
|
||||||
│ ├── falsification.py Compile → backtest → DSR
|
|
||||||
│ ├── 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 + 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 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 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, 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
|
## Setup
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
uv sync
|
uv sync # installa entrambi i workspace member come editable
|
||||||
cp .env.example .env # compilare CERBERO_*_TOKEN e OPENROUTER_API_KEY
|
cp .env.example .env # compila CERBERO_*_TOKEN e OPENROUTER_API_KEY
|
||||||
uv run pytest # ~180 test attesi (unit + integration)
|
uv run pytest # 252 test attesi (248 core + 4 smoke strategy_crypto)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Variabili .env richieste
|
### Variabili .env richieste
|
||||||
@@ -116,53 +125,56 @@ CERBERO_BOT_TAG=swarm-poc-phase1
|
|||||||
|
|
||||||
# LLM provider (unico endpoint via OpenRouter)
|
# LLM provider (unico endpoint via OpenRouter)
|
||||||
OPENROUTER_API_KEY=<sk-or-v1-...>
|
OPENROUTER_API_KEY=<sk-or-v1-...>
|
||||||
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
|
|
||||||
|
|
||||||
# Modelli per tier (default Phase 2.5+: qwen-2.5-72b per tier C, vedi .env.example per gli altri)
|
# DB paths (split per dominio: core GA vs paper della strategia)
|
||||||
LLM_MODEL_TIER_C=qwen/qwen-2.5-72b-instruct
|
GA_DB_PATH=./state/runs.db
|
||||||
|
STRATEGY_CRYPTO_DB_PATH=./state/strategy_crypto.db
|
||||||
|
|
||||||
# Deploy Docker (vedi sezione Deploy)
|
# Deploy Docker — DASHBOARD_ROOT_PATH ora per-servizio (vedi docker-compose.yml)
|
||||||
DOMAIN_NAME=tielogic.xyz
|
DOMAIN_NAME=tielogic.xyz
|
||||||
SWARM_DASHBOARD_PORT=8080
|
SWARM_DASHBOARD_PORT=8080
|
||||||
```
|
```
|
||||||
|
|
||||||
### Cerbero MCP
|
Backcompat: `DB_PATH` legacy continua a funzionare come alias di `GA_DB_PATH`.
|
||||||
|
|
||||||
Tutti i fetch OHLCV passano da Cerbero MCP (sostituisce ccxt). In sviluppo locale:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd /home/adriano/Documenti/Git_XYZ/CerberoSuite/Cerbero_mcp
|
|
||||||
uv sync
|
|
||||||
uv run cerbero-mcp # ascolta su porta da .env (default 9001 se 9000 è occupato)
|
|
||||||
```
|
|
||||||
|
|
||||||
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
|
## Comandi principali
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Quality gates
|
# Quality gates
|
||||||
uv run pytest # tutti i test
|
uv run pytest # tutti i test
|
||||||
uv run pytest tests/unit -v # solo unit
|
uv run pytest src/multi_swarm_core/tests/unit -v # solo unit core
|
||||||
uv run pytest tests/integration -v # solo integration (richiedono Cerbero + OpenRouter)
|
uv run pytest src/strategy_crypto/tests/ -v # smoke strategy_crypto
|
||||||
uv run ruff check src/ tests/ scripts/
|
uv run ruff check src/ scripts/
|
||||||
uv run mypy src/ scripts/
|
uv run mypy src/ scripts/
|
||||||
|
|
||||||
# Smoke run (MockLLM + OHLCV sintetico, no API calls)
|
# Smoke run (MockLLM + OHLCV sintetico, no API calls)
|
||||||
uv run python scripts/smoke_run.py
|
uv run python scripts/smoke_run.py
|
||||||
|
|
||||||
# Run reale Phase 1/2 (Cerbero + OpenRouter, ~$0.07 per run K=20 10gen)
|
# Run reale Phase 1/2 (Cerbero + OpenRouter, ~$0.15-0.25 per run K=20 10gen,
|
||||||
|
# ~$0.40-0.55 per run esteso K=40 20gen con WFA OOS).
|
||||||
|
# Default --start ora 2018-09-01 (7.3y, copre bear+halving+covid+ATH+winter+ETF).
|
||||||
uv run python scripts/run_phase1.py \
|
uv run python scripts/run_phase1.py \
|
||||||
--name run-XXX \
|
--name run-XXX \
|
||||||
--exchange deribit --symbol BTC-PERPETUAL --timeframe 1h \
|
--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
|
--prompt-mutation-weight 0.30 --fitness-v2 \
|
||||||
|
--llm-concurrency 8 # 5-8x speedup wall time (default 1)
|
||||||
|
# fitness-v2 hardened: hard-kill su {no_trades, degenerate, undertrading,
|
||||||
|
# fees_eat_alpha, negative_net_pnl}. Override via --fitness-hard-kill CSV.
|
||||||
|
# Default --prompt-library: importlib.resources del package strategy_crypto/prompts.json
|
||||||
|
|
||||||
# Backtest standalone di una strategia JSON su range esteso
|
# Multi-fold validation di un run esistente (anti-overfit, 7y expanding-window)
|
||||||
|
uv run python scripts/validate_run.py \
|
||||||
|
--run-id <run_id> \
|
||||||
|
--top-k 10 --n-folds 4 --train-ratio 0.5 \
|
||||||
|
--start 2018-09-01T00:00:00+00:00 --end 2026-01-01T00:00:00+00:00 \
|
||||||
|
--fitness-v2 \
|
||||||
|
--output-json state/validation-XXX.json
|
||||||
|
# Ranking per "robust_score" = min(fitness_oos) su tutti i fold.
|
||||||
|
|
||||||
|
# Backtest standalone di una strategia JSON
|
||||||
uv run python scripts/backtest_strategy.py \
|
uv run python scripts/backtest_strategy.py \
|
||||||
--strategy strategies/btc_fb63e851.json \
|
--strategy src/strategy_crypto/strategy_crypto/strategies/btc_fb63e851.json \
|
||||||
--start 2018-09-01 --end 2026-01-01
|
--start 2018-09-01 --end 2026-01-01
|
||||||
|
|
||||||
# Paper-trading forward-test (Phase 3)
|
# Paper-trading forward-test (Phase 3)
|
||||||
@@ -170,57 +182,68 @@ uv run python scripts/run_paper_trading.py \
|
|||||||
--name phase3-papertrade-XXX \
|
--name phase3-papertrade-XXX \
|
||||||
--initial-capital 1000 --poll-seconds 300
|
--initial-capital 1000 --poll-seconds 300
|
||||||
|
|
||||||
# Dashboard NiceGUI locale
|
# Dashboard NiceGUI locale (2 distinte)
|
||||||
DB_PATH=./runs.db uv run python -m multi_swarm.dashboard.nicegui_app
|
uv run python -m multi_swarm_core.dashboard.nicegui_app # GA core (/, /convergence, /genomes)
|
||||||
|
uv run python -m strategy_crypto.frontend.nicegui_app # Strategy crypto (/ paper)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Dashboard
|
## Performance & Validation
|
||||||
|
|
||||||
NiceGUI dashboard (dark/neon palette) su `http://localhost:8080` (override con env `SWARM_DASHBOARD_PORT`):
|
**Backtest engine vettorializzato** (`backtest/engine.py`): rimosso il loop `pd.iterrows()` a favore di state machine numpy. Speedup misurati:
|
||||||
|
|
||||||
- **Overview** (`/`): lista runs, status, costo, metriche aggregate evaluations (parse success %, top fitness, median).
|
| Dataset | Before (iterrows) | After (vectorized) | Speedup |
|
||||||
- **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.
|
| 2 anni (17545 bar) | 470 ms | **28 ms** | **16.8×** |
|
||||||
|
| 7 anni (64297 bar) | 1744 ms | **154 ms** | **11.3×** |
|
||||||
|
|
||||||
In produzione gira dentro Docker dietro Traefik su `https://swarm.${DOMAIN_NAME}` — vedi sezione Deploy.
|
Equivalenza numerica garantita: 5 parity test parametrici vs. reference implementation legacy (`test_backtest_engine_vectorized.py`).
|
||||||
|
|
||||||
|
**Parallel propose LLM** (`orchestrator/run.py`): `--llm-concurrency N` lancia N chiamate `hypothesis_agent.propose()` concorrenti per generazione tramite `ThreadPoolExecutor`. OpenRouter qwen-2.5 regge 6-10 concorrenti senza rate-limit. Default 1 = backward-compat.
|
||||||
|
|
||||||
|
**Multi-fold validation tool** (`scripts/validate_run.py`): qualunque run completato puo' essere rivalutato post-hoc su N fold expanding-window di un dataset esteso (tipicamente 7 anni). Vital per evitare il single-hold-out overfit: il GA puo' selezionare un genome con `fitness_is` alta che collassa OOS (osservato su `phase1-extended-001`: elite IS Sharpe 1.93, OOS Sharpe -1.00). Ranking finale per `robust_score = min(fitness_oos)`. Output JSON con per-fold breakdown + aggregati mean/min/std.
|
||||||
|
|
||||||
|
## Dashboard (split core + strategy)
|
||||||
|
|
||||||
|
Due NiceGUI dashboard distinte (dark palette, palette neon):
|
||||||
|
|
||||||
|
**Core GA** — `multi_swarm_core.dashboard.nicegui_app` → `https://swarm.tielogic.xyz/multi_swarm_core_gui/`:
|
||||||
|
- **Overview** (`/`): lista runs GA, costo cumulato, metriche aggregate evaluations.
|
||||||
|
- **GA Convergence** (`/convergence`): fitness median/max/p90 per generazione + entropy.
|
||||||
|
- **Genomes** (`/genomes`): top-K ordinati per fitness, ispezione system_prompt + JSON strategy.
|
||||||
|
|
||||||
|
**Strategy crypto** — `strategy_crypto.frontend.nicegui_app` → `https://swarm.tielogic.xyz/strategy_crypto_gui/`:
|
||||||
|
- **Paper** (`/`): forward-test live con equity curve, posizioni aperte, trade list, tick log.
|
||||||
|
|
||||||
|
In produzione subpath gestiti via `DASHBOARD_ROOT_PATH` (per-servizio) + Traefik `replacepathregex` (NB: NON `stripprefix`, vedi sezione Deploy). La root del dominio resta libera per future GUI di altre strategie.
|
||||||
|
|
||||||
## Deploy
|
## Deploy
|
||||||
|
|
||||||
`docker-compose.yml` definisce due servizi che condividono la stessa immagine `multi-swarm:dev`:
|
`docker-compose.yml` definisce 3 servizi su immagine condivisa `multi-swarm-coevolutive:dev`:
|
||||||
|
|
||||||
- **`multi-swarm-paper`** — runner `scripts/run_paper_trading.py` long-running (`restart: unless-stopped`).
|
- **`strategy-crypto-paper`** — runner `scripts/run_paper_trading.py` long-running.
|
||||||
- **`multi-swarm-dashboard`** — NiceGUI esposta via Traefik su `https://swarm.${DOMAIN_NAME}`.
|
- **`strategy-crypto-gui`** — NiceGUI paper dashboard su `https://swarm.${DOMAIN_NAME}/strategy_crypto_gui/`.
|
||||||
|
- **`multi-swarm-core-gui`** — NiceGUI GA dashboard su `https://swarm.${DOMAIN_NAME}/multi_swarm_core_gui/`.
|
||||||
|
|
||||||
Entrambi joinano la rete external `traefik` per parlare direttamente con `cerbero-mcp:9000` senza giro pubblico+TLS. Persistenza via bind mount:
|
Persistenza via bind mount: `./data/`, `./series/`, `./state/`. Strategie JSON bind-mounted in read-only dal package: `./src/strategy_crypto/strategy_crypto/strategies/`.
|
||||||
|
|
||||||
- `./data/`, `./series/` — cache OHLCV (parquet)
|
|
||||||
- `./state/` — `runs.db` (+ WAL/SHM)
|
|
||||||
- `./strategies/` — `btc_*.json` / `eth_*.json` (read-only nel container)
|
|
||||||
|
|
||||||
Bring-up:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose up -d --build
|
docker compose up -d --build
|
||||||
docker compose logs -f multi-swarm-paper # segui i tick
|
docker compose logs -f strategy-crypto-paper
|
||||||
docker compose ps # stato
|
docker compose ps
|
||||||
```
|
```
|
||||||
|
|
||||||
Note operative:
|
Note operative:
|
||||||
|
|
||||||
- Le bind-mount dir devono essere `chown 1000:1000` (uid utente `app` nel container).
|
- Bind-mount dir devono essere `chown 1000:1000` (uid utente `app` nel container). **Anche `src/strategy_crypto/strategy_crypto/strategies/`** (creata da `git mv`, default `root:root`).
|
||||||
- Override del command paper-trading via env (`PAPER_RUN_NAME`, `PAPER_INITIAL_CAPITAL`, `PAPER_POLL_SECONDS`, ecc.) — vedi `.env.example`.
|
- Override del command paper via env (`PAPER_RUN_NAME`, `PAPER_INITIAL_CAPITAL`, ecc.).
|
||||||
- `SWARM_DASHBOARD_PORT` controlla la porta interna del container (Traefik fa il TLS davanti).
|
- `SWARM_DASHBOARD_PORT` controlla la porta interna del container (Traefik fa il TLS).
|
||||||
|
- **Traefik subpath**: usa `replacepathregex` middleware (NON `stripprefix`) per evitare doppio root_path (uvicorn legge `X-Forwarded-Prefix` da stripprefix + applica `root_path` di NiceGUI = doppio prefix). Vedi commit `436613b`.
|
||||||
## Costi
|
- Dopo cambio label Traefik: `docker restart traefik-traefik-1` per forzare refresh discovery.
|
||||||
|
|
||||||
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
|
## Sviluppo
|
||||||
|
|
||||||
Conventional commits con prefix `feat:` `fix:` `chore:` `docs:` `refactor:` `test:`. Body italiano. Footer `Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>` su ogni commit collaborativo.
|
Conventional commits con prefix `feat:` `fix:` `chore:` `docs:` `refactor:` `test:`. Body italiano. Footer `Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>` su ogni commit collaborativo.
|
||||||
|
|
||||||
Branch attuale: `main`. Single-author retail R&D, nessun feature branch attivo. Ablation paralleli si gestiscono via CLI knobs sullo stesso branch.
|
Branch attuale: `main`. Workspace single-repo, monorepo unificato dal 15 maggio 2026 (split temporaneo monorepo→figlio invertito, vedi tag `v0.1.0-pre-split` come bookmark).
|
||||||
|
|
||||||
|
**Modificare il prompt LLM** senza toccare codice: edita `src/strategy_crypto/strategy_crypto/prompts.json`. Schema documentato in `_design_invariants` del JSON stesso. I 3 regression guard test (`test_strategy_crypto_directives_ascii_safe`, `..._have_archetype_marker`, `..._have_lookback_hint`) bloccano regressioni accidentali sulle invarianti di design.
|
||||||
|
|||||||
+77
-25
@@ -1,25 +1,29 @@
|
|||||||
# docker-compose.yml — Multi-Swarm Coevolutive
|
# docker-compose.yml — Multi-Swarm Coevolutive
|
||||||
#
|
#
|
||||||
# Due servizi che condividono la stessa immagine `multi-swarm:dev`:
|
# Tre servizi della strategia crypto, condividono la stessa immagine
|
||||||
|
# `multi-swarm-coevolutive:dev` buildata dal Dockerfile root (uv workspace):
|
||||||
#
|
#
|
||||||
# * multi-swarm-paper — paper-trading runner long-running
|
# * strategy-crypto-paper — paper-trading runner long-running
|
||||||
# (scripts/run_paper_trading.py)
|
# (scripts/run_paper_trading.py)
|
||||||
# * multi-swarm-dashboard — Streamlit dashboard esposta da Traefik
|
# * strategy-crypto-gui — NiceGUI dashboard esposta da Traefik su
|
||||||
# su https://swarm.${DOMAIN_NAME:-tielogic.xyz}
|
# https://swarm.${DOMAIN_NAME:-tielogic.xyz}/strategy_crypto_gui
|
||||||
|
# * multi-swarm-core-gui — NiceGUI dashboard GA esposta su
|
||||||
|
# https://swarm.${DOMAIN_NAME:-tielogic.xyz}/multi_swarm_core_gui
|
||||||
#
|
#
|
||||||
# Entrambi joinano la rete external `traefik` cosi' il client Cerbero
|
# Entrambi joinano la rete external `traefik` cosi' il client Cerbero
|
||||||
# risolve direttamente l'host `cerbero-mcp` (porta 9000) senza passare
|
# risolve direttamente l'host `cerbero-mcp` (porta 9000) senza passare
|
||||||
# dal gateway pubblico ne' dal TLS.
|
# dal gateway pubblico ne' dal TLS.
|
||||||
#
|
#
|
||||||
|
# Pattern N strategie future: aggiungere strategy-<asset>-paper + strategy-<asset>-gui
|
||||||
|
# con PathPrefix(/strategy_<asset>_gui) e DASHBOARD_ROOT_PATH dedicato.
|
||||||
|
#
|
||||||
# Dati persistenti via bind mount dalla cartella del repo:
|
# Dati persistenti via bind mount dalla cartella del repo:
|
||||||
# ./data cache OHLCV intermedia
|
# ./data cache OHLCV intermedia
|
||||||
# ./series cache parquet per timeframe/symbol
|
# ./series cache parquet per timeframe/symbol
|
||||||
# ./state contiene runs.db (+ WAL/SHM)
|
# ./state contiene runs.db (GA) + strategy_crypto.db (paper) + WAL/SHM
|
||||||
# ./strategies btc_*.json / eth_*.json letti dal paper runner
|
# ./src/strategy_crypto/strategy_crypto/strategies JSON freezate (ro)
|
||||||
#
|
#
|
||||||
# Secrets (token Cerbero + OpenRouter): caricati da .env via env_file.
|
# Secrets (token Cerbero + OpenRouter): caricati da .env via env_file.
|
||||||
# Le variabili sotto `environment:` sovrascrivono solo i valori che
|
|
||||||
# devono cambiare dentro il container (URL interno, path container).
|
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
traefik:
|
traefik:
|
||||||
@@ -31,15 +35,22 @@ x-swarm-env: &swarm-env
|
|||||||
# Override: path container per persistenza
|
# Override: path container per persistenza
|
||||||
DATA_DIR: /app/data
|
DATA_DIR: /app/data
|
||||||
SERIES_DIR: /app/series
|
SERIES_DIR: /app/series
|
||||||
DB_PATH: /app/state/runs.db
|
# DB separati per dominio:
|
||||||
|
GA_DB_PATH: /app/state/runs.db
|
||||||
|
STRATEGY_CRYPTO_DB_PATH: /app/state/strategy_crypto.db
|
||||||
|
# DASHBOARD_ROOT_PATH e' ora per-servizio (vedi environment blocks sotto).
|
||||||
|
# IMPORTANT: NON usare StripPrefix middleware con questo. NiceGUI/Starlette
|
||||||
|
# gestisce internamente il root_path su request path che ARRIVANO con prefix.
|
||||||
|
# StripPrefix causa doppio prefix negli asset URL (NiceGUI prefixa + uvicorn
|
||||||
|
# rilegge X-Forwarded-Prefix e prefixa di nuovo).
|
||||||
|
|
||||||
services:
|
services:
|
||||||
multi-swarm-paper:
|
strategy-crypto-paper:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
image: multi-swarm:dev
|
image: multi-swarm-coevolutive:dev
|
||||||
container_name: multi-swarm-paper
|
container_name: strategy-crypto-paper
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
networks: [traefik]
|
networks: [traefik]
|
||||||
env_file: .env
|
env_file: .env
|
||||||
@@ -49,7 +60,7 @@ services:
|
|||||||
- ./data:/app/data
|
- ./data:/app/data
|
||||||
- ./series:/app/series
|
- ./series:/app/series
|
||||||
- ./state:/app/state
|
- ./state:/app/state
|
||||||
- ./strategies:/app/strategies:ro
|
- ./src/strategy_crypto/strategy_crypto/strategies:/app/strategies:ro
|
||||||
# Niente HTTP da controllare: ci affidiamo a `restart: unless-stopped`
|
# Niente HTTP da controllare: ci affidiamo a `restart: unless-stopped`
|
||||||
# e ai log per la liveness del runner.
|
# e ai log per la liveness del runner.
|
||||||
command:
|
command:
|
||||||
@@ -64,26 +75,25 @@ services:
|
|||||||
labels:
|
labels:
|
||||||
- com.centurylinklabs.watchtower.enable=true
|
- com.centurylinklabs.watchtower.enable=true
|
||||||
|
|
||||||
multi-swarm-dashboard:
|
strategy-crypto-gui:
|
||||||
image: multi-swarm:dev
|
image: multi-swarm-coevolutive:dev
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: multi-swarm-dashboard
|
container_name: strategy-crypto-gui
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
networks: [traefik]
|
networks: [traefik]
|
||||||
env_file: .env
|
env_file: .env
|
||||||
environment:
|
environment:
|
||||||
<<: *swarm-env
|
<<: *swarm-env
|
||||||
|
DASHBOARD_ROOT_PATH: /strategy_crypto_gui
|
||||||
volumes:
|
volumes:
|
||||||
# Dashboard legge solo runs.db: mount in read-only
|
# Dashboard legge solo strategy_crypto.db: state/ in read-only (WAL: vedi nota)
|
||||||
- ./state:/app/state:ro
|
- ./state:/app/state:ro
|
||||||
- ./data:/app/data:ro
|
|
||||||
- ./series:/app/series:ro
|
|
||||||
entrypoint:
|
entrypoint:
|
||||||
- python
|
- python
|
||||||
- -m
|
- -m
|
||||||
- multi_swarm.dashboard.nicegui_app
|
- strategy_crypto.frontend.nicegui_app
|
||||||
command: []
|
command: []
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test:
|
test:
|
||||||
@@ -98,9 +108,51 @@ services:
|
|||||||
labels:
|
labels:
|
||||||
- traefik.enable=true
|
- traefik.enable=true
|
||||||
- traefik.docker.network=traefik
|
- traefik.docker.network=traefik
|
||||||
- "traefik.http.routers.multi-swarm-dashboard.rule=Host(`swarm.${DOMAIN_NAME:-tielogic.xyz}`)"
|
- "traefik.http.routers.strategy-crypto-gui.rule=Host(`swarm.${DOMAIN_NAME:-tielogic.xyz}`) && PathPrefix(`/strategy_crypto_gui`)"
|
||||||
- traefik.http.routers.multi-swarm-dashboard.tls=true
|
- traefik.http.routers.strategy-crypto-gui.tls=true
|
||||||
- traefik.http.routers.multi-swarm-dashboard.entrypoints=websecure
|
- traefik.http.routers.strategy-crypto-gui.entrypoints=websecure
|
||||||
- traefik.http.routers.multi-swarm-dashboard.tls.certresolver=mytlschallenge
|
- traefik.http.routers.strategy-crypto-gui.tls.certresolver=mytlschallenge
|
||||||
- "traefik.http.services.multi-swarm-dashboard.loadbalancer.server.port=${SWARM_DASHBOARD_PORT:-8080}"
|
- "traefik.http.services.strategy-crypto-gui.loadbalancer.server.port=${SWARM_DASHBOARD_PORT:-8080}"
|
||||||
|
# replacepathregex (NON stripprefix): strippa il prefix dalla request senza
|
||||||
|
# aggiungere X-Forwarded-Prefix header. uvicorn vede solo root_path da
|
||||||
|
# ui.run(root_path=...), quindi gli asset URL vengono prefissati una sola
|
||||||
|
# volta (no doppio prefix come succederebbe con stripprefix).
|
||||||
|
- "traefik.http.middlewares.strategy-crypto-replace.replacepathregex.regex=^/strategy_crypto_gui(/.*|$$)"
|
||||||
|
- "traefik.http.middlewares.strategy-crypto-replace.replacepathregex.replacement=$$1"
|
||||||
|
- "traefik.http.routers.strategy-crypto-gui.middlewares=strategy-crypto-replace"
|
||||||
|
- com.centurylinklabs.watchtower.enable=true
|
||||||
|
|
||||||
|
multi-swarm-core-gui:
|
||||||
|
image: multi-swarm-coevolutive:dev
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: multi-swarm-core-gui
|
||||||
|
restart: unless-stopped
|
||||||
|
networks: [traefik]
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
<<: *swarm-env
|
||||||
|
DASHBOARD_ROOT_PATH: /multi_swarm_core_gui
|
||||||
|
volumes:
|
||||||
|
- ./state:/app/state:ro
|
||||||
|
entrypoint: [python, -m, multi_swarm_core.dashboard.nicegui_app]
|
||||||
|
command: []
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import os, urllib.request; urllib.request.urlopen(f'http://localhost:{os.environ.get(\"SWARM_DASHBOARD_PORT\",\"8080\")}/', timeout=3).close()"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 30s
|
||||||
|
labels:
|
||||||
|
- traefik.enable=true
|
||||||
|
- traefik.docker.network=traefik
|
||||||
|
- "traefik.http.routers.multi-swarm-core-gui.rule=Host(`swarm.${DOMAIN_NAME:-tielogic.xyz}`) && PathPrefix(`/multi_swarm_core_gui`)"
|
||||||
|
- traefik.http.routers.multi-swarm-core-gui.tls=true
|
||||||
|
- traefik.http.routers.multi-swarm-core-gui.entrypoints=websecure
|
||||||
|
- traefik.http.routers.multi-swarm-core-gui.tls.certresolver=mytlschallenge
|
||||||
|
- "traefik.http.services.multi-swarm-core-gui.loadbalancer.server.port=${SWARM_DASHBOARD_PORT:-8080}"
|
||||||
|
- "traefik.http.middlewares.multi-swarm-core-replace.replacepathregex.regex=^/multi_swarm_core_gui(/.*|$$)"
|
||||||
|
- "traefik.http.middlewares.multi-swarm-core-replace.replacepathregex.replacement=$$1"
|
||||||
|
- "traefik.http.routers.multi-swarm-core-gui.middlewares=multi-swarm-core-replace"
|
||||||
- com.centurylinklabs.watchtower.enable=true
|
- com.centurylinklabs.watchtower.enable=true
|
||||||
|
|||||||
@@ -1,282 +0,0 @@
|
|||||||
# Phase 1 Lean Spike — Rapporto Tecnico
|
|
||||||
|
|
||||||
**Autore**: Adriano Dal Pastro
|
|
||||||
**Data**: 10 maggio 2026
|
|
||||||
**Versione**: 1.0 (finalizzato)
|
|
||||||
**Status**: ✅ Phase 1 chiusa, tutti 5 hard gate passati
|
|
||||||
|
|
||||||
**Documenti correlati**:
|
|
||||||
- `docs/superpowers/specs/2026-05-09-decisione-strategica-design.md` (decisione strategica B3)
|
|
||||||
- `docs/superpowers/plans/2026-05-09-phase1-lean-spike.md` (piano implementativo)
|
|
||||||
- `docs/decisions/2026-05-10-gate-phase1.md` (decision memo finale)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Setup sperimentale
|
|
||||||
|
|
||||||
L'obiettivo della Phase 1 lean spike è dimostrare che il loop tecnico (LLM hypothesis → backtest falsification → adversarial check → GA selection) funziona end-to-end e produce output formalizzabile. I cinque hard gate definiti nello spec sez. 4.4 misurano feasibility, non alpha edge — quella è valutazione di Phase 2.
|
|
||||||
|
|
||||||
### 1.1 Configurazione del run di riferimento
|
|
||||||
|
|
||||||
Il run `phase1-real-005` (id `1c526996160446b18c0fb57d94874975`) è il primo a superare tutti i gate dopo 4 iterazioni di bug-fix (vedi sez. 3 del decision memo).
|
|
||||||
|
|
||||||
| Parametro | Valore |
|
|
||||||
|---|---|
|
|
||||||
| Population size (K) | 20 |
|
|
||||||
| Generazioni | 10 |
|
|
||||||
| Elite k | 2 |
|
|
||||||
| Tournament k | 3 |
|
|
||||||
| Crossover probability | 0.5 |
|
|
||||||
| Random seed | 42 |
|
|
||||||
| Symbol | BTC-PERPETUAL (Deribit) |
|
|
||||||
| Timeframe | 1h |
|
|
||||||
| Range storico | 2024-01-01 → 2026-01-01 (2 anni, 17545 candele) |
|
|
||||||
| Fees backtest | 5 basis points |
|
|
||||||
| n_trials_dsr | 50 |
|
|
||||||
| Tier LLM dominante | C (qwen3-235b-a22b-2507 via OpenRouter) |
|
|
||||||
| Cerbero MCP endpoint | http://localhost:9001 (locale) |
|
|
||||||
| Durata wall-clock | 29 minuti |
|
|
||||||
| Costo LLM | $0.069 |
|
|
||||||
|
|
||||||
### 1.2 Stack tecnologico
|
|
||||||
|
|
||||||
Python 3.13, uv 0.10.9. Test framework: pytest + pytest-mock + responses. Persistence: sqlite3 + sqlmodel. Parsing strategia: `json.loads` con dataclass-based AST. Analytics: pandas + numpy + scipy. LLM: openai SDK con base URL OpenRouter (route unica per tutti i tier S/A/B/C/D). HTTP: requests + tenacity. Dashboard: streamlit + plotly + canvas HTML5 custom.
|
|
||||||
|
|
||||||
### 1.3 Architettura del run
|
|
||||||
|
|
||||||
L'orchestrator (`src/multi_swarm/orchestrator/run.py`, 184 righe) coordina la pipeline end-to-end:
|
|
||||||
|
|
||||||
1. **OHLCV loading**: `CerberoOHLCVLoader` chiama `mcp-deribit/tools/get_historical` paginando in chunk da 4500 barre (cap soft Deribit ~5000). Cache parquet su sha1 della query — il run v5 ha riusato cache popolata dai run precedenti, fetch istantaneo.
|
|
||||||
2. **Market summary**: statistiche return (mean, std, skew, kurt) + classificazione regime volatilità.
|
|
||||||
3. **Initial population**: 20 genomi distribuiti uniformemente sui 6 cognitive style (physicist, biologist, historian, meteorologist, ecologist, engineer), temperature random in [0.7, 1.2], lookback random in {100, 150, 200, 300}.
|
|
||||||
4. **Per ogni generazione (10 totali)**:
|
|
||||||
- **Hypothesis**: chiamata LLM con prompt SYSTEM (regole grammar) + USER (market summary). Output JSON estratto via regex fence ```json. Se parse/validation fallisce: retry 1x con error message nel prompt utente.
|
|
||||||
- **Falsification**: AST compilato in `Callable[[df], Series[Side]]`, backtest event-driven con 1-bar exec delay, calcolo Sharpe + Deflated Sharpe (Bailey & López 2014, n_trials=50).
|
|
||||||
- **Adversarial**: 4 check euristici (no_trades, degenerate, overtrading, undertrading).
|
|
||||||
- **Fitness**: `0.5*dsr + 0.25*(tanh(sharpe)+1)` × `1/(1+max_dd)`, range [0, ~1]. Kill (=0) su zero trade o HIGH adversarial finding.
|
|
||||||
- **Next generation**: elitism 2 + tournament 3 + 50% crossover / 50% mutation.
|
|
||||||
5. **Persistence SQLite**: ogni genome, evaluation, cost_record, adversarial_finding, generation summary persistito con indici per query rapide della dashboard.
|
|
||||||
|
|
||||||
### 1.4 Caveat metodologici noti
|
|
||||||
|
|
||||||
- **In-sample**: il backtest in Phase 1 lean spike non usa walk-forward; tutto il range 2024-2026 viene usato sia per la generazione delle ipotesi sia per la loro valutazione. La sopravvivenza out-of-sample è esplicitamente fuori scope di Phase 1 (gate Phase 2 #2).
|
|
||||||
- **Compiler con indicatori built-in**: il compiler JSON-based (`src/multi_swarm/protocol/compiler.py`) calcola RSI, SMA, ATR, MACD, realized_vol localmente con pandas. `CerberoTools` è plumbed ma non chiamato durante l'esecuzione delle strategie — è disponibile per agenti future-tense ma il fitness Phase 1 dipende solo dagli indicatori locali.
|
|
||||||
- **RSI epsilon-floor**: il compiler ha un epsilon sul `roll_down` per evitare RSI=100 esatto su serie monotonicamente crescenti (artefatto matematico irrilevante su dati reali ma documentato).
|
|
||||||
- **Top-1 strategia con DSR marginale**: vedi sez. 3.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Loop convergence
|
|
||||||
|
|
||||||
### 2.1 Fitness per generazione
|
|
||||||
|
|
||||||
| Gen | Median | Max | P90 | Entropy |
|
|
||||||
|---|---|---|---|---|
|
|
||||||
| 0 | 0.0001 | 0.0601 | 0.0165 | 0.588 |
|
|
||||||
| 1 | 0.0042 | 0.1893 | 0.0731 | 1.261 |
|
|
||||||
| 2 | 0.0188 | 0.3347 | 0.2039 | 1.333 |
|
|
||||||
| 3 | 0.0069 | 0.3347 | 0.3347 | 1.347 |
|
|
||||||
| 4 | 0.0910 | 0.3347 | 0.3347 | 1.415 |
|
|
||||||
| 5 | 0.0016 | 0.3347 | 0.3347 | 0.611 |
|
|
||||||
| 6 | 0.0040 | 0.3347 | 0.3347 | 0.886 |
|
|
||||||
| 7 | 0.0151 | 0.3347 | 0.3347 | 0.982 |
|
|
||||||
| 8 | 0.0066 | 0.3347 | 0.3347 | 0.746 |
|
|
||||||
| 9 | 0.0061 | 0.3347 | 0.3347 | 0.914 |
|
|
||||||
|
|
||||||
### 2.2 Lettura
|
|
||||||
|
|
||||||
**Convergenza tre-step iniziale**: gen 0→1→2 mostra crescita mediana 4x-50x (0.0001 → 0.0042 → 0.0188) e crescita max 3x-6x (0.06 → 0.19 → 0.33). Gate 1 PASS su questa finestra.
|
|
||||||
|
|
||||||
**Plateau dell'elite da gen 2**: max stabile a 0.3347 per le restanti 7 generazioni — comportamento atteso con `elite_k=2` che preserva il top performer attraverso le generazioni. P90 si allinea al max da gen 3, segno che almeno 2 elite mantengono la top fitness.
|
|
||||||
|
|
||||||
**Median oscillante**: dopo il picco a gen 4 (0.091), la median fluttua fra 0.0016 e 0.0151 nelle generazioni successive. Causa: turnover stocastico della popolazione (mutation + crossover) introduce genomi nuovi, alcuni dei quali parse correctly ma falliscono Adversarial (no_trades) e si attestano a fitness 0, abbassando la median. Non è regressione strutturale del GA.
|
|
||||||
|
|
||||||
**Entropy**: oscilla 0.6-1.4 dopo gen 0, sempre sopra soglia 0.5 → diversità di fitness preservata anche durante plateau dell'elite.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Top-5 genomi: ispezione qualitativa
|
|
||||||
|
|
||||||
| Rank | Genome ID | Gen | Style | Fitness | DSR | Sharpe | Max DD | Trades | Temp |
|
|
||||||
|---|---|---|---|---|---|---|---|---|---|
|
|
||||||
| 1 | `696052b8...` | 2 | physicist | 0.3347 | 0.0021 | 0.381 | 0.0215 | 33 | 0.68 |
|
|
||||||
| 2 | `169376a2...` | 1 | engineer | 0.3347 | 0.0021 | 0.381 | 0.0215 | 33 | 0.78 |
|
|
||||||
| 3 | `eb0265ad...` | 3 | ecologist | 0.2453 | 0.0006 | −0.019 | 0.0011 | 1 | 1.14 |
|
|
||||||
| 4 | `38d4c1d9...` | 1 | engineer | 0.1893 | 0.0001 | −0.245 | 0.0028 | 1 | 0.82 |
|
|
||||||
| 5 | `3e355975...` | 1 | physicist | 0.1893 | 0.0001 | −0.245 | 0.0028 | 1 | 0.78 |
|
|
||||||
|
|
||||||
### 3.1 Top-1 strategia (ispezione approfondita)
|
|
||||||
|
|
||||||
**System prompt** (engineer): *"Cerca segnali con rapporto S/N favorevole, filtri causali, robustezza a perturbazioni di calibrazione."*
|
|
||||||
|
|
||||||
**Strategia JSON** (3 regole, evaluation in ordine):
|
|
||||||
|
|
||||||
- **LONG**: `SMA(10) crossover SMA(30)` AND `realized_vol(20) > 0.3%` AND `RSI(14) < 45`.
|
|
||||||
- **SHORT**: `SMA(10) crossunder SMA(30)` AND `realized_vol(20) > 0.3%` AND `RSI(14) > 55`.
|
|
||||||
- **EXIT**: (`RSI(14) > 70` AND `close crossover SMA(50)`) OR `realized_vol(20) < 0.1%`.
|
|
||||||
|
|
||||||
**Lettura economica**: trend-following SMA-cross fast/slow modulato da filtro volatilità (entra solo quando il regime è abbastanza mosso, esce quando è troppo calmo) e filtro RSI come momentum confirmation (long solo se non già ipercomprato; short solo se non già ipervenduto). L'EXIT è sofisticato: esce su overbought confermato da break sopra MA50, OPPURE su collasso di volatilità.
|
|
||||||
|
|
||||||
**Performance**: 33 trade su 17545 candele (1 trade ogni 532 candele = 1 ogni 22 giorni). Sharpe positivo modesto, max drawdown 2.15% (basso). DSR praticamente zero (0.0021) — il segnale non è statisticamente significativo dopo correzione multiple testing, perché 33 trade su 2 anni è sample piccolo.
|
|
||||||
|
|
||||||
**Plausibilità**: pattern economicamente sensato, non casuale. Reminiscente di strategie trend-following classiche (Donchian, turtle-style) con filtri di regime. Lo stile cognitivo "engineer" (S/N favorable, filtri causali) si riflette nella struttura.
|
|
||||||
|
|
||||||
### 3.2 Top-2/3/4/5 brevemente
|
|
||||||
|
|
||||||
- Top-2 è una replica funzionale di Top-1 con metriche identiche. Plausibile elite duplicato o convergenza indipendente sulla stessa strategia (verifica per Phase 2: signal correlation fra duplicati).
|
|
||||||
- Top-3, 4, 5 hanno **1 trade ciascuno** su 2 anni. Sono "lucky shot": una posizione tenuta a lungo che casualmente termina con leggera vincita. Adversarial flagga MEDIUM `undertrading` ma non HIGH, quindi sopravvivono. La fitness function continua dà loro valore non-zero perché `tanh(sharpe)` è leggermente sopra 0.5 e penalty drawdown è quasi 1.0 (max_dd <0.5%).
|
|
||||||
|
|
||||||
### 3.3 Ratio top-1 / median
|
|
||||||
|
|
||||||
Median fitness su 98 evals: 0.0003.
|
|
||||||
Top-1 fitness: 0.3347.
|
|
||||||
**Ratio**: 1116x — Gate 3 soddisfatto con margine drammatico (soglia 1.5x).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Parser failure modes
|
|
||||||
|
|
||||||
### 4.1 Statistiche aggregate v5
|
|
||||||
|
|
||||||
- Evaluations totali: 98
|
|
||||||
- Parse success: **98 (100.0%)**
|
|
||||||
- Parse failure: **0 (0.0%)**
|
|
||||||
|
|
||||||
### 4.2 Confronto con iterazioni precedenti
|
|
||||||
|
|
||||||
| Run | Grammar | Parse success | Note |
|
|
||||||
|---|---|---|---|
|
|
||||||
| v1 | S-expression | 33% | LLM nesta indicators non supportati |
|
|
||||||
| v4 | S-expression (con arity check post-fix) | 36% | 89 di 98 errori = `indicator nested` |
|
|
||||||
| v5 | **JSON Schema** | **100%** | Refactor commit `44eb643` |
|
|
||||||
|
|
||||||
Il salto da 36% a 100% deriva interamente dal cambio di grammar. JSON è natively supported dal training dei modelli LLM moderni; S-expression è esotica e induce hallucination di sintassi creative.
|
|
||||||
|
|
||||||
### 4.3 Retry-with-feedback (commit `d4fcb42`)
|
|
||||||
|
|
||||||
Il sistema accetta 1 retry con error feedback. Nel run v5 il retry **non è mai stato usato** (zero retry per parse, dato il 100% di success). Il retry rimane comunque architetturalmente presente per Phase 2 / casi edge.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Costi reali vs preventivo
|
|
||||||
|
|
||||||
### 5.1 Breakdown costi LLM v5
|
|
||||||
|
|
||||||
| Tier | Calls | Input tokens | Output tokens | Cost USD |
|
|
||||||
|---|---|---|---|---|
|
|
||||||
| C (qwen3-235b) | 113 | 112369 | 60060 | $0.069 |
|
|
||||||
|
|
||||||
### 5.2 Costo cumulativo Phase 1 (5 run, inclusi bug-fix iterations)
|
|
||||||
|
|
||||||
| Run | Cost | Note |
|
|
||||||
|---|---|---|
|
|
||||||
| v1 (aborted) | $0.034 | 67% parse_error, max_dd bug |
|
|
||||||
| v2 (aborted) | $0.018 | macd 3 args, OHLCV cap discovery |
|
|
||||||
| v3 (aborted) | $0.015 | crash su indicator arity |
|
|
||||||
| v4 (completed FAIL) | $0.057 | 36% parse, fitness tutti 0 |
|
|
||||||
| v5 (completed PASS) | $0.069 | tutti gate passati |
|
|
||||||
| **Totale Phase 1** | **$0.193** | — |
|
|
||||||
|
|
||||||
### 5.3 Confronto con preventivo
|
|
||||||
|
|
||||||
- Preventivo originale (basato su pricing Anthropic Sonnet): $500-700.
|
|
||||||
- Spesa reale Phase 1 totale: **$0.19**.
|
|
||||||
- Deviazione: −99.97%.
|
|
||||||
|
|
||||||
La differenza non è dovuta a underuse — il run v5 ha fatto 113 chiamate LLM = full saturazione del budget previsto di calls. È un cambio di ordine di grandezza nei prezzi dovuto al pricing aggressivo di OpenRouter per modelli open-weights (qwen3-235b è 7.5x più economico di Sonnet su input, 37x su output). Il preventivo originale era calibrato su Sonnet 4.6.
|
|
||||||
|
|
||||||
### 5.4 Implicazioni per Phase 2
|
|
||||||
|
|
||||||
Il margine economico permette di pianificare Phase 2 con maggiore aggressività senza superare il cap ($700-1100):
|
|
||||||
- K=40 (×2), gen=15 (×1.5), tier mix 30% B / 70% C, ablation runs multiple.
|
|
||||||
- Estrapolazione lineare conservativa: $0.07 × 2 × 1.5 × ~3 (tier B factor) × 5 (ablation) = ~$3 totali. Possibile spingere a $30-50 senza preoccupazioni se serve per ablation più ricche.
|
|
||||||
|
|
||||||
**Rischio cost-trap inverso**: tentazione di sovra-dimensionare Phase 2 perché "tanto costa nulla". Mantenere disciplina budget invariata — investire i $700 cap in PIÙ ablation, non in run più grandi.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Diversity metrics
|
|
||||||
|
|
||||||
### 6.1 Entropy fitness per generazione
|
|
||||||
|
|
||||||
Vedi tabella sez. 2.1 colonna entropy. Mai sotto 0.5, picco a gen 4 (1.415).
|
|
||||||
|
|
||||||
### 6.2 Cognitive style sopravvissuti gen 9
|
|
||||||
|
|
||||||
| Stile | Count gen 9 | Avg fitness | Note |
|
|
||||||
|---|---|---|---|
|
|
||||||
| engineer | 3 | 0.0 | Dominante numericamente ma fitness 0 (genomi recent, non valutati su elite) |
|
|
||||||
| physicist | 1 | 0.0598 | Solo presente nel top-K |
|
|
||||||
| historian | 1 | 0.0002 | — |
|
|
||||||
| biologist | 0 | — | Estinto |
|
|
||||||
| meteorologist | 0 | — | Estinto |
|
|
||||||
| ecologist | 0 | — | Estinto |
|
|
||||||
|
|
||||||
**Lettura**: pressione selettiva ha eliminato 3 di 6 stili cognitivi alla generazione finale. Engineer è dominante numericamente, physicist domina nel valore (l'unico con fitness >0 della popolazione "live" gen 9). Phase 2 deve introdurre speciation esplicita per evitare questo collasso (minimum 2-3 specie protette).
|
|
||||||
|
|
||||||
### 6.3 Trade distribution sui 98 evals
|
|
||||||
|
|
||||||
| Categoria | n | % |
|
|
||||||
|---|---|---|
|
|
||||||
| Zero trade (HIGH no_trades, kill) | 42 | 42.9% |
|
|
||||||
| Undertrading (1-4 trade, MEDIUM) | 5 | 5.1% |
|
|
||||||
| Normal (5-100 trade) | 9 | 9.2% |
|
|
||||||
| Overtrading (>100 trade, NON flaggato) | 42 | 42.9% |
|
|
||||||
|
|
||||||
**Issue identificato**: il 42.9% di overtrading non viene catturato dall'Adversarial perché la soglia attuale è `n_trades > n_bars/5 = 3509` — troppo alta per essere triggerata su 1000-2000 trade. Phase 2 dovrebbe abbassare a `n_bars/20 = 877` o usare metrica relativa al regime.
|
|
||||||
|
|
||||||
### 6.4 Adversarial findings totali
|
|
||||||
|
|
||||||
| Finding | Severity | Count |
|
|
||||||
|---|---|---|
|
|
||||||
| no_trades | HIGH | 42 |
|
|
||||||
| undertrading | MEDIUM | 5 |
|
|
||||||
|
|
||||||
Niente `degenerate` né `overtrading` flaggato. Il primo è raro (richiede strategia sempre-LONG o sempre-SHORT puro), il secondo soffre della soglia troppo alta.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Threats to validity
|
|
||||||
|
|
||||||
Lista esplicita dei limiti metodologici da non sovra-interpretare:
|
|
||||||
|
|
||||||
1. **In-sample fitting**: tutto il backtest è in-sample. Il top-1 ha Sharpe 0.38 ottenuto guardando i dati su cui è stato selezionato. Phase 2 (walk-forward + hold-out Q1-Q2 2026 intoccabile) misura overfitting reale.
|
|
||||||
2. **Tier C unico**: nessun confronto contro tier B/S. Possibile underperformance del LLM economico vs Sonnet/Opus. Phase 2 introduce ablation multi-tier.
|
|
||||||
3. **Adversarial hand-crafted**: 4 check euristici (no_trades, degenerate, overtrading, undertrading). Phase 2 introduce 5 prompt LLM-driven dedicati (data snooping, lookahead, regime fragility, crowding, transaction cost erosion).
|
|
||||||
4. **Fitness function v1**: lineare in DSR + tanh(Sharpe) normalizzato + drawdown moltiplicativa. Non multi-livello (per-team, anti-collusion). Phase 2 introduce.
|
|
||||||
5. **No speciation, no novelty bonus**: cognitive style scendono da 6 a 3 a gen 9. Phase 2 deve mitigare.
|
|
||||||
6. **DSR del top-1 = 0.0021**: il "successo" del Gate 3 è guidato da Sharpe (positivo modesto), non da significatività statistica vera. Senza walk-forward + multiple testing rigoroso, non si può affermare alpha edge.
|
|
||||||
7. **Top-3/4/5 sono "lucky shot" 1-trade**: la fitness function continua li promuove perché drawdown bassissimo + sharpe leggermente negativo, ma sono artefatti. Phase 2 promuove undertrading a HIGH se `n_trades < 10`.
|
|
||||||
8. **Cerbero/Deribit data quality**: nessuna detection di gap, outlier, exchange downtime. Da affrontare prima di forward-test (Phase 3).
|
|
||||||
9. **Cost predictability inverso**: Phase 2 deve resistere alla tentazione di sovra-dimensionare perché Phase 1 è costata $0.19.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Conclusioni e implicazioni per Phase 2
|
|
||||||
|
|
||||||
**Hard gate sintesi**: ✅ 5 su 5 passati.
|
|
||||||
|
|
||||||
**Decisione finale**: **GO Phase 2** (formalizzata nel decision memo).
|
|
||||||
|
|
||||||
**Apprendimenti chiave per Phase 2**:
|
|
||||||
|
|
||||||
1. **JSON >> S-expression** per grammar LLM-generated. Phase 2 non rivisita.
|
|
||||||
2. **Fitness continua è essenziale** per dare gradient al GA, ma può promuovere strategie degeneri (1-trade) che vanno killate diversamente.
|
|
||||||
3. **OpenRouter qwen3-235b** è sorprendentemente capace per generare strategie strutturate, dato un prompt schema-rigoroso. Tier B (Sonnet) potrebbe non essere necessario al 30% come pianificato; ablation Phase 2 misurerà il vero contributo.
|
|
||||||
4. **Cerbero MCP come single source of truth** funziona: paginazione, cache parquet, audit log integrati senza fragility.
|
|
||||||
5. **Bug-fix discovery via run reale** è efficiente: 4 cicli, ognuno ha esposto un problema specifico (max_dd math, macd arity, validator arity, fitness clamp, grammar choice). Phase 2 può aspettarsi pattern simile per nuove componenti (speciation edge cases, OOS overfitting, multi-tier dispatch).
|
|
||||||
|
|
||||||
**Riusabilità del codebase Phase 1**: il design modulare (data, backtest, metrics, cerbero, protocol, genome, llm, agents, ga, persistence, orchestrator, dashboard) è riusabile direttamente. Estensioni Phase 2:
|
|
||||||
- `ga/speciation.py` (nuovo) — clustering cosine similarity prompt, quota tournament per specie.
|
|
||||||
- `ga/fitness.py` — versione v2 con novelty bonus + per-team aggregation.
|
|
||||||
- `orchestrator/run.py` — integrazione walk-forward.
|
|
||||||
- `agents/adversarial_llm.py` (nuovo) — 5 prompt LLM-driven.
|
|
||||||
- `baseline/random_forest.py` (nuovo) — RF baseline per benchmark.
|
|
||||||
|
|
||||||
**Costo stimato Phase 2**: $3-15 (estrapolazione molto conservativa). Cap rimane $700-1100 invariato per disciplina.
|
|
||||||
|
|
||||||
**Tempo stimato Phase 2**: 4-6 settimane di lavoro calendar, includendo i 3 aggiustamenti del decision memo (Adversarial soglie, speciation, walk-forward).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
*Documento finalizzato 10 maggio 2026. Versione 1.0.*
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,318 +0,0 @@
|
|||||||
# `mutate_prompt_llm` — Phase 2.5 Implementation Plan
|
|
||||||
|
|
||||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
|
|
||||||
|
|
||||||
**Status:** **TUTTI I 6 TASK COMPLETATI** (task 1-5 il 2026-05-11, task 6 il 2026-05-12). Mergiati su main. Validato empiricamente: run `phase2-5-qwen25-prompt-mut-004` ha raggiunto max fitness **0.1012** (+225% vs baseline `phase2-qwen25-control-001` 0.0311). Sweet spot weight=0.30 (curva U: weight=0.50 → regressione plateau 0.0311; weight=0.00 → baseline piatto).
|
|
||||||
|
|
||||||
**Trigger Phase 2.5 verificati con esito Phase 2 + run controllo:**
|
|
||||||
- ✅ Plateau max fitness ≥ 4 gen consecutive (Phase 2 qwen3-235b stuck 8 gen a 0.0238; run controllo qwen-2.5-72b stuck 9 gen a 0.0311).
|
|
||||||
- ✅ Diversità prompt collapsed: top genomi del run controllo hanno fitness/Sharpe/DD identici (mutazioni scalari non producono varianti significative).
|
|
||||||
- ✗ Top quasi-fit ≥ 0.10 non raggiunto, ma 2/3 trigger sufficienti.
|
|
||||||
|
|
||||||
**Decisione collaterale:** rollback tier C a `qwen/qwen-2.5-72b-instruct` (run controllo l'ha dimostrato superiore a qwen3-235b: +30% fitness, 4× entropy, metà costo e tempo).
|
|
||||||
|
|
||||||
**Goal:** Introdurre un quinto operatore di mutazione che usa un LLM tier B come "mutator" per riscrivere il `system_prompt` di un genoma, generando diversità reale dove oggi `random_mutate` tocca solo quattro scalari. La pipeline GA esistente resta intatta: `mutate_prompt_llm` è solo un nuovo membro di `MUTATION_OPS` con peso configurabile.
|
|
||||||
|
|
||||||
**Architecture:** Operatore puro come gli altri quattro (`mutate_temperature`, `mutate_lookback`, `mutate_feature_access`, `mutate_cognitive_style`). Riceve `parent_genome`, `llm_client`, `rng` e restituisce un child genome con `system_prompt` modificato. Il mutator LLM (tier B = `deepseek/deepseek-v4-flash`) riceve una mutation-instruction casuale tra sei tipi predefiniti (`tighten_threshold`, `swap_comparator`, `add_condition`, `remove_condition`, `change_timeframe`, `add_temporal_gate`) e produce un nuovo prompt vincolato a una mutazione "atomica". Il child viene validato (parser + adversarial dry-run); su fallimento si effettua fallback a `random_mutate`. Selezione probabilistica nel `random_mutate` dispatcher con peso configurabile (default 0.30) — i quattro operator scalari mantengono il 70% complessivo.
|
|
||||||
|
|
||||||
**Tech Stack:** Python 3.13, `LLMClient` esistente (OpenAI SDK via OpenRouter), pytest + `pytest-mock`. Niente nuove dipendenze.
|
|
||||||
|
|
||||||
**Spec di riferimento:** sezione "Meccanismo di mutazione" della conversazione `2026-05-11`, valutazione `mutate_prompt_llm` (questa pagina contiene la sintesi).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Trigger condition (quando attivare)
|
|
||||||
|
|
||||||
Implementare e mergiare **solo se** uno dei seguenti è vero al termine di Phase 2:
|
|
||||||
|
|
||||||
1. **Plateau evolutivo**: max fitness stagnante (Δ < 0.01) per ≥ 4 generazioni consecutive su `phase2-qwen3-001` o successori.
|
|
||||||
2. **Diversità prompt collassa**: media Levenshtein normalizzata fra i prompt della popolazione finale ≤ 0.15 (= popolazione clonata).
|
|
||||||
3. **Top genome problematico ma quasi-fit**: max fitness ≥ 0.10 ma adversarial finding HIGH ≥ 2 per il top, suggerendo che una mutazione mirata del prompt potrebbe "ripararlo".
|
|
||||||
|
|
||||||
Se Phase 2 raggiunge max fitness ≥ 0.30 senza plateau, **non attivare** (la diversità random basta).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## File map
|
|
||||||
|
|
||||||
| File | Tipo | Responsabilità |
|
|
||||||
|------|------|----------------|
|
|
||||||
| `src/multi_swarm/genome/mutation_prompt_llm.py` | New | Operatore `mutate_prompt_llm` + helper `MUTATION_INSTRUCTIONS` + retry/fallback wrapper |
|
|
||||||
| `src/multi_swarm/genome/mutation.py` | Modify | Estendere `MUTATION_OPS` + introdurre dispatcher pesato `weighted_random_mutate` |
|
|
||||||
| `src/multi_swarm/ga/loop.py` | Modify | Sostituire `random_mutate(parent, rng)` con `weighted_random_mutate(parent, rng, llm_client, weights)` |
|
|
||||||
| `src/multi_swarm/orchestrator/run.py` | Modify | Aggiungere `mutator_tier: ModelTier = ModelTier.B` e `prompt_mutation_weight: float = 0.30` a `RunConfig`, passare `LLMClient` al loop GA |
|
|
||||||
| `src/multi_swarm/llm/cost_tracker.py` | Modify (minimo) | Loggare `mutation_call` separatamente da `hypothesis_call` per attribuzione costo |
|
|
||||||
| `src/multi_swarm/metrics/diversity.py` | New | Funzione `population_prompt_diversity` (Levenshtein normalizzata) — usata in trigger check + telemetry |
|
|
||||||
| `tests/unit/test_mutation_prompt_llm.py` | New | Test operator con mock `LLMClient` (success + validation fail + retry/fallback) |
|
|
||||||
| `tests/unit/test_mutation_dispatcher.py` | New | Test `weighted_random_mutate` rispetta i pesi |
|
|
||||||
| `tests/unit/test_diversity.py` | New | Test `population_prompt_diversity` su prompt identici/diversi |
|
|
||||||
| `tests/integration/test_ga_loop_with_prompt_mutator.py` | New | Loop end-to-end di 2 gen × 5 genomi con mock LLM, verifica diversità prompt cresce |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 1: Mutator instructions + operator stub
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- New: `src/multi_swarm/genome/mutation_prompt_llm.py`
|
|
||||||
- New: `tests/unit/test_mutation_prompt_llm.py`
|
|
||||||
|
|
||||||
- [x] **Step 1.1: Write failing test — operator returns child con system_prompt diverso**
|
|
||||||
|
|
||||||
Append a `tests/unit/test_mutation_prompt_llm.py`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_mutate_prompt_llm_produces_different_prompt(mock_llm: LLMClient) -> None:
|
|
||||||
parent = make_genome(system_prompt="Strategia: compra quando RSI < 30")
|
|
||||||
mock_llm.respond_with("Strategia: compra quando RSI < 25 e ora >= 14")
|
|
||||||
child = mutate_prompt_llm(parent, mock_llm, rng=random.Random(0))
|
|
||||||
assert child.system_prompt != parent.system_prompt
|
|
||||||
assert child.parent_ids == [*parent.parent_ids, parent.id]
|
|
||||||
assert child.generation == parent.generation + 1
|
|
||||||
```
|
|
||||||
|
|
||||||
- [x] **Step 1.2: Implement `MUTATION_INSTRUCTIONS` constant**
|
|
||||||
|
|
||||||
`mutation_prompt_llm.py`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
MUTATION_INSTRUCTIONS: dict[str, str] = {
|
|
||||||
"tighten_threshold": "Rendi una soglia numerica più restrittiva del 10–20%...",
|
|
||||||
"swap_comparator": "Inverti un comparator (gt ↔ lt, gte ↔ lte) mantenendo intent...",
|
|
||||||
"add_condition": "Aggiungi una condizione AND/OR alla rule più specifica...",
|
|
||||||
"remove_condition": "Rimuovi una condizione ridondante o debole...",
|
|
||||||
"change_timeframe": "Modifica una finestra rolling (lookback) di ±30%...",
|
|
||||||
"add_temporal_gate": "Aggiungi un gate temporale (hour, dow, is_weekend)...",
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [x] **Step 1.3: Implement `mutate_prompt_llm`**
|
|
||||||
|
|
||||||
Firma:
|
|
||||||
```python
|
|
||||||
def mutate_prompt_llm(
|
|
||||||
g: HypothesisAgentGenome,
|
|
||||||
llm: LLMClient,
|
|
||||||
rng: random.Random,
|
|
||||||
mutator_tier: ModelTier = ModelTier.B,
|
|
||||||
) -> HypothesisAgentGenome:
|
|
||||||
```
|
|
||||||
|
|
||||||
Logica:
|
|
||||||
1. Scegli `instruction_key = rng.choice(list(MUTATION_INSTRUCTIONS))`.
|
|
||||||
2. Costruisci messaggio system + user con `MUTATION_INSTRUCTIONS[instruction_key]` + `g.system_prompt`.
|
|
||||||
3. Crea genoma temporaneo `mutator_genome` con `model_tier=mutator_tier`.
|
|
||||||
4. Chiama `llm.complete(mutator_genome, system, user, max_tokens=2000)`.
|
|
||||||
5. Estrai nuovo prompt da risposta (cerca blocco `<prompt>...</prompt>` o intero output).
|
|
||||||
6. Ritorna `_clone_with(g, system_prompt=new_prompt)` (riusa helper di `mutation.py`).
|
|
||||||
|
|
||||||
- [x] **Step 1.4: Run test → green**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
uv run pytest tests/unit/test_mutation_prompt_llm.py::test_mutate_prompt_llm_produces_different_prompt -xvs
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 2: Validation + fallback
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/multi_swarm/genome/mutation_prompt_llm.py`
|
|
||||||
- Append: `tests/unit/test_mutation_prompt_llm.py`
|
|
||||||
|
|
||||||
- [x] **Step 2.1: Write failing test — fallback a random_mutate su prompt invalid**
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_mutate_prompt_llm_falls_back_on_invalid_prompt(mock_llm: LLMClient) -> None:
|
|
||||||
parent = make_genome()
|
|
||||||
mock_llm.respond_with("garbage that does not parse")
|
|
||||||
child = mutate_prompt_llm(parent, mock_llm, rng=random.Random(0))
|
|
||||||
# Garbage prompt deve fallback: child è prodotto da random_mutate, quindi
|
|
||||||
# system_prompt == parent.system_prompt (random_mutate tocca solo scalari)
|
|
||||||
assert child.system_prompt == parent.system_prompt
|
|
||||||
assert child.parent_ids == [*parent.parent_ids, parent.id]
|
|
||||||
```
|
|
||||||
|
|
||||||
- [x] **Step 2.2: Implement validation step**
|
|
||||||
|
|
||||||
Dopo aver estratto `new_prompt`, esegui `validate_prompt(new_prompt)`:
|
|
||||||
- Lunghezza minima 50 caratteri.
|
|
||||||
- Contiene almeno una keyword fra `{rsi, sma, ema, atr, momentum, breakout, mean reversion, gt, lt, ...}`.
|
|
||||||
- Non identico a `parent.system_prompt` (Levenshtein > 0.05 normalizzata).
|
|
||||||
|
|
||||||
Su fail → log warning + ritorna `random_mutate(g, rng)`.
|
|
||||||
|
|
||||||
- [x] **Step 2.3: Write failing test — diversity guard**
|
|
||||||
|
|
||||||
Mock LLM ritorna prompt identico al parent → `validate_prompt` rifiuta → fallback.
|
|
||||||
|
|
||||||
- [x] **Step 2.4: Run test suite parziale**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
uv run pytest tests/unit/test_mutation_prompt_llm.py -xvs
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 3: Weighted dispatcher
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/multi_swarm/genome/mutation.py`
|
|
||||||
- New: `tests/unit/test_mutation_dispatcher.py`
|
|
||||||
|
|
||||||
- [x] **Step 3.1: Write failing test — weighted_random_mutate rispetta pesi**
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_weighted_random_mutate_picks_prompt_op_at_configured_rate() -> None:
|
|
||||||
rng = random.Random(0)
|
|
||||||
weights = {"prompt": 1.0, "scalar": 0.0} # 100% prompt
|
|
||||||
counter = Counter()
|
|
||||||
for _ in range(100):
|
|
||||||
op_name = _pick_op_name(weights, rng)
|
|
||||||
counter[op_name] += 1
|
|
||||||
assert counter["prompt"] == 100
|
|
||||||
```
|
|
||||||
|
|
||||||
- [x] **Step 3.2: Implement `weighted_random_mutate`**
|
|
||||||
|
|
||||||
```python
|
|
||||||
def weighted_random_mutate(
|
|
||||||
g: HypothesisAgentGenome,
|
|
||||||
rng: random.Random,
|
|
||||||
llm: LLMClient | None = None,
|
|
||||||
prompt_mutation_weight: float = 0.30,
|
|
||||||
) -> HypothesisAgentGenome:
|
|
||||||
if llm is not None and rng.random() < prompt_mutation_weight:
|
|
||||||
return mutate_prompt_llm(g, llm, rng)
|
|
||||||
return random_mutate(g, rng)
|
|
||||||
```
|
|
||||||
|
|
||||||
- [x] **Step 3.3: Test edge cases**
|
|
||||||
|
|
||||||
- `llm=None` → sempre scalar mutation (backward compat).
|
|
||||||
- `prompt_mutation_weight=0.0` → sempre scalar.
|
|
||||||
- `prompt_mutation_weight=1.0` → sempre prompt (se llm presente).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 4: Integrazione GA loop
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/multi_swarm/ga/loop.py`
|
|
||||||
- Modify: `src/multi_swarm/orchestrator/run.py`
|
|
||||||
- New: `tests/integration/test_ga_loop_with_prompt_mutator.py`
|
|
||||||
|
|
||||||
- [x] **Step 4.1: Estendere `GAConfig`**
|
|
||||||
|
|
||||||
```python
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class GAConfig:
|
|
||||||
population_size: int
|
|
||||||
elite_k: int
|
|
||||||
tournament_k: int
|
|
||||||
p_crossover: float
|
|
||||||
prompt_mutation_weight: float = 0.0 # default off → opt-in
|
|
||||||
```
|
|
||||||
|
|
||||||
- [x] **Step 4.2: Pass `LLMClient` in `next_generation`**
|
|
||||||
|
|
||||||
```python
|
|
||||||
def next_generation(
|
|
||||||
population: list[HypothesisAgentGenome],
|
|
||||||
fitnesses: dict[str, float],
|
|
||||||
cfg: GAConfig,
|
|
||||||
rng: random.Random,
|
|
||||||
llm: LLMClient | None = None,
|
|
||||||
) -> list[HypothesisAgentGenome]:
|
|
||||||
...
|
|
||||||
child = weighted_random_mutate(parent, rng, llm, cfg.prompt_mutation_weight)
|
|
||||||
```
|
|
||||||
|
|
||||||
- [x] **Step 4.3: Wire in orchestrator**
|
|
||||||
|
|
||||||
`RunConfig.prompt_mutation_weight: float = 0.0` (default off). Quando attivo via CLI `--prompt-mutation-weight 0.30`, passare a `next_generation`.
|
|
||||||
|
|
||||||
- [x] **Step 4.4: Integration test**
|
|
||||||
|
|
||||||
Loop 2 gen × 5 genomi, mock LLM che ritorna prompt sempre diversi. Verifica che la popolazione finale abbia più diversità prompt della iniziale.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 5: Diversity metric
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- New: `src/multi_swarm/metrics/diversity.py`
|
|
||||||
- New: `tests/unit/test_diversity.py`
|
|
||||||
|
|
||||||
- [x] **Step 5.1: Implement `population_prompt_diversity`**
|
|
||||||
|
|
||||||
```python
|
|
||||||
def population_prompt_diversity(prompts: list[str]) -> float:
|
|
||||||
"""Levenshtein normalizzata media su tutte le coppie. 0.0 = identici, 1.0 = totalmente diversi."""
|
|
||||||
```
|
|
||||||
|
|
||||||
- [x] **Step 5.2: Test**
|
|
||||||
|
|
||||||
Tre prompt identici → 0.0. Tre prompt totalmente diversi → ~1.0.
|
|
||||||
|
|
||||||
- [x] **Step 5.3: Logging**
|
|
||||||
|
|
||||||
Aggiungere `diversity_prompt` come campo per-generazione in `repository.save_generation` (richiede migration leggera).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 6: Cost attribution
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/multi_swarm/llm/cost_tracker.py`
|
|
||||||
- Modify: tests esistenti
|
|
||||||
|
|
||||||
- [x] **Step 6.1: Aggiungere `call_kind` a `CostRecord`**
|
|
||||||
|
|
||||||
```python
|
|
||||||
@dataclass
|
|
||||||
class CostRecord:
|
|
||||||
...
|
|
||||||
call_kind: str = "hypothesis" # "hypothesis" | "mutation"
|
|
||||||
```
|
|
||||||
|
|
||||||
- [x] **Step 6.2: Loggare separatamente in summary**
|
|
||||||
|
|
||||||
`summary()["by_call_kind"]` con breakdown.
|
|
||||||
|
|
||||||
- [x] **Step 6.3: Test compatibilità con record esistenti**
|
|
||||||
|
|
||||||
Backward compat: record senza `call_kind` interpretati come `"hypothesis"`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Verification end-to-end
|
|
||||||
|
|
||||||
- [x] `uv run pytest -q` → 100% passa (157 + nuovi test).
|
|
||||||
- [x] `uv run python scripts/smoke_run.py` → completa con mock LLM.
|
|
||||||
- [x] **Run baseline B**: ripetere `phase2-qwen3-001` con `--prompt-mutation-weight 0.0` per controllo.
|
|
||||||
- [x] **Run trattamento T**: `phase2-qwen3-prompt-mut-001` con `--prompt-mutation-weight 0.30`.
|
|
||||||
- [x] Confronto: max fitness T > B + 20%, diversity_prompt(T) > diversity_prompt(B) + 30%.
|
|
||||||
- [x] Costo aggiuntivo run T ≤ $0.10 (sanity check).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Risks & mitigations
|
|
||||||
|
|
||||||
| Rischio | Mitigazione |
|
|
||||||
|---------|-------------|
|
|
||||||
| Mode collapse mutator LLM | `mutation_instruction` scelta random + diversity guard Levenshtein |
|
|
||||||
| Prompt LLM-output non parsabile dal compiler | Validation step + fallback `random_mutate` |
|
|
||||||
| Costo runaway (loop infinito retry) | `max_tokens=2000`, no retry su validation fail |
|
|
||||||
| Bias condiviso con generator tier C | Mutator tier B = `deepseek-v4-flash`, famiglia diversa da Qwen3 |
|
|
||||||
| Variabili confuse con Phase 2 | Attivare **solo** dopo Phase 2 baseline; A/B isolato |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Cost estimate
|
|
||||||
|
|
||||||
Pop = 20, gen = 10, mutation rate ~75% (5 elite + 15 children), prompt_mutation_weight = 0.30:
|
|
||||||
- ~45 chiamate LLM tier B aggiuntive per run.
|
|
||||||
- ~500 tok input + 200 tok output per call → 22.5k in + 9k out totali.
|
|
||||||
- 22.5k × $0.14/1M + 9k × $0.28/1M ≈ **$0.0057/run**.
|
|
||||||
|
|
||||||
Trascurabile rispetto al budget run base (~$0.10).
|
|
||||||
@@ -1,482 +0,0 @@
|
|||||||
# Feature temporali nella grammatica Hypothesis — Implementation Plan
|
|
||||||
|
|
||||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
||||||
|
|
||||||
**Goal:** Aggiungere quattro feature temporali (`hour`, `dow`, `is_weekend`, `minute_of_hour`) alla grammatica delle strategie Hypothesis come `FeatureNode`, universalmente accessibili a ogni genoma e usabili con i comparator esistenti.
|
|
||||||
|
|
||||||
**Architecture:** Estensione puramente additiva. La whitelist `KNOWN_FEATURES` in `protocol/grammar.py` cresce da 5 a 9 nomi. Il dispatcher di `FeatureNode` in `protocol/compiler.py` acquisisce un branch prioritario che mappa i nomi temporali a serie derivate da `df.index` (DatetimeIndex UTC). Il prompt template di `agents/hypothesis.py` riceve due esempi few-shot. Nessuna modifica a parser, mutation/crossover, genome dataclass.
|
|
||||||
|
|
||||||
**Tech Stack:** Python 3.13, pandas (DatetimeIndex), pytest. Esecuzione via `uv run`. Repository: `/home/adriano/Documenti/Git_XYZ/Multi_Swarm_Coevolutive`.
|
|
||||||
|
|
||||||
**Spec di riferimento:** `docs/superpowers/specs/2026-05-11-temporal-features-design.md`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## File map
|
|
||||||
|
|
||||||
| File | Tipo | Responsabilità |
|
|
||||||
|------|------|----------------|
|
|
||||||
| `src/multi_swarm/protocol/grammar.py` | Modify | Estendere `KNOWN_FEATURES` |
|
|
||||||
| `src/multi_swarm/protocol/compiler.py` | Modify | Aggiungere `_TIME_FEATURE_FNS` + branch in `_eval_node` |
|
|
||||||
| `src/multi_swarm/agents/hypothesis.py` | Modify | Estendere prompt template con sezione feature temporali + 2 esempi |
|
|
||||||
| `tests/unit/test_protocol_validator.py` | Modify | +2 test (accept/reject) |
|
|
||||||
| `tests/unit/test_protocol_compiler.py` | Modify | +5 test (4 feature + 1 integrazione) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 1: Grammar extension + validator tests
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/multi_swarm/protocol/grammar.py:21-23`
|
|
||||||
- Modify: `tests/unit/test_protocol_validator.py` (append)
|
|
||||||
|
|
||||||
- [ ] **Step 1.1: Write failing test — validator accepts temporal features**
|
|
||||||
|
|
||||||
Append to `tests/unit/test_protocol_validator.py`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_validator_accepts_temporal_features() -> None:
|
|
||||||
for name in ("hour", "dow", "is_weekend", "minute_of_hour"):
|
|
||||||
src = _wrap(
|
|
||||||
{
|
|
||||||
"op": "gt",
|
|
||||||
"args": [
|
|
||||||
{"kind": "feature", "name": name},
|
|
||||||
{"kind": "literal", "value": 0},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
)
|
|
||||||
ast = parse_strategy(src)
|
|
||||||
validate_strategy(ast) # no exception
|
|
||||||
|
|
||||||
|
|
||||||
def test_validator_rejects_temporal_typo() -> None:
|
|
||||||
src = _wrap(
|
|
||||||
{
|
|
||||||
"op": "gt",
|
|
||||||
"args": [
|
|
||||||
{"kind": "feature", "name": "weekday"},
|
|
||||||
{"kind": "literal", "value": 0},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
)
|
|
||||||
ast = parse_strategy(src)
|
|
||||||
with pytest.raises(ValidationError, match="unknown feature"):
|
|
||||||
validate_strategy(ast)
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 1.2: Run tests to verify they fail**
|
|
||||||
|
|
||||||
Run: `uv run pytest tests/unit/test_protocol_validator.py::test_validator_accepts_temporal_features tests/unit/test_protocol_validator.py::test_validator_rejects_temporal_typo -v`
|
|
||||||
Expected: First test FAILs with `ValidationError: unknown feature: hour`. Second test PASSes already (weekday is unknown today too).
|
|
||||||
|
|
||||||
- [ ] **Step 1.3: Extend `KNOWN_FEATURES` whitelist**
|
|
||||||
|
|
||||||
Edit `src/multi_swarm/protocol/grammar.py`, lines 21-23:
|
|
||||||
|
|
||||||
```python
|
|
||||||
KNOWN_FEATURES: frozenset[str] = frozenset(
|
|
||||||
{"open", "high", "low", "close", "volume",
|
|
||||||
"hour", "dow", "is_weekend", "minute_of_hour"}
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 1.4: Run tests to verify both pass**
|
|
||||||
|
|
||||||
Run: `uv run pytest tests/unit/test_protocol_validator.py -v`
|
|
||||||
Expected: All tests PASS (both new tests + all pre-existing ones).
|
|
||||||
|
|
||||||
- [ ] **Step 1.5: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/multi_swarm/protocol/grammar.py tests/unit/test_protocol_validator.py
|
|
||||||
git commit -m "feat(protocol): extend KNOWN_FEATURES with temporal feature names"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 2: Compiler — `hour` feature
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/multi_swarm/protocol/compiler.py:135-137`
|
|
||||||
- Modify: `tests/unit/test_protocol_compiler.py` (append)
|
|
||||||
|
|
||||||
- [ ] **Step 2.1: Write failing test for `hour`**
|
|
||||||
|
|
||||||
Append to `tests/unit/test_protocol_compiler.py`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_compile_hour_feature_returns_index_hour(ohlcv: pd.DataFrame) -> None:
|
|
||||||
src = json.dumps(
|
|
||||||
{
|
|
||||||
"rules": [
|
|
||||||
{
|
|
||||||
"condition": {
|
|
||||||
"op": "gt",
|
|
||||||
"args": [
|
|
||||||
{"kind": "feature", "name": "hour"},
|
|
||||||
{"kind": "literal", "value": -1},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"action": "entry-long",
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
ast = parse_strategy(src)
|
|
||||||
fn = compile_strategy(ast)
|
|
||||||
signal = fn(ohlcv)
|
|
||||||
# Tutte le righe hanno hour >= 0 > -1, quindi tutte entry-long
|
|
||||||
assert (signal == Side.LONG).all()
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2.2: Run test to verify it fails**
|
|
||||||
|
|
||||||
Run: `uv run pytest tests/unit/test_protocol_compiler.py::test_compile_hour_feature_returns_index_hour -v`
|
|
||||||
Expected: FAIL with `KeyError: 'hour'` (df has no `hour` column, dispatcher falls into `df[name]`).
|
|
||||||
|
|
||||||
- [ ] **Step 2.3: Add `_TIME_FEATURE_FNS` and dispatcher branch**
|
|
||||||
|
|
||||||
Edit `src/multi_swarm/protocol/compiler.py`. Insert after line 108 (end of `INDICATOR_FNS`):
|
|
||||||
|
|
||||||
```python
|
|
||||||
_TIME_FEATURE_FNS: dict[str, Callable[[pd.DatetimeIndex], pd.Series]] = {
|
|
||||||
"hour": lambda idx: pd.Series(idx.hour, index=idx, dtype="int64"),
|
|
||||||
"dow": lambda idx: pd.Series(idx.dayofweek, index=idx, dtype="int64"),
|
|
||||||
"is_weekend": lambda idx: pd.Series((idx.dayofweek >= 5).astype("int64"), index=idx),
|
|
||||||
"minute_of_hour": lambda idx: pd.Series(idx.minute, index=idx, dtype="int64"),
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Then modify `_eval_node` at line 135-137. Replace:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def _eval_node(node: Node, df: pd.DataFrame) -> pd.Series:
|
|
||||||
if isinstance(node, FeatureNode):
|
|
||||||
return df[node.name]
|
|
||||||
```
|
|
||||||
|
|
||||||
With:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def _eval_node(node: Node, df: pd.DataFrame) -> pd.Series:
|
|
||||||
if isinstance(node, FeatureNode):
|
|
||||||
if node.name in _TIME_FEATURE_FNS:
|
|
||||||
return _TIME_FEATURE_FNS[node.name](df.index)
|
|
||||||
return df[node.name]
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 2.4: Run test to verify it passes**
|
|
||||||
|
|
||||||
Run: `uv run pytest tests/unit/test_protocol_compiler.py::test_compile_hour_feature_returns_index_hour -v`
|
|
||||||
Expected: PASS.
|
|
||||||
|
|
||||||
- [ ] **Step 2.5: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/multi_swarm/protocol/compiler.py tests/unit/test_protocol_compiler.py
|
|
||||||
git commit -m "feat(protocol): dispatcher temporal features (hour) in compiler"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 3: Compiler — `dow` and `is_weekend` tests
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `tests/unit/test_protocol_compiler.py` (append)
|
|
||||||
|
|
||||||
Nessuna modifica al sorgente: `_TIME_FEATURE_FNS` definito in Task 2 contiene già le quattro funzioni. Questi test verificano semantica e copertura.
|
|
||||||
|
|
||||||
- [ ] **Step 3.1: Add `dow` test**
|
|
||||||
|
|
||||||
Append to `tests/unit/test_protocol_compiler.py`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_compile_dow_feature_monday_is_zero(ohlcv: pd.DataFrame) -> None:
|
|
||||||
# 2024-01-01 e' un lunedi -> dow=0; gating eq dow 0 deve dare LONG su monday only.
|
|
||||||
src = json.dumps(
|
|
||||||
{
|
|
||||||
"rules": [
|
|
||||||
{
|
|
||||||
"condition": {
|
|
||||||
"op": "eq",
|
|
||||||
"args": [
|
|
||||||
{"kind": "feature", "name": "dow"},
|
|
||||||
{"kind": "literal", "value": 0},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"action": "entry-long",
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
ast = parse_strategy(src)
|
|
||||||
fn = compile_strategy(ast)
|
|
||||||
signal = fn(ohlcv)
|
|
||||||
# ohlcv fixture: 200h da 2024-01-01 00:00 UTC -> primo lunedi e' bar 0..23
|
|
||||||
monday_hours = signal[(signal.index.dayofweek == 0)]
|
|
||||||
other_hours = signal[(signal.index.dayofweek != 0)]
|
|
||||||
assert (monday_hours == Side.LONG).all()
|
|
||||||
assert (other_hours == Side.FLAT).all()
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3.2: Add `is_weekend` test**
|
|
||||||
|
|
||||||
Append:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_compile_is_weekend_returns_zero_one(ohlcv: pd.DataFrame) -> None:
|
|
||||||
src = json.dumps(
|
|
||||||
{
|
|
||||||
"rules": [
|
|
||||||
{
|
|
||||||
"condition": {
|
|
||||||
"op": "eq",
|
|
||||||
"args": [
|
|
||||||
{"kind": "feature", "name": "is_weekend"},
|
|
||||||
{"kind": "literal", "value": 1},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"action": "entry-long",
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
ast = parse_strategy(src)
|
|
||||||
fn = compile_strategy(ast)
|
|
||||||
signal = fn(ohlcv)
|
|
||||||
weekend = signal[signal.index.dayofweek >= 5]
|
|
||||||
weekdays = signal[signal.index.dayofweek < 5]
|
|
||||||
assert (weekend == Side.LONG).all()
|
|
||||||
assert (weekdays == Side.FLAT).all()
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 3.3: Run both tests**
|
|
||||||
|
|
||||||
Run: `uv run pytest tests/unit/test_protocol_compiler.py::test_compile_dow_feature_monday_is_zero tests/unit/test_protocol_compiler.py::test_compile_is_weekend_returns_zero_one -v`
|
|
||||||
Expected: Both PASS.
|
|
||||||
|
|
||||||
- [ ] **Step 3.4: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add tests/unit/test_protocol_compiler.py
|
|
||||||
git commit -m "test(protocol): compiler semantica dow + is_weekend"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 4: Compiler — `minute_of_hour` test
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `tests/unit/test_protocol_compiler.py` (append)
|
|
||||||
|
|
||||||
- [ ] **Step 4.1: Add `minute_of_hour` test**
|
|
||||||
|
|
||||||
Append:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_compile_minute_of_hour_zero_on_1h_timeframe(ohlcv: pd.DataFrame) -> None:
|
|
||||||
# Fixture ohlcv ha freq=1h, quindi tutti i minute_of_hour sono 0.
|
|
||||||
# gating eq minute_of_hour 0 -> LONG su TUTTE le righe.
|
|
||||||
src = json.dumps(
|
|
||||||
{
|
|
||||||
"rules": [
|
|
||||||
{
|
|
||||||
"condition": {
|
|
||||||
"op": "eq",
|
|
||||||
"args": [
|
|
||||||
{"kind": "feature", "name": "minute_of_hour"},
|
|
||||||
{"kind": "literal", "value": 0},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"action": "entry-long",
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
ast = parse_strategy(src)
|
|
||||||
fn = compile_strategy(ast)
|
|
||||||
signal = fn(ohlcv)
|
|
||||||
assert (signal == Side.LONG).all()
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 4.2: Run test**
|
|
||||||
|
|
||||||
Run: `uv run pytest tests/unit/test_protocol_compiler.py::test_compile_minute_of_hour_zero_on_1h_timeframe -v`
|
|
||||||
Expected: PASS.
|
|
||||||
|
|
||||||
- [ ] **Step 4.3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add tests/unit/test_protocol_compiler.py
|
|
||||||
git commit -m "test(protocol): compiler semantica minute_of_hour su 1h"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 5: Compiler — integrazione con regola completa
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `tests/unit/test_protocol_compiler.py` (append)
|
|
||||||
|
|
||||||
- [ ] **Step 5.1: Add integration test**
|
|
||||||
|
|
||||||
Append:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def test_rule_with_temporal_gating_compiles_and_executes(ohlcv: pd.DataFrame) -> None:
|
|
||||||
# Regola: entry-long se hour > 14 AND close > sma(20).
|
|
||||||
# close in fixture e' lineare crescente, quindi close > sma(20) e' True dopo warmup.
|
|
||||||
# entry-long deve apparire solo nelle bar con hour > 14.
|
|
||||||
src = json.dumps(
|
|
||||||
{
|
|
||||||
"rules": [
|
|
||||||
{
|
|
||||||
"condition": {
|
|
||||||
"op": "and",
|
|
||||||
"args": [
|
|
||||||
{
|
|
||||||
"op": "gt",
|
|
||||||
"args": [
|
|
||||||
{"kind": "feature", "name": "hour"},
|
|
||||||
{"kind": "literal", "value": 14},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"op": "gt",
|
|
||||||
"args": [
|
|
||||||
{"kind": "feature", "name": "close"},
|
|
||||||
{"kind": "indicator", "name": "sma", "params": [20]},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"action": "entry-long",
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
ast = parse_strategy(src)
|
|
||||||
fn = compile_strategy(ast)
|
|
||||||
signal = fn(ohlcv)
|
|
||||||
|
|
||||||
# Bar con hour <= 14: mai LONG (gating temporale blocca).
|
|
||||||
morning = signal[signal.index.hour <= 14]
|
|
||||||
assert (morning == Side.FLAT).all()
|
|
||||||
|
|
||||||
# Bar con hour > 14 e dopo warmup sma (>=20 bar dall'inizio): LONG.
|
|
||||||
afternoon_warm = signal[(signal.index.hour > 14) & (np.arange(len(signal)) >= 20)]
|
|
||||||
assert (afternoon_warm == Side.LONG).all()
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 5.2: Run test**
|
|
||||||
|
|
||||||
Run: `uv run pytest tests/unit/test_protocol_compiler.py::test_rule_with_temporal_gating_compiles_and_executes -v`
|
|
||||||
Expected: PASS.
|
|
||||||
|
|
||||||
- [ ] **Step 5.3: Run full compiler + validator test suite to check regressions**
|
|
||||||
|
|
||||||
Run: `uv run pytest tests/unit/test_protocol_compiler.py tests/unit/test_protocol_validator.py -v`
|
|
||||||
Expected: All tests PASS (pre-existing + new). Nessun test rotto.
|
|
||||||
|
|
||||||
- [ ] **Step 5.4: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add tests/unit/test_protocol_compiler.py
|
|
||||||
git commit -m "test(protocol): integration test gating temporale + sma"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 6: Update Hypothesis prompt
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Modify: `src/multi_swarm/agents/hypothesis.py:84-85`
|
|
||||||
|
|
||||||
- [ ] **Step 6.1: Edit prompt template**
|
|
||||||
|
|
||||||
In `src/multi_swarm/agents/hypothesis.py`, alla riga 84-85 sostituire:
|
|
||||||
|
|
||||||
```python
|
|
||||||
Leaf - feature OHLCV:
|
|
||||||
{{"kind": "feature", "name": "open|high|low|close|volume"}}
|
|
||||||
```
|
|
||||||
|
|
||||||
con:
|
|
||||||
|
|
||||||
```python
|
|
||||||
Leaf - feature OHLCV:
|
|
||||||
{{"kind": "feature", "name": "open|high|low|close|volume"}}
|
|
||||||
|
|
||||||
Leaf - feature TEMPORALI (sempre accessibili, UTC):
|
|
||||||
{{"kind": "feature", "name": "hour"}} // range 0-23
|
|
||||||
{{"kind": "feature", "name": "dow"}} // range 0-6 (lun=0, dom=6)
|
|
||||||
{{"kind": "feature", "name": "is_weekend"}} // 0 o 1
|
|
||||||
{{"kind": "feature", "name": "minute_of_hour"}} // range 0-59
|
|
||||||
|
|
||||||
Esempi di gating temporale:
|
|
||||||
// Solo durante la sessione US (14:00-22:00 UTC)
|
|
||||||
{{"op": "and", "args": [
|
|
||||||
{{"op": "gt", "args": [{{"kind": "feature", "name": "hour"}}, {{"kind": "literal", "value": 14}}]}},
|
|
||||||
{{"op": "lt", "args": [{{"kind": "feature", "name": "hour"}}, {{"kind": "literal", "value": 22}}]}}
|
|
||||||
]}}
|
|
||||||
|
|
||||||
// Solo nel weekend (sab+dom)
|
|
||||||
{{"op": "eq", "args": [{{"kind": "feature", "name": "is_weekend"}}, {{"kind": "literal", "value": 1}}]}}
|
|
||||||
```
|
|
||||||
|
|
||||||
- [ ] **Step 6.2: Run existing hypothesis tests to verify prompt format still valid**
|
|
||||||
|
|
||||||
Run: `uv run pytest tests/unit/test_hypothesis_agent.py -v`
|
|
||||||
Expected: All tests PASS. Il template `{feature_access}` continua a funzionare perché non lo abbiamo toccato.
|
|
||||||
|
|
||||||
- [ ] **Step 6.3: Commit**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/multi_swarm/agents/hypothesis.py
|
|
||||||
git commit -m "feat(hypothesis): aggiungi feature temporali al prompt con 2 esempi few-shot"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Task 7: Smoke run end-to-end
|
|
||||||
|
|
||||||
**Files:**
|
|
||||||
- Nessuna modifica al codice.
|
|
||||||
|
|
||||||
Validazione che il loop intero giri con la grammatica estesa: carica OHLCV, genera 4 genomi, compila, backtesta, valuta DSR, applica Adversarial, persiste.
|
|
||||||
|
|
||||||
- [ ] **Step 7.1: Run smoke script**
|
|
||||||
|
|
||||||
Run: `uv run python -m scripts.smoke_run`
|
|
||||||
Expected: completamento senza eccezioni, output finale contenente `Smoke run completed`.
|
|
||||||
|
|
||||||
- [ ] **Step 7.2: Inspect at least one generated genome for temporal feature usage**
|
|
||||||
|
|
||||||
Run:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
LATEST=$(sqlite3 runs.db "SELECT id FROM runs WHERE name LIKE 'smoke%' ORDER BY started_at DESC LIMIT 1;")
|
|
||||||
sqlite3 runs.db "SELECT genome_id, substr(raw_text, 1, 600) FROM evaluations WHERE run_id='$LATEST' LIMIT 4;"
|
|
||||||
```
|
|
||||||
|
|
||||||
Expected output: 4 righe raw_text JSON. Almeno 1 dovrebbe contenere `"name": "hour"`, `"name": "dow"`, `"name": "is_weekend"`, o `"name": "minute_of_hour"`. Se 0/4 usano feature temporali, il prompt non è abbastanza eloquente — apri un follow-up per iterare il prompt (non bloccante per questa PR).
|
|
||||||
|
|
||||||
- [ ] **Step 7.3: Push branch + open PR**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git log --oneline -8 # verifica 6 commit dei Task 1-6
|
|
||||||
git push origin HEAD
|
|
||||||
```
|
|
||||||
|
|
||||||
Aprire PR con titolo `feat: feature temporali nella grammatica Hypothesis` referenziando lo spec.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Self-review notes (autore del piano)
|
|
||||||
|
|
||||||
- Tutti i 7 hard requirement dello spec (`grammar`, `compiler`, `prompt`, 4 feature, integration test, smoke, backward compat) sono coperti dai Task 1-7.
|
|
||||||
- Nessun placeholder `TBD`/`TODO`.
|
|
||||||
- Tipi consistenti: `_TIME_FEATURE_FNS` definito una volta in Task 2 e referenziato implicitamente dai tester nei Task 3-5 senza bisogno di re-definizione.
|
|
||||||
- Test pre-esistenti non vengono toccati; il Task 5 include `pytest` sull'intera suite del protocollo come regression check.
|
|
||||||
- Backward compat: `KNOWN_FEATURES` cresce, il branch OHLCV resta invariato → genomi vecchi restano validi senza migrazione DB.
|
|
||||||
@@ -1,427 +0,0 @@
|
|||||||
# Decisione Strategica PoC Multi-Swarm Coevolutivo — Design
|
|
||||||
|
|
||||||
**Autore**: Adriano Dal Pastro
|
|
||||||
**Data**: 9 maggio 2026
|
|
||||||
**Status**: Design strategico approvato per implementazione
|
|
||||||
**Versione**: 1.0
|
|
||||||
**Documenti correlati**:
|
|
||||||
- `00_documento_zero.md` (framework concettuale)
|
|
||||||
- `coevolutive_swarm_system.md` (Filone A, sistema completo)
|
|
||||||
- `poc_trading_swarm.md` (Filone B, design PoC trading)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Executive Summary
|
|
||||||
|
|
||||||
Questo documento formalizza la decisione strategica su come avviare il progetto Multi-Swarm Coevolutivo. La scelta cade sulla variante **B3 — PoC trading incrementale a tre fasi con gate go/no-go**, una declinazione disciplinata dell'opzione Smart Spike (Filone B) descritta nel documento zero.
|
|
||||||
|
|
||||||
La forma incrementale tripartita non sostituisce il design del PoC contenuto in `poc_trading_swarm.md`, ne organizza l'esecuzione in fasi successive con kill-switch numerici espliciti. Il principio guida è **applicare al progetto stesso la disciplina che il sistema dovrà applicare alle proprie ipotesi**: spegnere ciò che non funziona quando i dati lo dicono, senza sconti emotivi e senza giudizi soggettivi sui hard gate.
|
|
||||||
|
|
||||||
**Vincoli operativi adottati**:
|
|
||||||
|
|
||||||
| Dimensione | Valore |
|
|
||||||
|---|---|
|
|
||||||
| Obiettivo primario | Sistema produttivo che generi valore (trading reale, fase posteriore al PoC) |
|
|
||||||
| Dominio iniziale | Derivati crypto BTC/ETH |
|
|
||||||
| Tempo committed | Full-time, oltre 30h settimanali |
|
|
||||||
| Budget LLM cap | $2.200 hard, segmentato per fase |
|
|
||||||
| Capitale a rischio | $500-2.000 (solo nella Phase 3 forward-test mainnet) |
|
|
||||||
| Tempo calendario | 14-18 settimane atteso, 20 settimane hard cap |
|
|
||||||
| Setup tecnico di partenza | Cerbero_mcp operativo (multi-exchange, indicatori, audit, dual env) |
|
|
||||||
|
|
||||||
**Esito atteso**: alla fine delle tre fasi, una decisione binaria documentata con razionale numerico fra (a) avviare il sistema completo Filone A con confidence empirica forte, (b) iterare la Phase 2 su debolezze identificate, (c) pivotare su un dominio diverso (offerte commerciali Tielogic, code review), oppure (d) chiudere il progetto con learnings registrati.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Razionale della scelta strategica
|
|
||||||
|
|
||||||
### 2.1 Le tre opzioni del documento zero, oggi
|
|
||||||
|
|
||||||
Il documento zero presenta tre opzioni: A (Big Bet, sistema completo, 12-18 mesi), B (Smart Spike, PoC trading, 3-4 mesi), C (Research Dive, paper review più PoC minimo, 1-2 mesi). Alla luce dei vincoli operativi sopra elencati, la valutazione cambia rispetto al momento in cui il documento zero è stato scritto.
|
|
||||||
|
|
||||||
L'opzione A è esclusa dal vincolo budget. Le stime conservative del Filone A indicano costi LLM nell'ordine di $10.000-30.000 anche solo per la fase iniziale, contro un cap committed di $2.200. Non è una questione di tempo: il tempo full-time c'è. È che il rapporto fra costo del run e disponibilità non lo rende sostenibile senza una validazione empirica preliminare.
|
|
||||||
|
|
||||||
L'opzione C sotto-utilizza due asset materiali. Il primo è la disponibilità full-time, che rende il vincolo "non posso permettermi di costruire infrastruttura" non applicabile. Il secondo è Cerbero_mcp, già operativo: leggere paper per due settimane senza scrivere codice produttivo significherebbe lasciare ferma un'infrastruttura già pronta a essere wrappata come tool layer per agenti LLM.
|
|
||||||
|
|
||||||
Resta l'opzione B. Il documento zero la indicava come scelta preferita; questo documento la conferma e la struttura.
|
|
||||||
|
|
||||||
### 2.2 Perché B3 e non B1 o B2
|
|
||||||
|
|
||||||
Tre varianti di B sono state considerate.
|
|
||||||
|
|
||||||
La variante **B1 (Lean / single-shot)** comprime il PoC in un'unica run con popolazione ridotta a 20-30 agenti e tier C unico. Coerente con il budget tight, ma rischiosa: la dimensione della popolazione è il principale moltiplicatore di diversità nel sistema, e una popolazione undersized rischia di produrre un falso negativo. Si decreterebbe il sistema "non funzionante" quando in realtà non gli abbiamo dato il numero di tentativi necessari.
|
|
||||||
|
|
||||||
La variante **B2 (Canonical / come da documento)** segue fedelmente `poc_trading_swarm.md` con K=50, mix tier B/C, full set di ablation. Tecnicamente solida ma sfora il budget cap di un fattore 1.5-2x. Adottabile solo accettando di alzare il cap a $3-4K, decisione non giustificabile senza segnali empirici preliminari.
|
|
||||||
|
|
||||||
La variante **B3 (Incrementale)**, scelta, articola il PoC in tre fasi sequenziali con cap budget per fase e gate decisionali quantitativi fra una fase e la successiva. Phase 1 valida il loop tecnico con popolazione minima e tier economico. Phase 2 esegue il PoC canonico solo se Phase 1 passa. Phase 3 forward-testa con capitale reale solo se Phase 2 passa. Il budget totale resta entro $2.2K e il rischio di falso negativo viene ridotto dal fatto che la popolazione completa di Phase 2 non viene mai tagliata: viene messa al lavoro solo dopo che il loop è stato validato.
|
|
||||||
|
|
||||||
La struttura tripartita ha anche un beneficio non monetario: i deliverable di Phase 1 e Phase 2 valgono anche se le fasi successive falliscono. Il backtest engine, il GA harness, la Cerbero integration, la dashboard Streamlit, la pipeline DSR sono tutti riusabili in caso di pivot di dominio. Solo il capitale di Phase 3 è genuinamente "a rischio" come costo della validazione.
|
|
||||||
|
|
||||||
### 2.3 Coerenza con la filosofia del progetto
|
|
||||||
|
|
||||||
Il documento zero al §3.3 identifica come takeaway fondamentale di Renaissance la disciplina di spegnere strategie quando l'edge svanisce, senza decisioni emotive. Il design B3 applica questa disciplina al progetto stesso, prima ancora che al sistema. I gate sono numerici, le soglie sono fissate prima di vedere i dati, l'azione di stop è meccanica quando un hard gate fallisce. Non c'è spazio per "magari un'altra generazione" o "i risultati erano quasi ottimi": la decisione è già scritta nel design.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Vincoli di terminazione globali
|
|
||||||
|
|
||||||
Tre kill-switch globali sopra le singole fasi:
|
|
||||||
|
|
||||||
1. **Cap budget LLM globale**: $2.200 hard. Spesa effettiva monitorata da pagina Overview della dashboard, contatore aggiornato dopo ogni batch. Sforamento previsto entro la fase corrente → riformulazione scope, non incremento cap.
|
|
||||||
2. **Cap tempo calendario**: 14-18 settimane attese, **20 settimane hard cap** dalla settimana 1 della Phase 1 alla decisione formale post-Phase 3. Sforamento previsto del cap → decisione anticipata sulla base dei dati raccolti, non estensione del cap.
|
|
||||||
3. **Hard gate falliti**: per costruzione, un hard gate fallito chiude la fase corrente e non apre quella successiva. La decisione fra stop, pivot, o iterazione è formalizzata nel decision memo della fase chiusa, non nel passaggio automatico alla successiva.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Phase 1 — Lean Spike
|
|
||||||
|
|
||||||
**Obiettivo**: dimostrare che il loop tecnico funziona end-to-end. Non si misura ancora alpha: si misura se il sistema gira come progettato, se l'output LLM è formalizzabile, se la GA converge, se i costi sono prevedibili.
|
|
||||||
|
|
||||||
### 4.1 Scope IN
|
|
||||||
|
|
||||||
- Infrastruttura backtest minima: dataset 2 anni (2024-2026) di OHLCV 1h BTC/ETH, engine event-driven semplificato (no microstructure, no slippage modelling complesso, fees fissi a 5 basis points), walk-forward expanding 70/30.
|
|
||||||
- Wrapper Cerbero come tool layer per agenti: i tool MCP esistenti (`indicators`, `vol_cone`, `oi_weighted_skew`, indicatori options/microstructure/stats) tradotti in funzioni callable dagli agenti. Niente reimplementazione, solo wrapping.
|
|
||||||
- Protocollo S-expression fisso: 12-15 verbi disegnati manualmente come da `poc_trading_swarm.md` §2.2. Nessuna evoluzione del protocollo in questa fase.
|
|
||||||
- Hypothesis Swarm con K=20 agenti, tier C unico (Qwen 2.5 72B via OpenRouter). Mutazione e crossover prompt come da documento PoC. Nessuna speciation, nessun novelty bonus.
|
|
||||||
- Falsification e Adversarial layer hand-crafted, un agente fisso per ognuno, prompt manuali. Tier B (Sonnet 4.6) chiamato solo per i top-5 candidati a fine generazione, per contenere costi.
|
|
||||||
- Fitness function v0: DSR in-sample con drawdown penalty. No multi-livello, no out-of-sample ancora.
|
|
||||||
- GA loop: 8-12 generazioni, tournament selection, elitism k=2.
|
|
||||||
|
|
||||||
### 4.2 Scope OUT (esplicito)
|
|
||||||
|
|
||||||
- Multi-tier ablation comparativa.
|
|
||||||
- Out-of-sample DSR e hold-out finale.
|
|
||||||
- Random Forest baseline.
|
|
||||||
- Speciation, novelty, diversity metrics.
|
|
||||||
- Forward-test con capitale reale.
|
|
||||||
- Domini diversi da BTC/ETH.
|
|
||||||
|
|
||||||
### 4.3 Budget e tempo
|
|
||||||
|
|
||||||
- LLM: $500-700. Stima base: 20 agenti × ~8.000 token output medi × 10 generazioni × pricing Qwen ≈ $300, più 50% di overhead per Adversarial, Falsification e iterazioni di sviluppo, totale stimato $500-700.
|
|
||||||
- Tempo: 4-6 settimane full-time. Settimane 1-2 backtest engine e Cerbero wrapper, settimana 3 GA infrastructure e parser S-expression, settimane 4-5 tuning e run completo, settimana 6 analisi e decisione gate.
|
|
||||||
- Capitale a rischio: zero.
|
|
||||||
|
|
||||||
### 4.4 Gate go/no-go (tutti AND)
|
|
||||||
|
|
||||||
Cinque hard gate:
|
|
||||||
|
|
||||||
1. **Loop converge**: la fitness mediana della popolazione cresce per almeno tre generazioni consecutive prima di plateau.
|
|
||||||
2. **Output formalizzabile**: almeno l'80% delle proposte LLM passano il parser S-expression senza intervento manuale.
|
|
||||||
3. **Tail superiore esiste**: i top-5 genomi hanno DSR in-sample pari ad almeno 1.5x la mediana di popolazione, segnale che esiste struttura e non solo rumore.
|
|
||||||
4. **Diversità non collassa**: entropia della distribuzione di fitness in popolazione superiore a 0.5 a fine run, evita la convergenza monocoltura.
|
|
||||||
5. **Cost predictability**: spesa effettiva entro ±30% della stima preventivata.
|
|
||||||
|
|
||||||
Anche un solo hard gate fallito chiude la Phase 1. Decisione successiva (pivot, ridiscussione design, stop) presa nel decision memo, non automaticamente in Phase 2.
|
|
||||||
|
|
||||||
### 4.5 Deliverable Phase 1
|
|
||||||
|
|
||||||
- Codice testato (pytest): backtest engine, Cerbero wrapper, GA loop, protocol parser.
|
|
||||||
- Report tecnico (~5 pagine): loop convergence con grafici, ispezione qualitativa dei top-5 genomi, parser failure modes osservati, costi reali vs preventivo, diversity metrics.
|
|
||||||
- Decision memo: vai/non-vai a Phase 2 con eventuali aggiustamenti di scope.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Phase 2 — Canonical PoC
|
|
||||||
|
|
||||||
**Obiettivo**: rispondere ai cinque test del PoC originale (`poc_trading_swarm.md` §1) con popolazione e infrastruttura adeguate. Solo questa fase produce una vera misura dell'edge potenziale del sistema.
|
|
||||||
|
|
||||||
### 5.1 Scope IN (in aggiunta a Phase 1)
|
|
||||||
|
|
||||||
- Hypothesis Swarm K=40, scaling della popolazione a un livello canonico ridotto (K=50 documento → K=40 per disciplina budget).
|
|
||||||
- Tier mix B/C: circa 70% Qwen/DeepSeek (tier C), 30% Sonnet 4.6 (tier B). L'ablation comparativa misura il valore aggiunto del tier B.
|
|
||||||
- Speciation di base: clustering dei genomi per cosine similarity dei prompt più cognitive_style. Si mantengono almeno 3 specie attive, ognuna con quote di tournament protette.
|
|
||||||
- Novelty bonus: fitness composta α·DSR_OOS + β·novelty_score, dove la novelty è calcolata come distanza behavioural dei segnali rispetto a un archivio di elite.
|
|
||||||
- Walk-forward expanding più hold-out finale: training Q1-2024 a Q4-2025 in walk-forward, hold-out intoccabile Q1-Q2 2026.
|
|
||||||
- Random Forest baseline: feature engineering classico (returns multi-orizzonte, RSI/MACD/ATR, vol cone, funding rate, OI changes), classificazione long/flat/short su orizzonti 1d e 4h, valutato sulla stessa hold-out.
|
|
||||||
- Adversarial layer hand-crafted potenziato: cinque prompt distinti (data snooping, lookahead, regime fragility, crowding, transaction cost erosion) eseguiti sui top-10 candidati prima della valutazione OOS.
|
|
||||||
- Falsification con Deflated Sharpe Ratio (Bailey & López de Prado), correzione Bonferroni sul numero totale di ipotesi testate.
|
|
||||||
- Fitness multi-livello: per-agent (contributo DSR), per-team (DSR portfolio), diversity penalty per ridurre collusione.
|
|
||||||
|
|
||||||
### 5.2 Scope OUT
|
|
||||||
|
|
||||||
- Co-evolution del protocollo (Filone A).
|
|
||||||
- Forward-test con capitale reale (Phase 3).
|
|
||||||
- Speciation NEAT-style completa.
|
|
||||||
- Idiom emergence.
|
|
||||||
- Domini diversi da trading.
|
|
||||||
|
|
||||||
### 5.3 Budget e tempo
|
|
||||||
|
|
||||||
- LLM: $700-1.100. Dettaglio stimato: tier C ~$500, tier B ~$400, overhead per ablation iterativa ~$200. Range ampio per consentire più cicli di ablation se i primi risultati lo richiedono.
|
|
||||||
- Tempo: 4-6 settimane full-time. Settimana 1 porting K=40, speciation, novelty. Settimane 2-3 ablation runs (tier C only, tier B only, mix; con e senza speciation). Settimana 4 hold-out evaluation, RF baseline, Adversarial sweep. Settimane 5-6 analisi statistica, report, decisione gate.
|
|
||||||
- Capitale a rischio: zero.
|
|
||||||
|
|
||||||
### 5.4 Gate go/no-go
|
|
||||||
|
|
||||||
**Hard gate (tutti AND, altrimenti stop)**:
|
|
||||||
|
|
||||||
1. **Significatività statistica**: top genoma su hold-out con DSR > 1.0 e p-value < 0.05 dopo correzione Bonferroni.
|
|
||||||
2. **Sopravvivenza regime change**: DSR hold-out almeno 0.5x del DSR walk-forward — limite contro overfitting catastrofico.
|
|
||||||
3. **Batte baseline**: top-3 genomi con Sharpe OOS superiore al Sharpe RF baseline OOS, effect size non trascurabile (Cohen's d > 0.3 sul rolling Sharpe).
|
|
||||||
|
|
||||||
**Soft gate (informano, non killano)**:
|
|
||||||
|
|
||||||
4. **Diversità**: almeno 3 specie distinte sopravvivono a fine run, top-3 genomi non identici per signal correlation (ρ < 0.7).
|
|
||||||
5. **Tier B aggiunge valore**: l'ablation mostra Δ Sharpe OOS misurabile per tier mix vs tier C only. In caso negativo, Phase 3 può girare tier C only e il decision memo ne prende nota.
|
|
||||||
|
|
||||||
Hard gate passati → Phase 3. Hard gate falliti → stop o pivot. Soft gate falliti → Phase 3 con scope ridotto e annotazioni nel report.
|
|
||||||
|
|
||||||
### 5.5 Deliverable Phase 2
|
|
||||||
|
|
||||||
- Codice testato: speciation, novelty, ablation harness, RF baseline, DSR pipeline, Adversarial battery.
|
|
||||||
- Report scientifico (~15-20 pagine): metodologia, risultati per ogni gate, ablation table, top-5 strategie ispezionate qualitativamente, threats to validity.
|
|
||||||
- Decision memo: vai/non-vai a Phase 3, scope di Phase 3 (capitale, exchange, leva, durata) calibrato sui risultati.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Phase 3 — Forward-test mainnet
|
|
||||||
|
|
||||||
**Obiettivo**: vedere se l'edge sopravvive in produzione. Anche il backtest più rigoroso ha bias inevitabili (look-ahead microscopico, slippage idealizzato, assenza di information leakage da fonti che non esistevano in periodo storico). Solo il forward-test live risponde alla domanda finale.
|
|
||||||
|
|
||||||
### 6.1 Scope IN
|
|
||||||
|
|
||||||
- Selezione strategie: top-3 genomi out-of-sample dalla Phase 2, dopo passaggio completo dell'Adversarial battery. Niente cherry-picking ex-post post-Phase 2.
|
|
||||||
- Capitale: $500-2.000 totali, distribuiti sui tre genomi con allocazione equal weight oppure risk-parity sulla volatilità OOS attesa, scelta motivata nel decision memo Phase 2.
|
|
||||||
- Exchange: scelta condizionata alle strategie selezionate. Default raccomandati Bybit (perp, fees competitive, liquidità BTC/ETH adeguata) oppure Hyperliquid (no KYC, transparent funding). Cerbero supporta entrambi nativamente.
|
|
||||||
- Leva: massimo 2x in forward-test. Anche se lo Sharpe OOS suggerisse di più, in fase di validazione la leva resta bassa per non confondere edge della strategia con leva.
|
|
||||||
- Durata: 6-8 settimane continue. Razionale: in crypto questa finestra copre tipicamente uno o due micro-regime change, sufficienti a stressare il modello senza catastrofi statistiche da campione troppo piccolo.
|
|
||||||
- Monitoring: dashboard giornaliera (sezione Live Monitor) con Sharpe live realized vs Sharpe OOS atteso, drawdown realtime, violation count (segnali generati ma non eseguiti per qualunque ragione), audit log Cerbero per ogni order.
|
|
||||||
- Decision triggers automatici: kill-switch se il drawdown live supera 1.5x il peggiore osservato in walk-forward; pause se Sharpe rolling 14d resta negativo per 14 giorni consecutivi.
|
|
||||||
- Adversarial post-mortem settimanale: l'agente Adversarial gira nuovamente sul signal log della settimana per identificare degradazione dell'edge (regime drift detection).
|
|
||||||
|
|
||||||
### 6.2 Scope OUT
|
|
||||||
|
|
||||||
- Capital scaling oltre $2.000 in Phase 3. Se i risultati promettono, la decisione di scaling è esplicitamente fuori dal PoC e viene presa dopo il decision memo finale.
|
|
||||||
- Multi-strategy portfolio rebalancing dinamico. Allocazione statica sui tre genomi.
|
|
||||||
- Hedging cross-exchange. Confonderebbe la lettura dell'edge della strategia.
|
|
||||||
- Aggiunta di nuovi genomi in corsa. I tre genomi sono fissati a inizio fase.
|
|
||||||
|
|
||||||
### 6.3 Budget e tempo
|
|
||||||
|
|
||||||
- LLM: $200-400. La popolazione GA non gira più, gli agenti sono richiamati solo per Adversarial post-mortem settimanale e per occasionali refresh quando i decision triggers scattano.
|
|
||||||
- Capitale a rischio: $500-2.000. Trattato come **costo della validazione**, non come investimento. Se il capitale va a zero, il dato che ne ricaviamo vale comunque.
|
|
||||||
- Tempo: 6-8 settimane di calendario, monitoring operativo circa 5h/settimana — non full-time. Le settimane libere sono allocate a documentazione finale, lavoro su Tielogic e altri progetti, prima esplorazione Filone A in caso di decisione GO.
|
|
||||||
- Costo infra extra: circa $10-30/mese VPS per dashboard più monitoring, in larga parte già coperto dal setup Hostinger esistente.
|
|
||||||
|
|
||||||
### 6.4 Gate decisionale finale del PoC
|
|
||||||
|
|
||||||
**Hard gate per "GO sistema completo / Filone A"**:
|
|
||||||
|
|
||||||
1. **Edge sopravvive live**: Sharpe live realized almeno 0.5x dello Sharpe OOS atteso, su finestra di almeno 4 settimane.
|
|
||||||
2. **No catastrophic failure**: max drawdown live al massimo 1.5x del peggior drawdown walk-forward.
|
|
||||||
3. **Reproducibility**: almeno 2 dei 3 genomi performano in linea con previsione — la fortuna non si concentra su uno solo.
|
|
||||||
|
|
||||||
**Soft gate (qualitativi, informano la decisione)**:
|
|
||||||
|
|
||||||
4. **Audit Adversarial settimanali**: nessuna scoperta critica come lookahead nascosto emerso solo live, oppure data leakage da provider.
|
|
||||||
5. **Cost economy**: edge dopo costi reali (slippage effettivo, fees, funding) resta positivo.
|
|
||||||
|
|
||||||
**Esiti possibili**:
|
|
||||||
|
|
||||||
- Hard gate e soft gate tutti passati → GO Filone A con confidence empirica forte. Si apre la ridiscussione del budget e della roadmap del sistema completo, fuori dal perimetro di questo documento.
|
|
||||||
- Hard gate passati, soft gate falliti → iterazione Phase 2 mirata sulle debolezze identificate, no Filone A immediato.
|
|
||||||
- Hard gate falliti, ma senza catastrofi → l'idea regge concettualmente ma non scala live retail. Decision memo con due opzioni: pivot dominio (offerte Tielogic, code review) oppure chiusura del progetto.
|
|
||||||
- Hard gate falliti più drawdown catastrofico → l'idea non regge live. Stop del progetto. Documento di chiusura con learnings registrati per progetti futuri.
|
|
||||||
|
|
||||||
### 6.5 Deliverable Phase 3 e finali
|
|
||||||
|
|
||||||
- Report finale del PoC (~20-30 pagine): metodologia completa, risultati Phase 1+2+3, comparison Sharpe in-sample / OOS / live, ispezione qualitativa delle strategie, learnings, threats to validity confermati o respinti.
|
|
||||||
- Decision memo strategico: GO Filone A / iterate Phase 2 / pivot dominio / stop, con razionale quantitativo ancorato ai gate.
|
|
||||||
- Codebase pubblicabile (anche se repo privato): backtest, GA, Cerbero integration, speciation, DSR pipeline, RF baseline, monitoring dashboard, tutto documentato.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. GUI Streamlit incrementale
|
|
||||||
|
|
||||||
Una dashboard è essenziale per ispezionare cosa fa il sistema, decidere i gate in modo informato, e produrre i grafici che entreranno nei report.
|
|
||||||
|
|
||||||
### 7.1 Architettura
|
|
||||||
|
|
||||||
- Tech stack: Streamlit single-app multi-page, dati letti da SQLite locale (`runs.db`) e Parquet per series numerici pesanti.
|
|
||||||
- SQLite per stato: genomi, generazioni, fitness, ablation results, adversarial findings, trade log. Schema relazionale stabile, query veloci, nessun DB server da gestire.
|
|
||||||
- Parquet per series: equity curves, signal time series, OHLCV. File-based, columnar, leggero.
|
|
||||||
- Auto-refresh ogni 10 secondi nella sola pagina Live Monitor (Phase 3). Sufficiente per uno scope a decisioni minute-level, non HFT.
|
|
||||||
- Single app, multipage: tutto sotto `dashboard/streamlit_app.py` più `pages/`. Deploy locale con `streamlit run`, niente VPS frontend.
|
|
||||||
|
|
||||||
### 7.2 Pagine costruite incrementalmente
|
|
||||||
|
|
||||||
**Phase 1 (3-4 giorni di lavoro)**:
|
|
||||||
|
|
||||||
- *Overview*: ultima run, generazione corrente, stato (running/completed/failed), spesa LLM cumulata vs cap.
|
|
||||||
- *GA Convergence*: line plot fitness mediana / max / 90° percentile per generazione, distribuzione fitness ultima generazione (histogram), counter chiamate LLM e costo.
|
|
||||||
- *Genomes (basic)*: tabella top-10 genomi correnti con DSR, cognitive_style, temperature, lookback. Click su riga apre side panel con system_prompt completo, feature_access, lineage parent_id.
|
|
||||||
|
|
||||||
**Phase 2 (9-12 giorni distribuiti)**:
|
|
||||||
|
|
||||||
- *Genomes (avanzato)*: lineage tree interattivo (parent → children su 15 generazioni), speciation cluster view (UMAP/t-SNE su prompt embedding più parametri, colori per specie), filtri per specie / tier / cognitive_style.
|
|
||||||
- *Performance*: equity curve in-sample, walk-forward, OOS, hold-out per ogni genoma. Sharpe, DSR, drawdown. Trade distribution per regime di volatilità, asset, orario. Per-strategy e portfolio view.
|
|
||||||
- *Ablation*: confronto runs (tier C only, tier B only, mix) side-by-side. Δ Sharpe OOS, costo per percentile fitness, breakeven analysis.
|
|
||||||
- *Adversarial*: per ogni top-10 genoma, le cinque critiche (data snooping, lookahead, regime fragility, crowding, transaction cost). Click espande prompt completo, risposta LLM, decisione pass/fail con rationale.
|
|
||||||
- *RF Baseline*: Sharpe RF baseline OOS, feature importance, comparison vs top-3 swarm, Cohen's d effect size.
|
|
||||||
|
|
||||||
**Phase 3 (4-5 giorni)**:
|
|
||||||
|
|
||||||
- *Live Monitor*: P&L realtime per strategia e portfolio, equity curve da inizio Phase 3, drawdown rolling. Auto-refresh 10s.
|
|
||||||
- *Live vs OOS*: Sharpe live realized vs Sharpe OOS atteso (con confidence interval), gauge "edge sopravvive?", cumulative deviation tracker.
|
|
||||||
- *Triggers state*: stato kill-switch per strategia, distance from threshold, history pause/resume, audit log decisioni recenti.
|
|
||||||
- *Adversarial weekly*: report settimanale di regime drift detection, diff vs settimana precedente.
|
|
||||||
|
|
||||||
### 7.3 Costi GUI
|
|
||||||
|
|
||||||
- Effort totale: 16-21 giorni netti, distribuiti come da fasi sopra.
|
|
||||||
- LLM: zero (codice e visualizzazione Python locale).
|
|
||||||
- Infra: zero (esecuzione locale, SQLite locale, Parquet locale).
|
|
||||||
|
|
||||||
### 7.4 Trade-off accettati
|
|
||||||
|
|
||||||
- Refresh non realtime sub-secondo: accettabile per scope decisionale minute/hour.
|
|
||||||
- Niente login né multi-utente: dashboard personale solo locale.
|
|
||||||
- Niente alert push esterni in default: alert appaiono in dashboard. Per Phase 3 si può aggiungere webhook Telegram/email se necessario, mezza giornata extra di lavoro.
|
|
||||||
- Streamlit re-runs full-page on interaction: gestibile con `@st.cache_data` su query SQLite e dataset PoC di dimensioni contenute.
|
|
||||||
|
|
||||||
### 7.5 Deliverable GUI
|
|
||||||
|
|
||||||
- Codice `dashboard/` testato (smoke test e data layer test).
|
|
||||||
- Schema SQLite versionato con migrazioni semplici (Alembic light o script SQL).
|
|
||||||
- README con istruzioni `streamlit run` e descrizione di ogni pagina.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Hardware e infrastruttura
|
|
||||||
|
|
||||||
Principio: tutto locale più Cerbero come unico servizio remoto. Nessuna GPU, nessun cloud compute, nessun costo infra ricorrente significativo.
|
|
||||||
|
|
||||||
### 8.1 Compute
|
|
||||||
|
|
||||||
- Backtest e GA loop: PC locale Linux. Tutto CPU-bound, parallelizzabile su core (joblib o multiprocessing). Dataset 2 anni OHLCV 1h BTC+ETH circa 30-50 MB. Anche granularità 1m sarebbe sotto i 2 GB, gestibile.
|
|
||||||
- LLM: tutte chiamate via API esterne (OpenRouter per tier C, Anthropic per tier B). Nessun model locale, nessuna GPU.
|
|
||||||
- Streamlit dashboard: locale (`streamlit run` su `localhost:8501`).
|
|
||||||
|
|
||||||
### 8.2 Cerbero_mcp
|
|
||||||
|
|
||||||
Già configurato e operativo. Modalità d'uso durante PoC:
|
|
||||||
|
|
||||||
- Locale via Docker compose durante development e Phase 1-2 (testnet only). Riduce latenza, niente costi VPS, debug più rapido.
|
|
||||||
- VPS Hostinger durante Phase 3 forward-test (mainnet). Già setup `/opt/cerbero-mcp` con `deploy-vps.sh` e branch V2.0.0.
|
|
||||||
- Token bearer: `TESTNET_TOKEN` per Phase 1-2 backtest replay, `MAINNET_TOKEN` solo per Phase 3.
|
|
||||||
- Bot tag dedicato per il PoC (`X-Bot-Tag: swarm-poc-<phase>`). L'audit log Cerbero traccia ogni call separatamente per fase, utile per ricostruzioni post-mortem.
|
|
||||||
|
|
||||||
### 8.3 Storage
|
|
||||||
|
|
||||||
- `runs.db` SQLite per stato GA, genomi, generazioni, fitness, adversarial, trade log. Backup giornaliero su disco esterno o cloud personale.
|
|
||||||
- `series/` Parquet per equity curves, signal time series, OHLCV cache. Versionato fuori da git (Git LFS o cartella esterna trackata in `.gitignore`).
|
|
||||||
- Audit log Cerbero: già JSONL con rotazione 30 giorni (`AUDIT_LOG_BACKUP_DAYS=30`). Per Phase 3 aumentare a 90 giorni per coprire intera fase più post-mortem.
|
|
||||||
|
|
||||||
### 8.4 Networking
|
|
||||||
|
|
||||||
- LLM API via OpenRouter (tier C) e Anthropic (tier B). Nessun setup speciale.
|
|
||||||
- Cerbero locale: porta 9000 default, nessuna esposizione pubblica.
|
|
||||||
- Cerbero VPS: già protetto da Traefik più bearer più allowlist IP. Nessun lavoro extra.
|
|
||||||
|
|
||||||
### 8.5 Costi infra ricorrenti
|
|
||||||
|
|
||||||
- VPS Hostinger: già pagato per altri progetti, costo marginale zero.
|
|
||||||
- Storage backup: trascurabile.
|
|
||||||
- Domini e TLS: già coperti (cerbero-mcp.tielogic.xyz).
|
|
||||||
|
|
||||||
### 8.6 Decisioni hardware non bloccanti
|
|
||||||
|
|
||||||
- Se la Phase 2 ablation richiedesse parallelizzazione massiva (ad esempio cento backtest concorrenti), valutare spot instance AWS o Hetzner. Probabilmente non necessario, le strategie a granularità 1h sono veloci da backtestare anche su CPU desktop.
|
|
||||||
- Backup off-site di `runs.db`: decisione di lifecycle, non bloccante per Phase 1.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Cadenza review e disciplina autoriale
|
|
||||||
|
|
||||||
Regola personale dell'autore: mai self-approve, separare author pass da review pass. Applicata sistematicamente ai gate del PoC.
|
|
||||||
|
|
||||||
### 9.1 Cadenza working
|
|
||||||
|
|
||||||
- Daily: lavoro full-time. Self-review informale a fine giornata, una riga nel commit message su cosa è andato e cosa no.
|
|
||||||
- Settimanale (venerdì): review formale con dump strutturato che include fitness convergence plot, top-5 genomi della settimana, spesa LLM accumulata vs cap di fase, eventuali findings Adversarial significativi, aggiornamento di `progress.md`.
|
|
||||||
- Bi-settimanale: snapshot completo più decision check sul fatto se siamo ancora on-track per il gate. Se due bi-weekly consecutivi mostrano off-track materiale, decisione anticipata di pivot o iterate, non attesa fino a fine fase.
|
|
||||||
|
|
||||||
### 9.2 Gate review (decisione formale fine fase)
|
|
||||||
|
|
||||||
Per ognuno dei tre gate (fine Phase 1, fine Phase 2, fine Phase 3): author pass e review pass separati.
|
|
||||||
|
|
||||||
- **Author pass**: l'autore scrive il decision memo con tutti i numeri, gate per gate, conclusione raccomandata.
|
|
||||||
- **Review pass**: secondo passaggio con approccio adversarial. Tre opzioni equivalenti:
|
|
||||||
- Subagent Claude con prompt esplicitamente "red team" che riceve memo più dati grezzi e produce critica strutturata (cherry-picking, debolezze statistiche, omissioni).
|
|
||||||
- Collega umano disponibile, se esiste un contesto Tielogic adatto.
|
|
||||||
- Rilettura dopo 48 ore con timer, fresh eyes pass.
|
|
||||||
- **Sintesi**: solo dopo il review pass la decisione viene formalizzata e committata.
|
|
||||||
|
|
||||||
### 9.3 Decision triggers oggettivi
|
|
||||||
|
|
||||||
I gate hard di ogni fase sono numerici (DSR, p-value, drawdown ratio). La decisione GO/STOP è meccanica sui hard gate:
|
|
||||||
|
|
||||||
- Hard gate fallito → STOP automatico, non in discussione.
|
|
||||||
- Hard gate passato → si valuta se i soft gate danno motivo di iterazione invece di procedere.
|
|
||||||
|
|
||||||
Questa è la disciplina Renaissance applicata al progetto: niente "magari un'altra generazione" se il numero non lo dice.
|
|
||||||
|
|
||||||
### 9.4 Documentazione del processo
|
|
||||||
|
|
||||||
- `docs/runs/YYYY-MM-DD-phase{1,2,3}-run-N.md` per ogni run completato: configurazione, risultati, anomalie, learning.
|
|
||||||
- `docs/decisions/YYYY-MM-DD-gate-phase{1,2,3}.md` per ogni decisione gate: author pass, review pass, decisione finale, razionale.
|
|
||||||
- Questo documento (`docs/superpowers/specs/2026-05-09-decisione-strategica-design.md`) come north star strategico, aggiornato se cambiano vincoli o decisioni macro.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. Catena di ragionamento (tracciabilità)
|
|
||||||
|
|
||||||
Per riferimento futuro, la sequenza logica che ha portato al design B3:
|
|
||||||
|
|
||||||
1. Obiettivo dichiarato sistema produttivo che generi valore → esclude C (research dive senza output produttivo).
|
|
||||||
2. Dominio iniziale trading crypto → allinea il PoC al design già scritto in `poc_trading_swarm.md`.
|
|
||||||
3. Tempo full-time disponibile → scioglie il vincolo "non posso costruire infrastruttura", apre spazio per fasi sequenziali.
|
|
||||||
4. Budget LLM tight ($1-2K) → esclude A (Filone completo) e impone disciplina su B.
|
|
||||||
5. Setup Cerbero_mcp esistente → riduce settimane di plumbing, gli agenti chiamano tool MCP nativi.
|
|
||||||
6. Forward-test mainnet con capitale piccolo come parte del successo → richiede una Phase 3 dedicata, distinta dalla validazione statistica.
|
|
||||||
7. Disciplina "spegnere ciò che non funziona" → struttura tripartita con kill-switch numerici.
|
|
||||||
8. Mai self-approve → separazione author pass / review pass nei gate.
|
|
||||||
9. Necessità di ispezionare cosa fa il sistema → GUI Streamlit come componente orizzontale, non opzionale.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 11. Decisioni risolte e decisioni ancora aperte
|
|
||||||
|
|
||||||
### 11.1 Risolte da questo documento
|
|
||||||
|
|
||||||
- Opzione strategica: B3.
|
|
||||||
- Dominio iniziale: trading derivati crypto BTC/ETH.
|
|
||||||
- Numero di fasi: tre, con gate go/no-go fra una e l'altra.
|
|
||||||
- Budget cap globale: $2.200 LLM più $500-2.000 capitale a rischio Phase 3.
|
|
||||||
- Cap calendario: 18 settimane.
|
|
||||||
- Tier mix: solo C in Phase 1, mix B/C in Phase 2-3.
|
|
||||||
- Tech stack GUI: Streamlit più SQLite più Parquet.
|
|
||||||
- Infrastruttura: locale più Cerbero_mcp esistente.
|
|
||||||
- Cadenza review: settimanale, bi-settimanale per check, gate con author/review pass separati.
|
|
||||||
|
|
||||||
### 11.2 Aperte (non bloccanti per Phase 1)
|
|
||||||
|
|
||||||
- Allocazione capitale Phase 3 (equal weight vs risk-parity): decisione formalizzata nel decision memo Phase 2 sulla base dei risultati OOS.
|
|
||||||
- Exchange Phase 3 (Bybit vs Hyperliquid): scelta dipendente dalle strategie selezionate, decisa nel decision memo Phase 2.
|
|
||||||
- Approccio review pass (subagent vs umano vs fresh eyes): decisione tattica per gate, nessun lock-in.
|
|
||||||
- Webhook alert Telegram/email per Phase 3: opzionale, decidibile a inizio Phase 3.
|
|
||||||
|
|
||||||
### 11.3 Esplicitamente fuori scope
|
|
||||||
|
|
||||||
- Filone A (sistema completo) come fase corrente. Decisione su A presa solo dopo decision memo finale Phase 3.
|
|
||||||
- Filone C (applicazioni non-trading: offerte Tielogic, code review, doc Swagger). Possibile pivot in caso di hard gate falliti, non azione preventiva.
|
|
||||||
- Co-evolution del protocollo. Nessuna delle tre fasi PoC la include.
|
|
||||||
- Capital scaling oltre $2.000 in Phase 3. Decisione di scaling appartiene a una fase successiva al PoC.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 12. Prossimi passi
|
|
||||||
|
|
||||||
Esecuzione di Phase 1.
|
|
||||||
|
|
||||||
Il piano implementativo dettagliato di Phase 1 (settimana per settimana, task atomici, dipendenze, verifiche) sarà oggetto del documento successivo, da costruire con l'invocazione dello skill `writing-plans` su questo design.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
*Documento approvato il 9 maggio 2026. Versione 1.0. Aggiornare in caso di modifica dei vincoli operativi o di esiti di gate che richiedano revisione strategica complessiva.*
|
|
||||||
@@ -1,183 +0,0 @@
|
|||||||
# Feature temporali nella grammatica Hypothesis — Design
|
|
||||||
|
|
||||||
**Data**: 11 maggio 2026
|
|
||||||
**Status**: design approvato dall'operatore, pronto per writing-plans
|
|
||||||
**Scope target**: Phase 2
|
|
||||||
**Riferimenti**: `docs/decisions/2026-05-11-phase1-5-nemotron-run.md` (memo che ha originato la discussione)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Motivazione
|
|
||||||
|
|
||||||
Le strategie LLM-generate da Phase 1 operano in modo time-blind: la grammatica espone solo OHLCV (`open`, `high`, `low`, `close`, `volume`) e indicatori tecnici (`sma`, `rsi`, `atr`, `macd`, `realized_vol`) calcolati sopra. Non esiste alcuna feature che permetta al genoma di condizionare il comportamento sull'orario o sul giorno della settimana.
|
|
||||||
|
|
||||||
Questo è un limite strutturale rispetto a BTC-PERPETUAL su Cerbero, dove esistono effetti temporali sistematici:
|
|
||||||
|
|
||||||
- apertura USA (14:30 UTC) e Europa (08:00 UTC) generano volatilità sistematica;
|
|
||||||
- apertura/chiusura settimanale crypto (Sabato/Domenica vs. resto della settimana) ha liquidità diversa e basis funding diverso;
|
|
||||||
- la sessione asiatica overnight presenta pattern di trend reversal noti.
|
|
||||||
|
|
||||||
Il design seguente aggiunge alla grammatica quattro feature temporali — `hour`, `dow`, `is_weekend`, `minute_of_hour` — universalmente accessibili a ogni genoma, lasciando inalterati i meccanismi di mutation/crossover esistenti.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Decisioni di design
|
|
||||||
|
|
||||||
Le seguenti scelte sono state ratificate in fase di brainstorming.
|
|
||||||
|
|
||||||
**Quattro feature, non una.** `hour` da sola coprirebbe l'80% dei casi, ma `dow` cattura un asse ortogonale (weekend effect) e `is_weekend` è una scorciatoia espressiva utile al LLM. `minute_of_hour` è incluso per disponibilità futura (timeframe 5m/15m in Phase 2+), inerte sui dati 1h attuali.
|
|
||||||
|
|
||||||
**Accesso universale, non soggetto a `feature_access`.** Le feature temporali sono sempre disponibili a ogni genoma, indipendentemente dal subset OHLCV randomizzato in `ga/initial.py` e mutato da `mutate_feature_access`. Motivo: vogliamo che ogni genoma possa testarle; passarle attraverso `FEATURE_POOL` rischia di lasciarle inutilizzate in metà della popolazione e vanificare l'esperimento. Il prompt indica esplicitamente che sono "sempre accessibili", separate dalla sezione `{feature_access}` del template.
|
|
||||||
|
|
||||||
**Riuso di `FeatureNode`, niente nuovo tipo AST.** Le feature temporali entrano nella stessa whitelist `KNOWN_FEATURES` di OHLCV e usano la stessa shape JSON `{"kind": "feature", "name": "..."}`. Il dispatcher in `compiler.py` discrimina per nome. Alternativa scartata: introdurre `TimeFeatureNode` separato. Avrebbe dato type-safety formale ma richiesto modifiche a parser, validator, JSON shape, prompt — costo eccessivo per beneficio puramente strutturale, dato che semanticamente "ora del giorno" e "prezzo close" sono entrambi attributi della riga.
|
|
||||||
|
|
||||||
**Few-shot examples nel prompt.** L'istruzione minimale (solo nomi) lascia troppo spazio a interpretazioni errate (es. `dow=7` per domenica all'italiana, `hour` in fuso locale invece che UTC). Due esempi concreti — un gating intraday `gt hour 14 AND lt hour 22`, un gating settimanale `eq is_weekend 1` — fissano la semantica al costo di ~200 token addizionali per call.
|
|
||||||
|
|
||||||
**Out-of-range non è errore di validazione.** Il LLM potrebbe emettere `gt hour 25` o `eq dow 7`. Il validator non li intercetta: tecnicamente sono `LiteralNode(value=...)` numerici legali. La condizione sarà semplicemente sempre falsa e l'Adversarial layer (`flat_too_long`, `no_trades`) sanzionerà i genomi che ne sono dipendenti. Aggiungere un check range esplicito sarebbe over-engineering per un caso che il sistema già gestisce.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Architettura — modifiche file-by-file
|
|
||||||
|
|
||||||
Cinque file toccati. Nessun nuovo modulo.
|
|
||||||
|
|
||||||
### `src/multi_swarm/protocol/grammar.py`
|
|
||||||
|
|
||||||
Estendere `KNOWN_FEATURES` da 5 a 9 nomi:
|
|
||||||
|
|
||||||
```python
|
|
||||||
KNOWN_FEATURES: frozenset[str] = frozenset(
|
|
||||||
{"open", "high", "low", "close", "volume",
|
|
||||||
"hour", "dow", "is_weekend", "minute_of_hour"}
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
Nessun'altra modifica al file. Il validator legge da qui automaticamente.
|
|
||||||
|
|
||||||
### `src/multi_swarm/protocol/compiler.py`
|
|
||||||
|
|
||||||
Aggiungere un dizionario di derivazioni temporali ed estendere il dispatcher di `FeatureNode` con un branch prioritario:
|
|
||||||
|
|
||||||
```python
|
|
||||||
_TIME_FEATURE_FNS: dict[str, Callable[[pd.DatetimeIndex], pd.Series]] = {
|
|
||||||
"hour": lambda idx: pd.Series(idx.hour, index=idx, dtype="int64"),
|
|
||||||
"dow": lambda idx: pd.Series(idx.dayofweek, index=idx, dtype="int64"),
|
|
||||||
"is_weekend": lambda idx: pd.Series((idx.dayofweek >= 5).astype("int64"), index=idx),
|
|
||||||
"minute_of_hour": lambda idx: pd.Series(idx.minute, index=idx, dtype="int64"),
|
|
||||||
}
|
|
||||||
|
|
||||||
# nel branch FeatureNode di _eval_node:
|
|
||||||
if isinstance(node, FeatureNode):
|
|
||||||
if node.name in _TIME_FEATURE_FNS:
|
|
||||||
return _TIME_FEATURE_FNS[node.name](df.index)
|
|
||||||
return df[node.name]
|
|
||||||
```
|
|
||||||
|
|
||||||
Il branch OHLCV preesistente (`return df[node.name]`) resta invariato come fallback per i nomi non temporali. Si assume `df.index` di tipo `DatetimeIndex` UTC, già garantito da `CerberoOHLCVLoader`.
|
|
||||||
|
|
||||||
### `src/multi_swarm/agents/hypothesis.py`
|
|
||||||
|
|
||||||
Aggiungere nel prompt template, dopo la sezione "Leaf - feature OHLCV" (intorno a riga 84), una sezione "Leaf - feature TEMPORALI" con i quattro nomi, i loro range, e due esempi few-shot completi (gating sessione US, gating weekend). Mantenere la sezione separata da `{feature_access}` e dichiarare esplicitamente che le feature temporali sono "sempre accessibili". Contenuto preciso definito nella sezione 5 di questo spec.
|
|
||||||
|
|
||||||
### `tests/protocol/test_compiler.py`
|
|
||||||
|
|
||||||
Cinque test nuovi:
|
|
||||||
|
|
||||||
1. `test_compile_hour_feature_returns_index_hour` — DataFrame 24-bar con index orario, `FeatureNode("hour")` restituisce serie `[0,1,...,23]`.
|
|
||||||
2. `test_compile_dow_feature_lunedi_is_zero` — verifica convenzione pandas (lunedì → 0, domenica → 6).
|
|
||||||
3. `test_compile_is_weekend_returns_zero_one` — sabato e domenica → 1, altri → 0.
|
|
||||||
4. `test_compile_minute_of_hour_zero_on_1h_timeframe` — su index 1h tutti gli output sono 0 (test di regressione del comportamento atteso).
|
|
||||||
5. `test_rule_with_temporal_gating_compiles_and_executes` — integrazione: regola `entry-long if hour > 14 AND close > sma(20)`, verifica che `Side.LONG` appaia solo nelle bar con `hour > 14`.
|
|
||||||
|
|
||||||
### `tests/protocol/test_validator.py`
|
|
||||||
|
|
||||||
Due test nuovi:
|
|
||||||
|
|
||||||
1. `test_validator_accepts_temporal_features` — i quattro nuovi nomi non sollevano `ValidationError`.
|
|
||||||
2. `test_validator_rejects_temporal_typo` — `FeatureNode("weekday")` solleva `ValidationError`.
|
|
||||||
|
|
||||||
Test esistenti non devono cambiare. L'aggiunta è puramente additiva.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Contratto delle feature
|
|
||||||
|
|
||||||
| Feature | Tipo | Range | Derivazione pandas |
|
|
||||||
|---------|------|-------|---------------------|
|
|
||||||
| `hour` | int64 | 0–23 | `df.index.hour` |
|
|
||||||
| `dow` | int64 | 0–6 (lun=0) | `df.index.dayofweek` |
|
|
||||||
| `is_weekend` | int64 | 0 o 1 | `(df.index.dayofweek >= 5).astype(int)` |
|
|
||||||
| `minute_of_hour` | int64 | 0–59 | `df.index.minute` |
|
|
||||||
|
|
||||||
L'indice del DataFrame è UTC tz-aware per costruzione (`CerberoOHLCVLoader`). I valori temporali sono quindi in UTC, non in fuso locale italiano. Questa scelta è coerente con la convenzione di prezzi e timestamp del progetto e con la natura globale del mercato crypto.
|
|
||||||
|
|
||||||
I confronti tipici emessi dal LLM saranno della forma `{"op": "gt", "args": [{"kind": "feature", "name": "hour"}, {"kind": "literal", "value": 14}]}`. Funzionano via broadcasting numpy senza modifiche a comparator o operator nodes.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Frammento di prompt aggiunto
|
|
||||||
|
|
||||||
Da inserire in `hypothesis.py` dopo l'attuale sezione "Leaf - feature OHLCV":
|
|
||||||
|
|
||||||
```text
|
|
||||||
Leaf - feature TEMPORALI (sempre accessibili, UTC):
|
|
||||||
{{"kind": "feature", "name": "hour"}} range 0-23
|
|
||||||
{{"kind": "feature", "name": "dow"}} range 0-6 (lun=0, dom=6)
|
|
||||||
{{"kind": "feature", "name": "is_weekend"}} 0 o 1
|
|
||||||
{{"kind": "feature", "name": "minute_of_hour"}} range 0-59
|
|
||||||
|
|
||||||
Esempi di gating temporale:
|
|
||||||
// Solo durante la sessione US (14:00-22:00 UTC)
|
|
||||||
{{"op": "and", "args": [
|
|
||||||
{{"op": "gt", "args": [{{"kind": "feature", "name": "hour"}}, {{"kind": "literal", "value": 14}}]}},
|
|
||||||
{{"op": "lt", "args": [{{"kind": "feature", "name": "hour"}}, {{"kind": "literal", "value": 22}}]}}
|
|
||||||
]}}
|
|
||||||
|
|
||||||
// Solo nel weekend (sab+dom)
|
|
||||||
{{"op": "eq", "args": [{{"kind": "feature", "name": "is_weekend"}}, {{"kind": "literal", "value": 1}}]}}
|
|
||||||
```
|
|
||||||
|
|
||||||
Il blocco va inserito **prima** della frase corrente "Feature accessibili dal tuo genoma: {feature_access}", per chiarire che `{feature_access}` riguarda solo OHLCV mentre le temporali sono universali.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Backward compatibility e impatto sui run esistenti
|
|
||||||
|
|
||||||
Tutti i genomi esistenti nei `runs.db` storici (Phase 1, Phase 1.5 nemotron, Phase 1.5 grok in corso) usano solo feature OHLCV. Con la grammatica estesa restano validi: il validator continua ad accettarli, il compiler li gestisce nel branch OHLCV invariato.
|
|
||||||
|
|
||||||
Non c'è quindi alcuna migrazione di dati. I run vecchi possono essere ri-letti dalla dashboard senza modifiche. La distinzione "run pre/post feature temporali" sarà tracciata implicitamente dalla data del commit di merge.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Validazione end-to-end
|
|
||||||
|
|
||||||
Dopo il merge dei cinque file, la procedura di validazione è:
|
|
||||||
|
|
||||||
1. Esecuzione test suite completa (`uv run pytest`) — i 7 nuovi test devono passare, nessun test esistente deve rompersi.
|
|
||||||
2. `scripts/smoke_run.py` con `population_size=4, n_generations=1` per verificare che il loop end-to-end completi (caricamento OHLCV → generazione genome → compile → backtest → DSR → adversarial → persistenza). Tempo atteso ~2 minuti.
|
|
||||||
3. Ispezione manuale di almeno 1 genoma generato post-merge: verificare che il LLM abbia effettivamente usato almeno una feature temporale tra le sue regole. Se in 4 genomi nessuno usa feature temporali, ri-esaminare il prompt.
|
|
||||||
|
|
||||||
Non è previsto un confronto ablation formale (con/senza feature temporali) in questo spec — è un'attività di Phase 2 separata che andrà pianificata in un proprio spec quando si avvierà il run di valutazione.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Out of scope
|
|
||||||
|
|
||||||
I seguenti elementi sono esplicitamente fuori dallo scope di questo spec e dovranno essere oggetto di design dedicato se desiderati:
|
|
||||||
|
|
||||||
- **Feature temporali con segno periodico** (es. `sin_hour`, `cos_dow`): utili per regressioni continue, non per regole booleane GA-based. Skip.
|
|
||||||
- **Feature di sessione discreta** (es. `session=us|europe|asia`): derivabili componendo `hour` con comparator, non necessario aggiungere come feature primitiva.
|
|
||||||
- **Time-zone configurabile**: rimane fissa UTC. Cambiare implica refactor del loader OHLCV.
|
|
||||||
- **Validator range-check** (es. rifiutare `gt(dow, 6)`): sanzionato già dal loop GA via fitness e Adversarial.
|
|
||||||
- **Modifica del meccanismo `mutate_feature_access`**: invariato. Le feature temporali non entrano nel pool mutabile.
|
|
||||||
- **Indicatori temporali** (es. `time_since_last_high`): richiede stato persistente, fuori dal modello stateless attuale.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Stima di sforzo
|
|
||||||
|
|
||||||
Implementazione: ~120 LOC (60 di codice + 60 di test) in 5 file. Complessità bassa.
|
|
||||||
|
|
||||||
TDD-driven: scrivere prima i 7 test, verificare che falliscano, poi aggiungere whitelist + dispatcher + prompt. Tempo stimato: 2-3 ore di lavoro continuo, validation smoke run inclusa.
|
|
||||||
|
|
||||||
Costo prompt addizionale per call: ~200 token. Su un run da 200 call, ~40k token aggiuntivi → impatto economico trascurabile (<$0.05 con qualsiasi tier).
|
|
||||||
@@ -1,831 +0,0 @@
|
|||||||
# PoC Trading Swarm — Validazione Strategica
|
|
||||||
|
|
||||||
**Autore**: Adriano Dal Pastro
|
|
||||||
**Data**: Maggio 2026
|
|
||||||
**Status**: Design document — pre-implementazione
|
|
||||||
**Versione**: 0.1
|
|
||||||
**Documento correlato**: `coevolutive_swarm_system.md` (sistema completo)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Razionale della deviazione
|
|
||||||
|
|
||||||
Invece di committere 12-18 mesi al sistema co-evolutivo completo descritto nel documento principale, partiamo con un **proof-of-concept strategico** focalizzato su trading, con architettura semplificata, per validare empiricamente se l'idea di base funziona prima di investire nel sistema full.
|
|
||||||
|
|
||||||
**Cosa il PoC valida**:
|
|
||||||
1. Lo swarm produce strategie che superano il null hypothesis statistico (Deflated Sharpe Ratio significativo)?
|
|
||||||
2. Le strategie sono qualitativamente diverse o cloni leggeri?
|
|
||||||
3. Le strategie sopravvivono al regime change out-of-sample?
|
|
||||||
4. Quanto del successo viene da modelli costosi vs economici (ablation multi-tier)?
|
|
||||||
5. Lo swarm batte una baseline statistica tradizionale (random forest + feature engineering)?
|
|
||||||
|
|
||||||
**Tempo target**: 3-4 mesi a impegno significativo.
|
|
||||||
**Budget LLM target**: $2-4K.
|
|
||||||
|
|
||||||
**Decisione post-PoC**:
|
|
||||||
- Se passa tutti i 5 test → procedere con sistema completo (documento principale)
|
|
||||||
- Se passa parzialmente → iterare sul PoC, identificare bottleneck
|
|
||||||
- Se non passa → riformulare. Forse l'edge degli LLM agents è in altri domini, non in pattern discovery numerico
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Architettura semplificata
|
|
||||||
|
|
||||||
### 2.1 Cosa cambia rispetto al sistema completo
|
|
||||||
|
|
||||||
| Aspetto | Sistema completo | PoC |
|
|
||||||
|------------------------|-----------------------------|------------------------------------|
|
|
||||||
| Popolazioni evolventi | 4 (3 layer + protocollo) | 1 (solo Hypothesis) |
|
|
||||||
| Hypothesis layer | Evolve via GA | Evolve via GA (K=50) |
|
|
||||||
| Falsification layer | Evolve via GA | Hand-crafted, 1 agente fisso |
|
|
||||||
| Adversarial layer | Evolve via GA | Hand-crafted, 1 agente fisso |
|
|
||||||
| Protocollo | Co-evolve | Fisso, designed manualmente |
|
|
||||||
| Domini di applicazione | Multipli | Solo trading BTC/ETH |
|
|
||||||
| Idiom emergence | Sì | No |
|
|
||||||
| Speciation | Sì | Versione semplificata (clustering base) |
|
|
||||||
| Tier multi-model | Sì (S/A/B/C/D) | Sì (semplificato a B/C principalmente) |
|
|
||||||
| Human-in-the-loop | Strutturato ogni 20 gen | Review settimanale informale |
|
|
||||||
|
|
||||||
**Filosofia**: massimizzare apprendimento, minimizzare complessità implementativa.
|
|
||||||
|
|
||||||
### 2.2 Schema architetturale
|
|
||||||
|
|
||||||
```
|
|
||||||
┌───────────────────────────────────┐
|
|
||||||
│ PROTOCOLLO FISSO (S-expression) │
|
|
||||||
│ ~15 verbi designed manualmente │
|
|
||||||
└─────────────┬─────────────────────┘
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
┌──────────────────────┐
|
|
||||||
│ HYPOTHESIS SWARM │ ← UNICO layer che evolve
|
|
||||||
│ K=50 agenti │
|
|
||||||
│ Tier mix: B/C │
|
|
||||||
│ GA: tournament, │
|
|
||||||
│ speciation base, │
|
|
||||||
│ novelty bonus │
|
|
||||||
└──────────┬───────────┘
|
|
||||||
│ ipotesi formalizzate
|
|
||||||
▼
|
|
||||||
┌──────────────────────┐
|
|
||||||
│ FALSIFICATION (hand) │ ← FISSO
|
|
||||||
│ 1 agente Tier-B │
|
|
||||||
│ Funzione: traduce │
|
|
||||||
│ ipotesi in regole + │
|
|
||||||
│ chiama backtest + │
|
|
||||||
│ valuta con DSR │
|
|
||||||
└──────────┬───────────┘
|
|
||||||
│ strategie validate
|
|
||||||
▼
|
|
||||||
┌──────────────────────┐
|
|
||||||
│ ADVERSARIAL (hand) │ ← FISSO
|
|
||||||
│ 1 agente Tier-A │
|
|
||||||
│ Funzione: red team │
|
|
||||||
│ con checklist statica│
|
|
||||||
│ (lookahead, regime, │
|
|
||||||
│ crowding) │
|
|
||||||
└──────────┬───────────┘
|
|
||||||
│ strategie sopravvissute
|
|
||||||
▼
|
|
||||||
┌──────────────────────┐
|
|
||||||
│ FITNESS LOOP │
|
|
||||||
│ Update agent_fitness│
|
|
||||||
│ Selezione + GA │
|
|
||||||
└──────────────────────┘
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
Generazione N+1
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Le quattro trappole del backtesting su crypto
|
|
||||||
|
|
||||||
Queste sono le killer specifiche del dominio. Vanno mitigate by design, non come afterthought.
|
|
||||||
|
|
||||||
### 3.1 Look-ahead bias subdolo
|
|
||||||
|
|
||||||
**Problema**: molti dati "storici" su crypto sono in realtà revisionati ex-post.
|
|
||||||
- Funding rates: spesso medie giornaliere ricalcolate, non valori real-time storici
|
|
||||||
- On-chain metrics (MVRV, NUPL, SOPR): formule che cambiano nel tempo, applicate retroattivamente
|
|
||||||
- Liste top-N token: survivorship bias massiccio
|
|
||||||
- Sentiment storico: ricostruzioni post-hoc, non disponibili in tempo reale a quei momenti
|
|
||||||
|
|
||||||
**Mitigazione**:
|
|
||||||
- Ogni feature deve avere un campo `availability_lag`: quante ore dopo il timestamp T la feature era effettivamente disponibile
|
|
||||||
- Backtest engine rifiuta di usare feature prima del lag
|
|
||||||
- Documentazione esplicita di come/quando ogni feature è stata raccolta
|
|
||||||
- Preferire fonti che pubblicano archivi real-time (Kaiko, Tardis.dev, Amberdata) a quelle ricostruite
|
|
||||||
|
|
||||||
### 3.2 Multiple testing su scala industriale
|
|
||||||
|
|
||||||
**Problema**: con 10000 strategie testate, ~100 superano p<0.01 per puro caso. Senza correzione, il sistema produce sempre "vincitori" illusori.
|
|
||||||
|
|
||||||
**Mitigazione**:
|
|
||||||
- **Deflated Sharpe Ratio (DSR)** come fitness primaria, non Sharpe naive
|
|
||||||
- Tracking del numero totale di strategie testate fino a generazione N (impatta DSR)
|
|
||||||
- Bonferroni-style correction quando si seleziona "top strategies" da reporting
|
|
||||||
- Hold-out set finale **mai toccato durante evoluzione** per validation finale
|
|
||||||
|
|
||||||
### 3.3 Regime dependency
|
|
||||||
|
|
||||||
**Problema**: BTC/ETH hanno regimi macro molto diversi. Una strategia che funziona 2018-2024 può essere semplicemente "long-only momentum con leva". OOS 2026 fallisce.
|
|
||||||
|
|
||||||
**Periodi di regime distintivi**:
|
|
||||||
- 2017: bull mania retail (escluso dal dataset, troppo anomalo)
|
|
||||||
- 2018-2019: bear lungo
|
|
||||||
- 2020-2021: DeFi summer + bull istituzionale + COVID
|
|
||||||
- 2022: collapse cycle (LUNA, FTX, Celsius)
|
|
||||||
- 2023-2024: ripresa + ETF spot
|
|
||||||
- 2025-2026: post-ETF, regime nuovo
|
|
||||||
|
|
||||||
**Mitigazione**:
|
|
||||||
- Walk-forward con **purged cross-validation** (López de Prado 2018)
|
|
||||||
- Train su finestra mobile, test su successiva, **gap di purging** in mezzo per evitare leakage
|
|
||||||
- Fitness penalizza strategie che funzionano solo su 1-2 regimi
|
|
||||||
- OOS finale obbligatoriamente su periodo diverso dal training
|
|
||||||
|
|
||||||
### 3.4 Backtest ≠ live execution
|
|
||||||
|
|
||||||
**Problema**: anche backtest perfetto ha gap col live.
|
|
||||||
- Slippage non lineare con size (su crypto particolarmente)
|
|
||||||
- Fees variabili (maker/taker, volume rebates)
|
|
||||||
- Funding rate sui perp può mangiarsi l'edge
|
|
||||||
- Liquidità evapora nei momenti che contano
|
|
||||||
- API outages, exchange downtime
|
|
||||||
|
|
||||||
**Mitigazione**:
|
|
||||||
- Modello di slippage realistico (Almgren-Chriss o simile, non costante)
|
|
||||||
- Fees accurate (struttura tier per exchange)
|
|
||||||
- Funding payments simulati per posizioni perp
|
|
||||||
- Cap su size per evitare strategie che funzionano solo a $100, non a $100K
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Dataset Specification
|
|
||||||
|
|
||||||
### 4.1 Coverage
|
|
||||||
|
|
||||||
- **Asset**: BTC, ETH (focus iniziale)
|
|
||||||
- **Periodo**: 2018-01-01 → 2025-12-31
|
|
||||||
- **Train/OOS split**: train 2018-2023, OOS validation 2024, OOS final hold-out 2025
|
|
||||||
- **Frequenza base**: 1-hour bars (compromesso tra granularità e gestibilità)
|
|
||||||
- **Frequenze derivate**: 4h, 1d aggregate per features di lungo periodo
|
|
||||||
|
|
||||||
### 4.2 Feature catalog
|
|
||||||
|
|
||||||
**Price/Volume (sempre disponibili real-time, lag=0)**:
|
|
||||||
- OHLCV su 1h, 4h, 1d
|
|
||||||
- Returns log su orizzonti multipli
|
|
||||||
- Volatility realized (Garman-Klass, Parkinson, RV)
|
|
||||||
- Volume profile, VWAP
|
|
||||||
|
|
||||||
**Derivatives (lag tipicamente 5-15min)**:
|
|
||||||
- Funding rates (Bybit, Binance, Hyperliquid, Deribit)
|
|
||||||
- Open Interest (per exchange e aggregato)
|
|
||||||
- Put/Call ratio (Deribit options)
|
|
||||||
- Implied volatility surface (Deribit)
|
|
||||||
- Skew, term structure
|
|
||||||
- Liquidations (volume e direzione)
|
|
||||||
|
|
||||||
**On-chain (lag tipicamente 1-6 ore per finalization)**:
|
|
||||||
- Active addresses
|
|
||||||
- Transaction count + volume
|
|
||||||
- Exchange inflows/outflows (Glassnode-style)
|
|
||||||
- Miner flows
|
|
||||||
- Whale transactions (>$1M)
|
|
||||||
- MVRV, NUPL, SOPR (con cautela su revisionalità)
|
|
||||||
|
|
||||||
**Macro context (lag variabile)**:
|
|
||||||
- DXY, gold, S&P 500, yield 10Y (per correlazioni)
|
|
||||||
- Crypto-specific: BTC dominance, ETH/BTC ratio, total market cap
|
|
||||||
- Stablecoin supply (USDT, USDC, DAI)
|
|
||||||
|
|
||||||
**Sentiment (lag variabile, qualità incerta)**:
|
|
||||||
- Funding rate come proxy sentiment
|
|
||||||
- Open Interest variations come proxy speculation
|
|
||||||
- (Skip Twitter/social per ora — qualità storica troppo bassa)
|
|
||||||
|
|
||||||
### 4.3 Data sources
|
|
||||||
|
|
||||||
**Preferiti** (real-time archivi):
|
|
||||||
- Tardis.dev (derivatives, order book, trades — premium)
|
|
||||||
- Kaiko (institutional grade — premium)
|
|
||||||
- Amberdata (multi-source)
|
|
||||||
|
|
||||||
**Backup gratuiti/cheap**:
|
|
||||||
- CCXT historical (OHLCV affidabile)
|
|
||||||
- Binance/Bybit/Deribit API direct (con cautela su gap)
|
|
||||||
- CoinGlass (derivatives aggregati, qualità media)
|
|
||||||
- Glassnode free tier (on-chain, limitato)
|
|
||||||
|
|
||||||
**Da evitare**:
|
|
||||||
- Aggregatori che non documentano metodologia
|
|
||||||
- Source che hanno cambiato formula nel tempo senza versioning
|
|
||||||
|
|
||||||
### 4.4 Storage
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE TABLE features (
|
|
||||||
timestamp TIMESTAMPTZ NOT NULL,
|
|
||||||
asset TEXT NOT NULL,
|
|
||||||
feature_name TEXT NOT NULL,
|
|
||||||
value DOUBLE PRECISION,
|
|
||||||
availability_lag_seconds INT NOT NULL, -- CRITICO
|
|
||||||
source TEXT,
|
|
||||||
version TEXT, -- per gestire cambi di metodologia
|
|
||||||
PRIMARY KEY (timestamp, asset, feature_name)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX idx_feat_time ON features (timestamp);
|
|
||||||
CREATE INDEX idx_feat_asset_name ON features (asset, feature_name);
|
|
||||||
```
|
|
||||||
|
|
||||||
Considerare TimescaleDB se le query temporali diventano colli di bottiglia.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Backtest Engine
|
|
||||||
|
|
||||||
### 5.1 Requisiti
|
|
||||||
|
|
||||||
- **Determinismo**: stesso input, stesso output, sempre
|
|
||||||
- **Velocità**: target ≥100 backtest/sec su CPU normale (per gestire 50 agenti × 10 ipotesi/gen)
|
|
||||||
- **Anti-leakage by design**: rifiuta feature prima di availability_lag
|
|
||||||
- **Walk-forward integrato**: non opzionale, parte del flow base
|
|
||||||
- **Realistic execution**: slippage, fees, funding
|
|
||||||
|
|
||||||
### 5.2 Architettura
|
|
||||||
|
|
||||||
**Linguaggio**: Python+NumPy per il PoC. Rust+PyO3 solo se diventa bottleneck (probabile in fase scaling, non necessario per PoC).
|
|
||||||
|
|
||||||
**API base**:
|
|
||||||
```python
|
|
||||||
class BacktestEngine:
|
|
||||||
def run(self,
|
|
||||||
strategy: StrategySpec,
|
|
||||||
features: FeatureSet,
|
|
||||||
time_range: tuple[datetime, datetime],
|
|
||||||
walk_forward_config: WFConfig) -> BacktestResult:
|
|
||||||
...
|
|
||||||
|
|
||||||
def run_with_dsr(self,
|
|
||||||
strategy: StrategySpec,
|
|
||||||
...) -> tuple[BacktestResult, DSRStats]:
|
|
||||||
...
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class StrategySpec:
|
|
||||||
entry_rules: list[Rule] # condizioni di ingresso
|
|
||||||
exit_rules: list[Rule] # condizioni di uscita
|
|
||||||
sizing: SizingRule # position sizing
|
|
||||||
instruments: list[str] # BTC, ETH, BTC-PERP, etc.
|
|
||||||
constraints: list[Constraint] # max leverage, max DD, etc.
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class BacktestResult:
|
|
||||||
pnl_curve: pd.Series
|
|
||||||
sharpe: float
|
|
||||||
sortino: float
|
|
||||||
max_drawdown: float
|
|
||||||
n_trades: int
|
|
||||||
win_rate: float
|
|
||||||
avg_holding_time: timedelta
|
|
||||||
fees_paid: float
|
|
||||||
funding_paid: float
|
|
||||||
slippage_cost: float
|
|
||||||
regime_breakdown: dict[str, float] # PnL per regime
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5.3 Execution model
|
|
||||||
|
|
||||||
**Slippage**:
|
|
||||||
```
|
|
||||||
slippage = base_spread + impact_factor * (size / avg_volume_5min) ^ 0.5
|
|
||||||
```
|
|
||||||
Calibrato su book reale per BTC/ETH. Più alto in regimi di alta volatilità.
|
|
||||||
|
|
||||||
**Fees**:
|
|
||||||
- Maker: 0.02% (tipico)
|
|
||||||
- Taker: 0.05% (tipico)
|
|
||||||
- Tier per volume non simulato nel PoC (assume tier base)
|
|
||||||
|
|
||||||
**Funding** (per perp):
|
|
||||||
- Pagato/ricevuto ogni 8 ore
|
|
||||||
- Calcolato su mark price × position size × funding rate
|
|
||||||
|
|
||||||
**Constraints automatiche**:
|
|
||||||
- Max leverage (configurabile, default 5x per il PoC)
|
|
||||||
- Margin call simulati realisticamente
|
|
||||||
- Liquidations forzate se margin scende sotto threshold
|
|
||||||
|
|
||||||
### 5.4 Walk-forward purged CV
|
|
||||||
|
|
||||||
```
|
|
||||||
Time: |---------train-----------|gap|----test----|---next gap---|--next test--|
|
|
||||||
Window 1: [2018-01 ──────── 2020-06] [2020-07 ──── 2020-12]
|
|
||||||
Window 2: [2018-07 ──── 2021-06] [2021-07 ──── 2021-12]
|
|
||||||
Window 3: [2019-01 ── 2022-06] [2022-07 ── 2022-12]
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
- Training window: 30 mesi
|
|
||||||
- Gap (purging): 1 mese (evita leakage da event horizon)
|
|
||||||
- Test window: 6 mesi
|
|
||||||
- Step: 6 mesi
|
|
||||||
- Embargo: ulteriori 2 settimane post-test prima del prossimo training (López de Prado embargo)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Hypothesis Swarm (l'unico layer che evolve)
|
|
||||||
|
|
||||||
### 6.1 Genome design
|
|
||||||
|
|
||||||
```python
|
|
||||||
@dataclass
|
|
||||||
class HypothesisAgentGenome:
|
|
||||||
# Cognizione
|
|
||||||
system_prompt: str
|
|
||||||
cognitive_style: str # "physicist", "biologist", "engineer", "trader_oldschool"...
|
|
||||||
|
|
||||||
# Accesso a dati
|
|
||||||
feature_access: list[str] # subset delle feature disponibili
|
|
||||||
lookback_window_days: int # quanto storico vede
|
|
||||||
timeframes: list[str] # ["1h", "4h", "1d"]
|
|
||||||
|
|
||||||
# Modello
|
|
||||||
model_tier: ModelTier # B o C principalmente nel PoC
|
|
||||||
temperature: float # 0.6 - 1.2
|
|
||||||
|
|
||||||
# Bias di output
|
|
||||||
strategy_type_preference: list[str] # ["mean_reversion", "momentum", "vol_arb", "cross_asset"]
|
|
||||||
timeframe_preference: str # "intraday", "swing", "position"
|
|
||||||
|
|
||||||
# Tracking
|
|
||||||
parent_ids: list[UUID]
|
|
||||||
generation: int
|
|
||||||
species_id: UUID
|
|
||||||
```
|
|
||||||
|
|
||||||
### 6.2 Output format (nel protocollo fisso)
|
|
||||||
|
|
||||||
```
|
|
||||||
PROPOSE_STRATEGY(
|
|
||||||
id=#strat_47,
|
|
||||||
name="vol_skew_momentum",
|
|
||||||
|
|
||||||
entry_conditions=[
|
|
||||||
AND(
|
|
||||||
(deribit_skew_25d > rolling_mean(deribit_skew_25d, 30d) + 1.5*std),
|
|
||||||
(btc_funding_8h > 0.01),
|
|
||||||
(eth_funding_8h > btc_funding_8h)
|
|
||||||
)
|
|
||||||
],
|
|
||||||
|
|
||||||
exit_conditions=[
|
|
||||||
OR(
|
|
||||||
(skew normalized below mean),
|
|
||||||
(max_holding > 7d),
|
|
||||||
(drawdown > 0.03)
|
|
||||||
)
|
|
||||||
],
|
|
||||||
|
|
||||||
sizing=KELLY_FRACTIONAL(fraction=0.25),
|
|
||||||
instruments=["ETH-PERP-HL"],
|
|
||||||
side="long",
|
|
||||||
|
|
||||||
rationale="Skew elevato indica fear di puts, funding alto indica long crowding. Cross-section ETH/BTC funding suggerisce ETH outperformance attesa.",
|
|
||||||
|
|
||||||
expected_regime="normal volatility, trending",
|
|
||||||
expected_failure_modes=["crash con depinning", "regime shift improvviso"]
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 6.3 Operatori genetici
|
|
||||||
|
|
||||||
**Mutazione del system prompt**:
|
|
||||||
- LLM-as-mutator (Tier-B): "Modifica questo prompt cambiando un aspetto cognitivo, mantenendo intent"
|
|
||||||
- Probabilità: 60% per agente selezionato
|
|
||||||
|
|
||||||
**Mutazione di feature_access**:
|
|
||||||
- Add/remove 1-3 feature random
|
|
||||||
- Probabilità: 30%
|
|
||||||
|
|
||||||
**Mutazione di temperature**:
|
|
||||||
- Gaussiana, σ=0.1, clip [0.3, 1.4]
|
|
||||||
- Probabilità: 20%
|
|
||||||
|
|
||||||
**Crossover**:
|
|
||||||
- 50/50 di feature_access da due parent
|
|
||||||
- Cognitive_style preso da parent migliore
|
|
||||||
- System prompt: crossover sezione-by-sezione (role/context/instructions/output_format)
|
|
||||||
- Probabilità: 50% per nuova generazione (resto è mutazione)
|
|
||||||
|
|
||||||
**Mutazione di model_tier**:
|
|
||||||
- Rara (5%), perché impatta costo
|
|
||||||
- Solo C↔B, non promozioni a A senza fitness eccezionale
|
|
||||||
|
|
||||||
### 6.4 Selection
|
|
||||||
|
|
||||||
**Tournament selection**, k=5.
|
|
||||||
|
|
||||||
**Speciation semplificata**:
|
|
||||||
- Embedding del system prompt via Voyage o OpenAI ada
|
|
||||||
- K-means con K=5-7 cluster
|
|
||||||
- Fitness sharing dentro cluster
|
|
||||||
|
|
||||||
**Elitismo**: top 3 agenti per cluster sopravvivono non modificati.
|
|
||||||
|
|
||||||
**Immigrazione**: ogni 10 generazioni, 5 nuovi agenti random vengono inseriti (anti-stagnazione).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Falsification Agent (hand-crafted, fisso)
|
|
||||||
|
|
||||||
### 7.1 Ruolo
|
|
||||||
|
|
||||||
Prende ipotesi dal swarm, le esegue su backtest engine, riporta risultati con DSR e diagnostica.
|
|
||||||
|
|
||||||
**NON** valuta soggettivamente. Esegue test deterministici e li interpreta.
|
|
||||||
|
|
||||||
### 7.2 Modello
|
|
||||||
|
|
||||||
Tier-B (Qwen Max o equivalente). Sufficiente per:
|
|
||||||
- Tradurre ipotesi in linguaggio naturale → StrategySpec strutturato
|
|
||||||
- Chiamare backtest engine
|
|
||||||
- Interpretare output numerico
|
|
||||||
- Riportare in protocollo
|
|
||||||
|
|
||||||
### 7.3 System prompt template
|
|
||||||
|
|
||||||
```
|
|
||||||
Sei un agente di falsification rigoroso. Il tuo ruolo è testare ipotesi
|
|
||||||
trading senza pregiudizi e riportare risultati onesti.
|
|
||||||
|
|
||||||
Per ogni ipotesi ricevuta:
|
|
||||||
1. Verifica che le entry/exit conditions siano formalizzabili in regole testabili
|
|
||||||
2. Verifica che le feature richieste rispettino availability_lag
|
|
||||||
3. Chiama il backtest engine con configurazione walk-forward standard
|
|
||||||
4. Calcola Deflated Sharpe Ratio considerando il numero di test fatti finora ({total_trials})
|
|
||||||
5. Riporta breakdown per regime (bear/bull/sideways)
|
|
||||||
6. Identifica failure modes osservati nel backtest
|
|
||||||
|
|
||||||
Output strict in protocollo S-expression. Nessuna interpretazione narrativa.
|
|
||||||
Se l'ipotesi non è formalizzabile, ritorna REJECT con motivo specifico.
|
|
||||||
```
|
|
||||||
|
|
||||||
### 7.4 Output format
|
|
||||||
|
|
||||||
```
|
|
||||||
REPORT_BACKTEST(
|
|
||||||
target=#strat_47,
|
|
||||||
|
|
||||||
metrics=(
|
|
||||||
sharpe=1.34,
|
|
||||||
deflated_sharpe=0.87,
|
|
||||||
p_value=0.04,
|
|
||||||
max_drawdown=0.18,
|
|
||||||
n_trades=143,
|
|
||||||
avg_holding_h=42
|
|
||||||
),
|
|
||||||
|
|
||||||
regime_performance=(
|
|
||||||
bear_2018=0.42,
|
|
||||||
bull_2020=2.1,
|
|
||||||
crash_2022=-0.85,
|
|
||||||
recovery_2023=1.1
|
|
||||||
),
|
|
||||||
|
|
||||||
warnings=[
|
|
||||||
"Performance dominated by 2020-2021 regime",
|
|
||||||
"DSR significant but multiple testing burden high (8400 strategies tested)"
|
|
||||||
],
|
|
||||||
|
|
||||||
verdict=PASS_WITH_WARNINGS // PASS / FAIL / PASS_WITH_WARNINGS
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Adversarial Agent (hand-crafted, fisso)
|
|
||||||
|
|
||||||
### 8.1 Ruolo
|
|
||||||
|
|
||||||
Per ogni strategia che passa Falsification, applica una **checklist statica** di attacchi epistemici.
|
|
||||||
|
|
||||||
Nel PoC NON evolve. Ha vocabolario fisso di attacchi noti dalla letteratura (López de Prado, Bailey, etc.).
|
|
||||||
|
|
||||||
### 8.2 Modello
|
|
||||||
|
|
||||||
Tier-A (Sonnet). Qui il reasoning conta — riconoscere lookahead bias subtle richiede capacità.
|
|
||||||
|
|
||||||
### 8.3 Checklist di attacchi
|
|
||||||
|
|
||||||
```
|
|
||||||
1. Lookahead bias check
|
|
||||||
- Tutte le feature usate rispettano availability_lag?
|
|
||||||
- Qualche feature è "future-derived" subdolamente?
|
|
||||||
|
|
||||||
2. Survivorship bias check
|
|
||||||
- La strategia usa universo di asset dinamico?
|
|
||||||
- Filtra solo asset sopravvissuti?
|
|
||||||
|
|
||||||
3. Regime dependency check
|
|
||||||
- Performance concentrata in 1-2 regimi specifici?
|
|
||||||
- Cosa succede se rimuovi il regime migliore?
|
|
||||||
|
|
||||||
4. Multiple testing severity
|
|
||||||
- DSR resta significativo dopo Bonferroni stretto?
|
|
||||||
- Confronto con random strategy baseline
|
|
||||||
|
|
||||||
5. Crowding plausibility
|
|
||||||
- La logica è "ovvia"? Probabilmente già crowded
|
|
||||||
- Edge size ragionevole o sospettosamente alto?
|
|
||||||
|
|
||||||
6. Implementation friction
|
|
||||||
- Slippage assumption realistica per la size?
|
|
||||||
- Funding payments inclusi correttamente?
|
|
||||||
- Trade frequency compatibile con execution reale?
|
|
||||||
|
|
||||||
7. Feature stability
|
|
||||||
- Le feature critiche hanno stessa metodologia in tutto il periodo?
|
|
||||||
- Source provider ha cambiato formula?
|
|
||||||
|
|
||||||
8. Statistical robustness
|
|
||||||
- Sharpe sensibile a rimozione top 5% trade?
|
|
||||||
- Performance robusta a perturbazioni piccole nei parametri?
|
|
||||||
```
|
|
||||||
|
|
||||||
### 8.4 Output
|
|
||||||
|
|
||||||
```
|
|
||||||
ADVERSARIAL_REVIEW(
|
|
||||||
target=#strat_47,
|
|
||||||
attacks_passed=[1, 2, 5, 6, 7],
|
|
||||||
attacks_failed=[3, 4, 8],
|
|
||||||
|
|
||||||
critical_concerns=[
|
|
||||||
CONCERN(
|
|
||||||
type=regime_dependency,
|
|
||||||
severity=high,
|
|
||||||
detail="60% of PnL from 2020-2021 bull regime. Removing it gives Sharpe 0.4."
|
|
||||||
),
|
|
||||||
CONCERN(
|
|
||||||
type=multiple_testing,
|
|
||||||
severity=medium,
|
|
||||||
detail="DSR significant but only marginally (p=0.04). With 8400 trials, expect ~336 false positives at this level."
|
|
||||||
)
|
|
||||||
],
|
|
||||||
|
|
||||||
verdict=REJECT // ACCEPT / ACCEPT_CONDITIONAL / REJECT
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Fitness Function
|
|
||||||
|
|
||||||
### 9.1 Agent fitness (per Hypothesis swarm)
|
|
||||||
|
|
||||||
```python
|
|
||||||
def agent_fitness(agent: HypothesisAgentGenome,
|
|
||||||
episodes: list[Episode]) -> float:
|
|
||||||
|
|
||||||
# Quality of contributions
|
|
||||||
accepted_strats = [e for e in episodes
|
|
||||||
if e.adversarial_verdict == "ACCEPT"]
|
|
||||||
conditional_strats = [e for e in episodes
|
|
||||||
if e.adversarial_verdict == "ACCEPT_CONDITIONAL"]
|
|
||||||
|
|
||||||
quality_score = (
|
|
||||||
len(accepted_strats) * 1.0
|
|
||||||
+ len(conditional_strats) * 0.3
|
|
||||||
)
|
|
||||||
|
|
||||||
# Average DSR of accepted strategies
|
|
||||||
avg_dsr = np.mean([e.dsr for e in accepted_strats]) if accepted_strats else 0
|
|
||||||
|
|
||||||
# Cost penalty (proporzionale al tier usato)
|
|
||||||
cost_per_episode = TIER_COST[agent.model_tier] * agent.avg_tokens_per_episode
|
|
||||||
cost_penalty = cost_per_episode * COST_PENALTY_LAMBDA
|
|
||||||
|
|
||||||
# Novelty bonus (semantica delle strategie prodotte)
|
|
||||||
novelty_score = compute_novelty(agent, all_agents_in_generation)
|
|
||||||
|
|
||||||
# Diversity bonus (strategie diverse, non cloni)
|
|
||||||
diversity_score = compute_internal_diversity(agent.strategies)
|
|
||||||
|
|
||||||
return (
|
|
||||||
quality_score
|
|
||||||
+ avg_dsr * DSR_WEIGHT
|
|
||||||
+ novelty_score * NOVELTY_WEIGHT
|
|
||||||
+ diversity_score * DIVERSITY_WEIGHT
|
|
||||||
- cost_penalty
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 9.2 Pesi iniziali (da calibrare empiricamente)
|
|
||||||
|
|
||||||
```python
|
|
||||||
DSR_WEIGHT = 2.0 # peso forte: vogliamo edge reale
|
|
||||||
NOVELTY_WEIGHT = 0.5 # bonus moderato per esplorazione
|
|
||||||
DIVERSITY_WEIGHT = 0.3 # leggero, evita cloni
|
|
||||||
COST_PENALTY_LAMBDA = 0.1 # da calibrare in base a budget
|
|
||||||
```
|
|
||||||
|
|
||||||
### 9.3 Anti-gaming
|
|
||||||
|
|
||||||
- Tracking globale del numero di test fatti per DSR correction
|
|
||||||
- Cap su `quality_score` per evitare gaming via spam di ipotesi banali
|
|
||||||
- Adversarial feedback va in fitness (strategie REJECTED penalizzano, non solo non bonificano)
|
|
||||||
- Periodic audit umano: ogni 10 generazioni rivedere top 5 strategies, marcare "spurious" se gaming
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. Baseline non-LLM (anti-illusion check)
|
|
||||||
|
|
||||||
**Critico**: il PoC deve includere una baseline statistica tradizionale.
|
|
||||||
|
|
||||||
### 10.1 Specifica baseline
|
|
||||||
|
|
||||||
- **Metodo**: Random Forest + feature engineering manuale
|
|
||||||
- **Features**: stesso pool del swarm
|
|
||||||
- **Target**: returns N-bar future (predizione regression o classification)
|
|
||||||
- **Validation**: stesso walk-forward purged CV
|
|
||||||
- **Output**: trade signals → backtest engine identico
|
|
||||||
|
|
||||||
### 10.2 Confronto
|
|
||||||
|
|
||||||
| Metrica | Baseline RF | Swarm LLM |
|
|
||||||
|----------------------------|-------------|-----------|
|
|
||||||
| Best DSR found | ? | ? |
|
|
||||||
| Avg DSR top-10 strategies | ? | ? |
|
|
||||||
| N strategies passing adv. | ? | ? |
|
|
||||||
| Diversity (semantic) | ? | ? |
|
|
||||||
| Total cost | ~$50 | ~$3K |
|
|
||||||
|
|
||||||
**Interpretazione**:
|
|
||||||
- Se Swarm batte significativamente Baseline → architettura LLM sta aggiungendo valore
|
|
||||||
- Se Swarm pareggia → costo non giustificato per discovery numerica pura
|
|
||||||
- Se Swarm perde → l'edge degli LLM agents è altrove (creatività su task non numerici, integrazione semi-strutturata)
|
|
||||||
|
|
||||||
**Punto importante**: anche se Swarm perde su pattern discovery numerico, NON significa che il sistema co-evolutivo completo è inutile. Significa che la value-add è in altri domini (ipotesi macro, integrazione narrative, generalizzazione cross-domain). È informazione preziosa.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 11. Roadmap Implementativa (3-4 mesi)
|
|
||||||
|
|
||||||
### Settimane 1-3: Setup & Dataset
|
|
||||||
|
|
||||||
- Setup repo, environment, dependencies
|
|
||||||
- Data sourcing: identificare provider, sottoscrivere se necessario
|
|
||||||
- Data ingestion: pipeline dati storici BTC/ETH 2018-2025
|
|
||||||
- Storage schema (PostgreSQL/TimescaleDB)
|
|
||||||
- Audit di availability_lag per ogni feature
|
|
||||||
- Sanity checks: confronto cross-source per validare integrity
|
|
||||||
|
|
||||||
**Deliverable**: dataset completo annotato, query-able, con feature catalog.
|
|
||||||
|
|
||||||
### Settimane 4-7: Backtest Engine
|
|
||||||
|
|
||||||
- Implementazione walk-forward purged CV
|
|
||||||
- Slippage model (Almgren-Chriss)
|
|
||||||
- Fees + funding
|
|
||||||
- DSR computation
|
|
||||||
- Test di non-leakage (deliberately inject lookahead → engine deve catcharlo)
|
|
||||||
- Performance optimization (target ≥100 backtest/sec)
|
|
||||||
|
|
||||||
**Deliverable**: backtest engine standalone testato. Strategie semplici (buy & hold, 50/200 SMA crossover) producono risultati noti.
|
|
||||||
|
|
||||||
### Settimane 8-9: Agenti hand-crafted
|
|
||||||
|
|
||||||
- Falsification agent (Tier-B)
|
|
||||||
- Adversarial agent (Tier-A)
|
|
||||||
- Protocol fisso (S-expression parser + 15 verbi)
|
|
||||||
- Message bus auditato semplificato
|
|
||||||
- Test end-to-end con ipotesi hand-crafted
|
|
||||||
|
|
||||||
**Deliverable**: pipeline agente → falsification → adversarial → verdict, funzionante end-to-end con strategie inserite manualmente.
|
|
||||||
|
|
||||||
### Settimane 10-12: Hypothesis Swarm + GA
|
|
||||||
|
|
||||||
- Population manager (50 agenti)
|
|
||||||
- Operatori genetici (mutazione + crossover)
|
|
||||||
- Speciation con clustering embedding
|
|
||||||
- Fitness computation
|
|
||||||
- Tournament selection
|
|
||||||
- Evoluzione per 50 generazioni baseline
|
|
||||||
|
|
||||||
**Deliverable**: swarm che evolve, fitness che migliora over generations, output di top strategies.
|
|
||||||
|
|
||||||
### Settimane 13-14: Baseline + Comparison
|
|
||||||
|
|
||||||
- Implementazione baseline Random Forest
|
|
||||||
- Run baseline su stesso dataset/timeframe
|
|
||||||
- Tabella comparison
|
|
||||||
- Analisi qualitative delle strategie prodotte da entrambi
|
|
||||||
|
|
||||||
**Deliverable**: documento di confronto onesto.
|
|
||||||
|
|
||||||
### Settimane 15-16: Analisi & Report
|
|
||||||
|
|
||||||
- Run finale su hold-out set 2025
|
|
||||||
- Analysis: ablation multi-tier, regime breakdown, diversity analysis
|
|
||||||
- Documentazione lessons learned
|
|
||||||
- Decision document: procedere con sistema completo, iterare PoC, o pivot
|
|
||||||
|
|
||||||
**Deliverable**: report finale con risposte alle 5 domande di validazione iniziali.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 12. Costi PoC
|
|
||||||
|
|
||||||
### 12.1 LLM costs
|
|
||||||
|
|
||||||
| Fase | Calls stimate | Tokens stimati | Tier mix | Costo |
|
|
||||||
|-------------------------|---------------|-----------------|--------------|--------|
|
|
||||||
| Setup + agenti hand | ~500 | 2M | A/B | ~$50 |
|
|
||||||
| Test pipeline | ~2000 | 8M | B/C | ~$30 |
|
|
||||||
| GA run principale | 50 gen × 50 agent × 10 calls × 5K tok = 125M tok | mostly C, some B | ~$300-500 |
|
|
||||||
| Repeat runs (3x) | (per ablation, tuning) | | | ~$1000-1500 |
|
|
||||||
| Hold-out validation | ~1000 | 5M | A (judge) | ~$80 |
|
|
||||||
| **Totale** | | | | **$1500-2500** |
|
|
||||||
|
|
||||||
Più conservativo se aggiungiamo iteration overhead: **budget $2-4K**.
|
|
||||||
|
|
||||||
### 12.2 Infrastruttura
|
|
||||||
|
|
||||||
- Compute (locale o cloud modesto): ~$200-400 totali
|
|
||||||
- Storage (data + logs): ~$50/mese
|
|
||||||
- Data subscription (Tardis o Kaiko per derivatives): variabile, $0-500/mese a seconda della qualità richiesta
|
|
||||||
|
|
||||||
### 12.3 Tempo
|
|
||||||
|
|
||||||
- Realistic estimate: **3-4 mesi** a 3-4 giorni/settimana effettivi
|
|
||||||
- Pessimistic estimate: 5-6 mesi se data sourcing risulta più complesso del previsto
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 13. Rischi e Mitigazioni
|
|
||||||
|
|
||||||
| Rischio | Probabilità | Impatto | Mitigazione |
|
|
||||||
|------------------------------------|-------------|---------|-----------------------------------------|
|
|
||||||
| Data sourcing più complesso | Alta | Medio | Start con CCXT + Binance free, upgrade dopo |
|
|
||||||
| Backtest engine ha bug subtle | Alta | Critico | Test deliberato di lookahead injection |
|
|
||||||
| Swarm non batte baseline RF | Media | Alto | È un risultato comunque, non fallimento |
|
|
||||||
| Costi over-budget | Media | Medio | Cap hard, monitor settimanale |
|
|
||||||
| Time over-budget (5+ mesi) | Alta | Medio | Milestone bi-settimanali, taglio scope se necessario |
|
|
||||||
| Convergenza prematura del swarm | Media | Alto | Speciation, novelty bonus, immigrazione |
|
|
||||||
| OpenRouter qualità inconsistente | Media | Basso | Fallback policy, monitor success rate |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 14. Decisioni Aperte
|
|
||||||
|
|
||||||
Da risolvere prima di Fase 1:
|
|
||||||
|
|
||||||
1. **Asset focus**: solo BTC, solo ETH, o entrambi? (suggerito: entrambi, per cross-asset features)
|
|
||||||
2. **Data provider primario**: pagare Tardis/Kaiko o partire con free sources? (suggerito: free per Fase 1, upgrade se necessario)
|
|
||||||
3. **Hardware**: locale o cloud? (suggerito: locale, dataset ~50-100GB gestibile)
|
|
||||||
4. **Tier-A budget**: quanto reservare a Sonnet per Adversarial? (suggerito: $300-500 cap)
|
|
||||||
5. **Frequency primaria**: 1h confermato o scendere a 15min? (suggerito: 1h, evita overfitting su microstructure)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 15. Cosa il PoC NON fa (e va bene)
|
|
||||||
|
|
||||||
- NON evolve il protocollo (sistema completo)
|
|
||||||
- NON co-evolve Falsification e Adversarial (sistema completo)
|
|
||||||
- NON esplora idiom emergence (sistema completo)
|
|
||||||
- NON applica a domini non-trading (sistema completo)
|
|
||||||
- NON cerca breakthrough singoli, cerca **validazione architetturale**
|
|
||||||
- NON è un trading bot pronto per capitale reale (mai dopo PoC, paper trading prima)
|
|
||||||
|
|
||||||
Il PoC è un **esperimento controllato**. Il sistema completo è il prodotto. Sono cose diverse, e va bene così.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 16. Decision Triggers
|
|
||||||
|
|
||||||
Dopo PoC, queste sono le decisioni discrete:
|
|
||||||
|
|
||||||
**GO al sistema completo se**:
|
|
||||||
- Swarm produce ≥5 strategie con DSR significativo dopo Adversarial
|
|
||||||
- Swarm batte baseline RF di ≥30% in best-DSR e diversity
|
|
||||||
- Strategie sopravvivono a OOS 2025 (regime change)
|
|
||||||
- Multi-tier ablation conferma valore (no significant loss usando 70% Tier-C)
|
|
||||||
|
|
||||||
**ITERATE PoC se**:
|
|
||||||
- Risultati borderline (alcuni indicatori sì, altri no)
|
|
||||||
- Bug specifici identificabili (es. GA non diversifica → fix speciation)
|
|
||||||
- Architettura sembra giusta ma implementazione perfettibile
|
|
||||||
|
|
||||||
**PIVOT se**:
|
|
||||||
- Swarm decisamente perde vs baseline su discovery numerica
|
|
||||||
- Ma: considerare pivot verso domini non-numerici (offerte commerciali, code review)
|
|
||||||
- O: considerare uso del swarm come *generator* di ipotesi macro/strutturali, non pattern numerici
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
*Documento da aggiornare durante PoC. Questa è v0.1, scritta prima di qualunque implementazione.*
|
|
||||||
*Documento principale (sistema completo): `coevolutive_swarm_system.md`*
|
|
||||||
+16
-26
@@ -1,27 +1,24 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "multi-swarm"
|
name = "multi-swarm-coevolutive"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
description = "Multi-Swarm Coevolutive PoC trading swarm — Phase 1 lean spike"
|
description = "Multi-Swarm Coevolutive: monorepo workspace (core + strategie)"
|
||||||
authors = [{ name = "Adriano Dal Pastro", email = "adrianodalpastro@tielogic.com" }]
|
authors = [{ name = "Adriano Dal Pastro", email = "adrianodalpastro@tielogic.com" }]
|
||||||
requires-python = ">=3.13"
|
requires-python = ">=3.13"
|
||||||
|
# I due workspace member sono dipendenze runtime del deployable app root.
|
||||||
|
# Cosi' `uv sync --frozen --no-dev` (nel builder Docker) li installa entrambi
|
||||||
|
# come editable nella venv senza tirare pytest/ruff/mypy.
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"pandas>=2.2",
|
"multi-swarm-core",
|
||||||
"numpy>=2.1",
|
"strategy-crypto",
|
||||||
"scipy>=1.14",
|
|
||||||
"pydantic>=2.9",
|
|
||||||
"pydantic-settings>=2.6",
|
|
||||||
"sqlmodel>=0.0.22",
|
|
||||||
"openai>=1.55",
|
|
||||||
"httpx>=0.28",
|
|
||||||
"requests>=2.32",
|
|
||||||
"tenacity>=9.0",
|
|
||||||
"pyyaml>=6.0",
|
|
||||||
"plotly>=5.24",
|
|
||||||
"pyarrow>=18.0",
|
|
||||||
"nicegui>=3.11.1",
|
|
||||||
"yfinance>=1.3.0",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[tool.uv.workspace]
|
||||||
|
members = ["src/multi_swarm_core", "src/strategy_crypto"]
|
||||||
|
|
||||||
|
[tool.uv.sources]
|
||||||
|
multi-swarm-core = { workspace = true }
|
||||||
|
strategy-crypto = { workspace = true }
|
||||||
|
|
||||||
[dependency-groups]
|
[dependency-groups]
|
||||||
dev = [
|
dev = [
|
||||||
"pytest>=8.3",
|
"pytest>=8.3",
|
||||||
@@ -33,13 +30,6 @@ dev = [
|
|||||||
"types-requests>=2.32",
|
"types-requests>=2.32",
|
||||||
]
|
]
|
||||||
|
|
||||||
[build-system]
|
|
||||||
requires = ["hatchling"]
|
|
||||||
build-backend = "hatchling.build"
|
|
||||||
|
|
||||||
[tool.hatch.build.targets.wheel]
|
|
||||||
packages = ["src/multi_swarm"]
|
|
||||||
|
|
||||||
[tool.ruff]
|
[tool.ruff]
|
||||||
line-length = 100
|
line-length = 100
|
||||||
target-version = "py313"
|
target-version = "py313"
|
||||||
@@ -52,8 +42,8 @@ python_version = "3.13"
|
|||||||
strict = true
|
strict = true
|
||||||
|
|
||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
testpaths = ["tests"]
|
testpaths = ["src/multi_swarm_core/tests", "src/strategy_crypto/tests"]
|
||||||
addopts = "-v --tb=short"
|
addopts = "-v --tb=short --import-mode=importlib"
|
||||||
markers = [
|
markers = [
|
||||||
"integration: tests that require external services (Cerbero, LLM API)",
|
"integration: tests that require external services (Cerbero, LLM API)",
|
||||||
"slow: tests that take more than 5 seconds",
|
"slow: tests that take more than 5 seconds",
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
"""Analisi per-trade dei top-K candidate del run BTC.
|
||||||
|
|
||||||
|
Per ciascun genome top-K, ri-esegue il backtest su ogni fold WFA e raccoglie:
|
||||||
|
- n_trades, n_wins, n_losses, win_rate
|
||||||
|
- max_drawdown
|
||||||
|
- return, sharpe
|
||||||
|
- list trade pnl summary
|
||||||
|
|
||||||
|
Output stampato a stdout, non scrive su disco.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import pandas as pd # type: ignore[import-untyped]
|
||||||
|
|
||||||
|
from multi_swarm_core.agents.hypothesis import _try_parse
|
||||||
|
from multi_swarm_core.backtest.engine import BacktestEngine
|
||||||
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
|
from multi_swarm_core.config import load_settings
|
||||||
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
|
from multi_swarm_core.data.splits import expanding_walk_forward
|
||||||
|
from multi_swarm_core.metrics.basic import max_drawdown, sharpe_ratio, total_return
|
||||||
|
from multi_swarm_core.persistence.repository import Repository
|
||||||
|
from multi_swarm_core.protocol.compiler import compile_strategy
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--run-id", required=True)
|
||||||
|
ap.add_argument("--top-k", type=int, default=10)
|
||||||
|
ap.add_argument("--n-folds", type=int, default=4)
|
||||||
|
ap.add_argument("--train-ratio", type=float, default=0.5)
|
||||||
|
ap.add_argument("--symbol", default="BTC-PERPETUAL")
|
||||||
|
ap.add_argument("--timeframe", default="1h")
|
||||||
|
ap.add_argument("--start", default="2018-09-01T00:00:00+00:00")
|
||||||
|
ap.add_argument("--end", default="2026-01-01T00:00:00+00:00")
|
||||||
|
ap.add_argument("--fees-bp", type=float, default=5.0)
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
settings = load_settings()
|
||||||
|
repo = Repository(settings.ga_db_path)
|
||||||
|
repo.init_schema()
|
||||||
|
all_evals = repo.list_evaluations(args.run_id)
|
||||||
|
parseable = [
|
||||||
|
e for e in all_evals
|
||||||
|
if e.get("raw_text") and not e.get("parse_error") and e["fitness"] > 0
|
||||||
|
]
|
||||||
|
parseable.sort(key=lambda e: e["fitness"], reverse=True)
|
||||||
|
seen: set[str] = set()
|
||||||
|
top: list[dict] = []
|
||||||
|
for e in parseable:
|
||||||
|
if e["genome_id"] in seen:
|
||||||
|
continue
|
||||||
|
seen.add(e["genome_id"])
|
||||||
|
top.append(e)
|
||||||
|
if len(top) >= args.top_k:
|
||||||
|
break
|
||||||
|
|
||||||
|
token = (
|
||||||
|
settings.cerbero_mainnet_token.get_secret_value()
|
||||||
|
if settings.cerbero_mainnet_token
|
||||||
|
else settings.cerbero_testnet_token.get_secret_value()
|
||||||
|
)
|
||||||
|
cerbero = CerberoClient(
|
||||||
|
base_url=settings.cerbero_base_url,
|
||||||
|
token=token,
|
||||||
|
bot_tag=settings.cerbero_bot_tag,
|
||||||
|
)
|
||||||
|
loader = CerberoOHLCVLoader(client=cerbero, cache_dir=settings.series_dir)
|
||||||
|
ohlcv = loader.load(OHLCVRequest(
|
||||||
|
symbol=args.symbol,
|
||||||
|
timeframe=args.timeframe,
|
||||||
|
start=datetime.fromisoformat(args.start),
|
||||||
|
end=datetime.fromisoformat(args.end),
|
||||||
|
))
|
||||||
|
splits = expanding_walk_forward(ohlcv.index, train_ratio=args.train_ratio, n_folds=args.n_folds)
|
||||||
|
engine = BacktestEngine(fees_bp=args.fees_bp)
|
||||||
|
|
||||||
|
print(f"\n{'=' * 110}")
|
||||||
|
print(f"PER-TRADE ANALYSIS — top-{len(top)} genomes × {len(splits)} folds")
|
||||||
|
print(f"{'=' * 110}")
|
||||||
|
|
||||||
|
for ev in top:
|
||||||
|
strat, err = _try_parse(ev["raw_text"] or "")
|
||||||
|
if strat is None:
|
||||||
|
print(f"\n>>> {ev['genome_id'][:16]} — parse error: {err}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
print(f"\n>>> {ev['genome_id']} (fit_IS={ev['fitness']:.4f}, sharpe_IS={ev['sharpe']:.3f})")
|
||||||
|
print(f"{'fold':<5} {'period':<26} {'trades':>7} {'wins':>5} {'losses':>7} {'win%':>6} {'avg_w':>9} {'avg_l':>9} {'ret':>7} {'maxDD':>7} {'sharpe':>7}")
|
||||||
|
for s in splits:
|
||||||
|
test_df = ohlcv.loc[s.test_idx]
|
||||||
|
try:
|
||||||
|
signal_fn = compile_strategy(strat)
|
||||||
|
signals = signal_fn(test_df)
|
||||||
|
bt = engine.run(test_df, signals)
|
||||||
|
except Exception as e:
|
||||||
|
print(f" fold {s.fold}: error {e}")
|
||||||
|
continue
|
||||||
|
trades = bt.trades
|
||||||
|
n_trades = len(trades)
|
||||||
|
wins = [t.net_pnl for t in trades if t.net_pnl > 0]
|
||||||
|
losses = [t.net_pnl for t in trades if t.net_pnl <= 0]
|
||||||
|
n_wins = len(wins)
|
||||||
|
n_losses = len(losses)
|
||||||
|
win_rate = (n_wins / n_trades * 100) if n_trades else 0.0
|
||||||
|
avg_w = (sum(wins) / n_wins) if n_wins else 0.0
|
||||||
|
avg_l = (sum(losses) / n_losses) if n_losses else 0.0
|
||||||
|
# Normalize equity for DD/return
|
||||||
|
if n_trades > 0:
|
||||||
|
notional = float(test_df["close"].iloc[0])
|
||||||
|
equity_pos = (bt.equity_curve / notional) + 1.0
|
||||||
|
ret_pct = total_return(equity_pos)
|
||||||
|
dd = max_drawdown(equity_pos)
|
||||||
|
sr = sharpe_ratio(bt.returns, periods_per_year=8760)
|
||||||
|
else:
|
||||||
|
ret_pct = dd = sr = 0.0
|
||||||
|
period = f"{str(s.test_idx[0])[:10]}..{str(s.test_idx[-1])[:10]}"
|
||||||
|
print(f"{s.fold:<5} {period:<26} {n_trades:>7} {n_wins:>5} {n_losses:>7} {win_rate:>5.1f}% {avg_w:>9.1f} {avg_l:>9.1f} {ret_pct:>6.2%} {dd:>6.2%} {sr:>7.3f}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -17,13 +17,13 @@ import math
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from multi_swarm.agents.adversarial import AdversarialAgent
|
from multi_swarm_core.agents.adversarial import AdversarialAgent
|
||||||
from multi_swarm.agents.falsification import FalsificationAgent
|
from multi_swarm_core.agents.falsification import FalsificationAgent
|
||||||
from multi_swarm.cerbero.client import CerberoClient
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
from multi_swarm.config import load_settings
|
from multi_swarm_core.config import load_settings
|
||||||
from multi_swarm.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
from multi_swarm.protocol.parser import parse_strategy
|
from multi_swarm_core.protocol.parser import parse_strategy
|
||||||
from multi_swarm.protocol.validator import validate_strategy
|
from multi_swarm_core.protocol.validator import validate_strategy
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""Confronto per-trade dei 4 winner cross-run (BTC/ETH × 1h/5m).
|
||||||
|
|
||||||
|
Per ogni winner: ri-esegue il backtest su 4 fold WFA expanding-window e raccoglie
|
||||||
|
trade buoni/non buoni, win-rate, avg PnL, return, max DD, Sharpe.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import pandas as pd # type: ignore[import-untyped]
|
||||||
|
|
||||||
|
from multi_swarm_core.agents.hypothesis import _try_parse
|
||||||
|
from multi_swarm_core.backtest.engine import BacktestEngine
|
||||||
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
|
from multi_swarm_core.config import load_settings
|
||||||
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
|
from multi_swarm_core.data.splits import expanding_walk_forward
|
||||||
|
from multi_swarm_core.metrics.basic import max_drawdown, sharpe_ratio, total_return
|
||||||
|
from multi_swarm_core.persistence.repository import Repository
|
||||||
|
from multi_swarm_core.protocol.compiler import compile_strategy
|
||||||
|
|
||||||
|
|
||||||
|
# (run_name, genome_id, symbol, timeframe, label)
|
||||||
|
WINNERS = [
|
||||||
|
("phase1-btc-100-001", "238e481262c1594c", "BTC-PERPETUAL", "1h", "BTC 1h sharpshooter (Gen 7)"),
|
||||||
|
("phase1-btc-100-001", "23a24989e2ed0f84", "BTC-PERPETUAL", "1h", "BTC 1h robust (Gen 0 elite)"),
|
||||||
|
("phase1-eth-100-001", "4b45a72c13acf1d5", "ETH-PERPETUAL", "1h", "ETH 1h best-by-sharpe (killed)"),
|
||||||
|
("phase1-btc-100-5m-001", "f8ca6642adf7e0cd", "BTC-PERPETUAL", "5m", "BTC 5m robust winner"),
|
||||||
|
("phase1-eth-100-5m-001", "c04dff7086bb9588", "ETH-PERPETUAL", "5m", "ETH 5m OOS winner"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def analyze_genome(run_id: str, genome_id: str, symbol: str, timeframe: str, label: str,
|
||||||
|
settings, cerbero, loader) -> None:
|
||||||
|
repo = Repository(settings.ga_db_path)
|
||||||
|
repo.init_schema()
|
||||||
|
evs = [e for e in repo.list_evaluations(run_id) if e["genome_id"] == genome_id]
|
||||||
|
if not evs:
|
||||||
|
print(f" no eval for {genome_id} in {run_id}")
|
||||||
|
return
|
||||||
|
ev = evs[0]
|
||||||
|
strat, err = _try_parse(ev.get("raw_text") or "")
|
||||||
|
if strat is None:
|
||||||
|
print(f" parse error: {err}")
|
||||||
|
return
|
||||||
|
|
||||||
|
req = OHLCVRequest(
|
||||||
|
symbol=symbol, timeframe=timeframe,
|
||||||
|
start=datetime.fromisoformat("2018-09-01T00:00:00+00:00"),
|
||||||
|
end=datetime.fromisoformat("2026-01-01T00:00:00+00:00"),
|
||||||
|
)
|
||||||
|
ohlcv = loader.load(req)
|
||||||
|
splits = expanding_walk_forward(ohlcv.index, train_ratio=0.5, n_folds=4)
|
||||||
|
engine = BacktestEngine(fees_bp=5.0)
|
||||||
|
|
||||||
|
print(f"\n>>> {label}")
|
||||||
|
print(f" {genome_id} | fit_IS={ev['fitness']:.4f} sharpe_IS={ev['sharpe']:.3f} trades_IS={ev['n_trades']}")
|
||||||
|
print(f" {'fold':<5} {'period':<26} {'trades':>7} {'wins':>5} {'losses':>7} {'win%':>6} {'avg_w':>10} {'avg_l':>10} {'ret':>8} {'maxDD':>7} {'sharpe':>7}")
|
||||||
|
|
||||||
|
sum_ret = 0.0
|
||||||
|
sum_trades = 0
|
||||||
|
sum_wins = 0
|
||||||
|
for s in splits:
|
||||||
|
test_df = ohlcv.loc[s.test_idx]
|
||||||
|
try:
|
||||||
|
signal_fn = compile_strategy(strat)
|
||||||
|
signals = signal_fn(test_df)
|
||||||
|
bt = engine.run(test_df, signals)
|
||||||
|
except Exception as e:
|
||||||
|
print(f" fold {s.fold}: error {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
trades = bt.trades
|
||||||
|
n = len(trades)
|
||||||
|
wins = [t.net_pnl for t in trades if t.net_pnl > 0]
|
||||||
|
losses = [t.net_pnl for t in trades if t.net_pnl <= 0]
|
||||||
|
nw, nl = len(wins), len(losses)
|
||||||
|
wr = (nw / n * 100) if n else 0.0
|
||||||
|
aw = (sum(wins) / nw) if nw else 0.0
|
||||||
|
al = (sum(losses) / nl) if nl else 0.0
|
||||||
|
if n > 0:
|
||||||
|
notional = float(test_df["close"].iloc[0])
|
||||||
|
eq = (bt.equity_curve / notional) + 1.0
|
||||||
|
ret = total_return(eq)
|
||||||
|
dd = max_drawdown(eq)
|
||||||
|
sr = sharpe_ratio(bt.returns, periods_per_year=8760)
|
||||||
|
else:
|
||||||
|
ret = dd = sr = 0.0
|
||||||
|
period = f"{str(s.test_idx[0])[:10]}..{str(s.test_idx[-1])[:10]}"
|
||||||
|
print(f" {s.fold:<5} {period:<26} {n:>7} {nw:>5} {nl:>7} {wr:>5.1f}% {aw:>10.1f} {al:>10.1f} {ret:>7.2%} {dd:>6.2%} {sr:>7.3f}")
|
||||||
|
sum_ret += ret
|
||||||
|
sum_trades += n
|
||||||
|
sum_wins += nw
|
||||||
|
overall_wr = (sum_wins / sum_trades * 100) if sum_trades else 0.0
|
||||||
|
print(f" {'='*5} TOTALS: {sum_trades:>7} {sum_wins:>5} {sum_trades-sum_wins:>7} {overall_wr:>5.1f}% cum_ret={sum_ret:+.2%}")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
settings = load_settings()
|
||||||
|
repo = Repository(settings.ga_db_path)
|
||||||
|
repo.init_schema()
|
||||||
|
name_to_id: dict[str, str] = {}
|
||||||
|
for w in WINNERS:
|
||||||
|
run_name = w[0]
|
||||||
|
if run_name in name_to_id:
|
||||||
|
continue
|
||||||
|
runs = repo.list_runs()
|
||||||
|
for r in runs:
|
||||||
|
if r["name"] == run_name:
|
||||||
|
name_to_id[run_name] = r["id"]
|
||||||
|
break
|
||||||
|
|
||||||
|
token = (
|
||||||
|
settings.cerbero_mainnet_token.get_secret_value()
|
||||||
|
if settings.cerbero_mainnet_token
|
||||||
|
else settings.cerbero_testnet_token.get_secret_value()
|
||||||
|
)
|
||||||
|
cerbero = CerberoClient(
|
||||||
|
base_url=settings.cerbero_base_url,
|
||||||
|
token=token,
|
||||||
|
bot_tag=settings.cerbero_bot_tag,
|
||||||
|
)
|
||||||
|
loader = CerberoOHLCVLoader(client=cerbero, cache_dir=settings.series_dir)
|
||||||
|
|
||||||
|
print(f"{'='*120}")
|
||||||
|
print(f"PER-TRADE COMPARISON — {len(WINNERS)} winner candidates × 4 folds WFA")
|
||||||
|
print(f"{'='*120}")
|
||||||
|
|
||||||
|
for run_name, genome_id, symbol, timeframe, label in WINNERS:
|
||||||
|
run_id = name_to_id.get(run_name)
|
||||||
|
if not run_id:
|
||||||
|
print(f"!!! run not found: {run_name}")
|
||||||
|
continue
|
||||||
|
analyze_genome(run_id, genome_id, symbol, timeframe, label, settings, cerbero, loader)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""2 winner cross-tick: BTC 238e4812 + ETH c04dff7086 su 5m / 15m / 1h.
|
||||||
|
|
||||||
|
Per ogni combinazione strategy × timeframe: backtest year-by-year (2019-2025)
|
||||||
|
con metriche per-anno e totale 7y.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from multi_swarm_core.backtest.engine import BacktestEngine
|
||||||
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
|
from multi_swarm_core.config import load_settings
|
||||||
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
|
from multi_swarm_core.metrics.basic import max_drawdown, sharpe_ratio, total_return
|
||||||
|
from multi_swarm_core.protocol.compiler import compile_strategy
|
||||||
|
from multi_swarm_core.protocol.parser import parse_strategy
|
||||||
|
|
||||||
|
|
||||||
|
WINNERS = [
|
||||||
|
# (label, path, symbol)
|
||||||
|
("BTC NEW (238e4812, native=1h)", "btc_238e4812.json", "BTC-PERPETUAL"),
|
||||||
|
("ETH NEW (c04dff7086, native=5m)", "eth_c04dff7086.json", "ETH-PERPETUAL"),
|
||||||
|
]
|
||||||
|
TIMEFRAMES = ["5m", "15m", "1h"]
|
||||||
|
|
||||||
|
YEARS = [
|
||||||
|
("2019", "2019-01-01T00:00:00+00:00", "2020-01-01T00:00:00+00:00"),
|
||||||
|
("2020", "2020-01-01T00:00:00+00:00", "2021-01-01T00:00:00+00:00"),
|
||||||
|
("2021", "2021-01-01T00:00:00+00:00", "2022-01-01T00:00:00+00:00"),
|
||||||
|
("2022", "2022-01-01T00:00:00+00:00", "2023-01-01T00:00:00+00:00"),
|
||||||
|
("2023", "2023-01-01T00:00:00+00:00", "2024-01-01T00:00:00+00:00"),
|
||||||
|
("2024", "2024-01-01T00:00:00+00:00", "2025-01-01T00:00:00+00:00"),
|
||||||
|
("2025", "2025-01-01T00:00:00+00:00", "2026-01-01T00:00:00+00:00"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(strat, ohlcv, engine, label, tf) -> None:
|
||||||
|
print(f"\n >>> tick={tf} | {len(ohlcv)} bars")
|
||||||
|
print(f" {'year':<6} {'trades':>7} {'wins':>5} {'losses':>7} {'win%':>6} {'ret':>8} {'maxDD':>7} {'sharpe':>7}")
|
||||||
|
sum_ret = 0.0
|
||||||
|
sum_trades = 0
|
||||||
|
sum_wins = 0
|
||||||
|
for year_label, start, end in YEARS:
|
||||||
|
mask = (ohlcv.index >= datetime.fromisoformat(start)) & (ohlcv.index < datetime.fromisoformat(end))
|
||||||
|
slice_df = ohlcv[mask]
|
||||||
|
if len(slice_df) == 0:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
signal_fn = compile_strategy(strat)
|
||||||
|
signals = signal_fn(slice_df)
|
||||||
|
bt = engine.run(slice_df, signals)
|
||||||
|
except Exception as e:
|
||||||
|
print(f" {year_label:<6} ERROR: {e}")
|
||||||
|
continue
|
||||||
|
trades = bt.trades
|
||||||
|
n = len(trades)
|
||||||
|
wins = [t.net_pnl for t in trades if t.net_pnl > 0]
|
||||||
|
losses = [t.net_pnl for t in trades if t.net_pnl <= 0]
|
||||||
|
nw, nl = len(wins), len(losses)
|
||||||
|
wr = (nw / n * 100) if n else 0.0
|
||||||
|
if n > 0:
|
||||||
|
notional = float(slice_df["close"].iloc[0])
|
||||||
|
eq = (bt.equity_curve / notional) + 1.0
|
||||||
|
ret = total_return(eq)
|
||||||
|
dd = max_drawdown(eq)
|
||||||
|
sr = sharpe_ratio(bt.returns, periods_per_year=8760)
|
||||||
|
else:
|
||||||
|
ret = dd = sr = 0.0
|
||||||
|
print(f" {year_label:<6} {n:>7} {nw:>5} {nl:>7} {wr:>5.1f}% {ret:>7.2%} {dd:>6.2%} {sr:>7.3f}")
|
||||||
|
sum_ret += ret
|
||||||
|
sum_trades += n
|
||||||
|
sum_wins += nw
|
||||||
|
overall_wr = (sum_wins / sum_trades * 100) if sum_trades else 0.0
|
||||||
|
print(f" ===== 7y TOT: {sum_trades:>7} {sum_wins:>5} {sum_trades-sum_wins:>7} {overall_wr:>5.1f}% cum_ret={sum_ret:+.2%}")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
settings = load_settings()
|
||||||
|
token = (
|
||||||
|
settings.cerbero_mainnet_token.get_secret_value()
|
||||||
|
if settings.cerbero_mainnet_token
|
||||||
|
else settings.cerbero_testnet_token.get_secret_value()
|
||||||
|
)
|
||||||
|
cerbero = CerberoClient(
|
||||||
|
base_url=settings.cerbero_base_url,
|
||||||
|
token=token,
|
||||||
|
bot_tag=settings.cerbero_bot_tag,
|
||||||
|
)
|
||||||
|
loader = CerberoOHLCVLoader(client=cerbero, cache_dir=settings.series_dir)
|
||||||
|
engine = BacktestEngine(fees_bp=5.0)
|
||||||
|
strategies_dir = Path("/app/strategies")
|
||||||
|
|
||||||
|
for label, fname, symbol in WINNERS:
|
||||||
|
path = strategies_dir / fname
|
||||||
|
strat = parse_strategy(path.read_text())
|
||||||
|
print(f"\n{'='*100}")
|
||||||
|
print(f">>> {label} — symbol={symbol}")
|
||||||
|
for tf in TIMEFRAMES:
|
||||||
|
try:
|
||||||
|
ohlcv = loader.load(OHLCVRequest(
|
||||||
|
symbol=symbol, timeframe=tf,
|
||||||
|
start=datetime.fromisoformat("2018-09-01T00:00:00+00:00"),
|
||||||
|
end=datetime.fromisoformat("2026-01-01T00:00:00+00:00"),
|
||||||
|
))
|
||||||
|
evaluate(strat, ohlcv, engine, label, tf)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n >>> tick={tf} FAILED TO LOAD: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
"""Replay diagnostico: per ciascuna strategia conta quanti bar avrebbero
|
||||||
|
soddisfatto le condizioni di ciascuna regola sull'ultimo `--days` di storico.
|
||||||
|
|
||||||
|
Ouput tabellare per branch: total_bars, fires, fire_rate, primo/ultimo fire.
|
||||||
|
Esegue anche un backtest grezzo (entry-on-signal, exit-on-flat) per stimare
|
||||||
|
n_trades e total_return realistici nel periodo.
|
||||||
|
|
||||||
|
Esempio:
|
||||||
|
docker compose exec multi-swarm-paper \
|
||||||
|
python /app/scripts/replay_strategies_window.py --days 30
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
|
from multi_swarm_core.config import load_settings
|
||||||
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
|
from multi_swarm_core.protocol.compiler import _eval_node, compile_strategy
|
||||||
|
from multi_swarm_core.protocol.parser import parse_strategy
|
||||||
|
|
||||||
|
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
p = argparse.ArgumentParser()
|
||||||
|
p.add_argument("--days", type=int, default=30)
|
||||||
|
p.add_argument("--strategies-dir", default=str(PROJECT_ROOT / "strategies"))
|
||||||
|
return p.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_window(loader: CerberoOHLCVLoader, symbol: str, days: int) -> pd.DataFrame:
|
||||||
|
end = datetime.now(UTC).replace(minute=0, second=0, microsecond=0)
|
||||||
|
start = end - timedelta(days=days)
|
||||||
|
req = OHLCVRequest(
|
||||||
|
symbol=symbol, timeframe="1h", start=start, end=end, exchange="deribit"
|
||||||
|
)
|
||||||
|
return loader._fetch(req) # noqa: SLF001 — bypass cache
|
||||||
|
|
||||||
|
|
||||||
|
def per_branch_fires(strategy_path: Path, ohlcv: pd.DataFrame) -> list[dict]:
|
||||||
|
raw = strategy_path.read_text()
|
||||||
|
parsed = parse_strategy(raw)
|
||||||
|
out = []
|
||||||
|
for idx, rule in enumerate(parsed.rules):
|
||||||
|
cond_series = _eval_node(rule.condition, ohlcv).fillna(False).astype(bool)
|
||||||
|
n = int(cond_series.sum())
|
||||||
|
first = ohlcv.index[cond_series.argmax()] if n > 0 else None
|
||||||
|
# last fire: argmax on reversed
|
||||||
|
last = ohlcv.index[len(cond_series) - 1 - cond_series[::-1].argmax()] if n > 0 else None
|
||||||
|
out.append({
|
||||||
|
"branch_idx": idx,
|
||||||
|
"action": rule.action,
|
||||||
|
"fires": n,
|
||||||
|
"fire_rate_pct": round(100.0 * n / len(ohlcv), 2),
|
||||||
|
"first_fire": first,
|
||||||
|
"last_fire": last,
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def quick_pnl(strategy_path: Path, ohlcv: pd.DataFrame, fees_bp: float = 5.0) -> dict:
|
||||||
|
"""Approx: at each bar evaluate compiled signal series (long/short/flat),
|
||||||
|
apply position to next-bar return, charge fees on changes. No leverage."""
|
||||||
|
raw = strategy_path.read_text()
|
||||||
|
parsed = parse_strategy(raw)
|
||||||
|
sig_fn = compile_strategy(parsed)
|
||||||
|
signals = sig_fn(ohlcv) # series of "long"/"short"/"flat"
|
||||||
|
# map to position: long=+1, short=-1, flat=0
|
||||||
|
pos = signals.map({"long": 1, "short": -1, "flat": 0}).fillna(0).astype(int)
|
||||||
|
rets = ohlcv["close"].pct_change().fillna(0.0)
|
||||||
|
# next-bar execution: position decided at bar t applies to return t+1 -> shift
|
||||||
|
pnl = pos.shift(1).fillna(0) * rets
|
||||||
|
# fees on position changes
|
||||||
|
changes = pos.diff().abs().fillna(0).astype(int)
|
||||||
|
fee_per_change = fees_bp / 10_000.0
|
||||||
|
pnl_after_fees = pnl - changes * fee_per_change
|
||||||
|
cum = (1 + pnl_after_fees).prod() - 1
|
||||||
|
n_trades = int((changes > 0).sum())
|
||||||
|
time_in_market = float((pos != 0).mean())
|
||||||
|
return {
|
||||||
|
"n_trades": n_trades,
|
||||||
|
"total_return_pct": round(100.0 * float(cum), 3),
|
||||||
|
"time_in_market_pct": round(100.0 * time_in_market, 2),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
args = parse_args()
|
||||||
|
settings = load_settings()
|
||||||
|
token = (
|
||||||
|
settings.cerbero_mainnet_token.get_secret_value()
|
||||||
|
if settings.cerbero_mainnet_token
|
||||||
|
else settings.cerbero_testnet_token.get_secret_value()
|
||||||
|
)
|
||||||
|
cerbero = CerberoClient(
|
||||||
|
base_url=settings.cerbero_base_url,
|
||||||
|
token=token,
|
||||||
|
bot_tag=settings.cerbero_bot_tag,
|
||||||
|
)
|
||||||
|
loader = CerberoOHLCVLoader(client=cerbero, cache_dir=settings.series_dir)
|
||||||
|
|
||||||
|
strategies_dir = Path(args.strategies_dir)
|
||||||
|
pairs = [
|
||||||
|
("BTC-PERPETUAL", sorted(strategies_dir.glob("btc_*.json"))[0]),
|
||||||
|
("ETH-PERPETUAL", sorted(strategies_dir.glob("eth_*.json"))[0]),
|
||||||
|
]
|
||||||
|
|
||||||
|
for symbol, strat_path in pairs:
|
||||||
|
print(f"\n=== {symbol} strategy={strat_path.name} window={args.days}d ===")
|
||||||
|
ohlcv = fetch_window(loader, symbol, args.days)
|
||||||
|
print(f"bars: {len(ohlcv)} range: {ohlcv.index[0]} -> {ohlcv.index[-1]}")
|
||||||
|
print("\n-- per branch --")
|
||||||
|
for row in per_branch_fires(strat_path, ohlcv):
|
||||||
|
print(json.dumps(row, default=str))
|
||||||
|
print("\n-- quick pnl (next-bar exec, fees=5bp) --")
|
||||||
|
print(json.dumps(quick_pnl(strat_path, ohlcv), default=str))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -20,22 +20,25 @@ Esempio:
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import importlib.resources
|
||||||
import time
|
import time
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import UTC, datetime, timedelta
|
from datetime import UTC, datetime, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from multi_swarm.cerbero.client import CerberoClient
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
from multi_swarm.config import load_settings
|
from multi_swarm_core.config import load_settings
|
||||||
from multi_swarm.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
from multi_swarm.paper_trading.executor import PaperExecutor
|
from strategy_crypto.backend import PaperExecutor, PaperRepository, Portfolio
|
||||||
from multi_swarm.paper_trading.persistence import PaperRepository
|
|
||||||
from multi_swarm.paper_trading.portfolio import Portfolio
|
|
||||||
from multi_swarm.persistence.repository import Repository
|
|
||||||
|
|
||||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
def _default_strategies_dir() -> Path:
|
||||||
|
"""Cartella JSON shippata col package strategy_crypto."""
|
||||||
|
return Path(str(importlib.resources.files("strategy_crypto") / "strategies"))
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class AssetConfig:
|
class AssetConfig:
|
||||||
symbol: str # es. "BTC-PERPETUAL"
|
symbol: str # es. "BTC-PERPETUAL"
|
||||||
@@ -54,8 +57,8 @@ def parse_args() -> argparse.Namespace:
|
|||||||
p.add_argument("--lookback-bars", type=int, default=500, help="Quante bar fetchare per indicatori")
|
p.add_argument("--lookback-bars", type=int, default=500, help="Quante bar fetchare per indicatori")
|
||||||
p.add_argument(
|
p.add_argument(
|
||||||
"--strategies-dir",
|
"--strategies-dir",
|
||||||
default=str(PROJECT_ROOT / "strategies"),
|
default=str(_default_strategies_dir()),
|
||||||
help="Cartella contenente btc_*.json e eth_*.json",
|
help="Cartella contenente btc_*.json e eth_*.json (default: package strategy_crypto/strategies)",
|
||||||
)
|
)
|
||||||
return p.parse_args()
|
return p.parse_args()
|
||||||
|
|
||||||
@@ -67,9 +70,11 @@ def load_assets(strategies_dir: Path) -> list[AssetConfig]:
|
|||||||
raise FileNotFoundError(
|
raise FileNotFoundError(
|
||||||
f"Expected btc_*.json and eth_*.json in {strategies_dir}"
|
f"Expected btc_*.json and eth_*.json in {strategies_dir}"
|
||||||
)
|
)
|
||||||
|
# ETH winner c04dff7086 e' tunato su 5m: a 1h la strategia perde (cum_ret -33% 7y).
|
||||||
|
# BTC winner 238e4812 e' tunato su 1h: tick native = paper tick.
|
||||||
return [
|
return [
|
||||||
AssetConfig(symbol="BTC-PERPETUAL", strategy_file=btc_files[0]),
|
AssetConfig(symbol="BTC-PERPETUAL", strategy_file=btc_files[0], timeframe="1h"),
|
||||||
AssetConfig(symbol="ETH-PERPETUAL", strategy_file=eth_files[0]),
|
AssetConfig(symbol="ETH-PERPETUAL", strategy_file=eth_files[0], timeframe="5m"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -77,9 +82,6 @@ def main() -> None:
|
|||||||
args = parse_args()
|
args = parse_args()
|
||||||
settings = load_settings()
|
settings = load_settings()
|
||||||
|
|
||||||
# Inizializza schema (idempotente).
|
|
||||||
Repository(settings.db_path).init_schema()
|
|
||||||
|
|
||||||
token = (
|
token = (
|
||||||
settings.cerbero_mainnet_token.get_secret_value()
|
settings.cerbero_mainnet_token.get_secret_value()
|
||||||
if settings.cerbero_mainnet_token
|
if settings.cerbero_mainnet_token
|
||||||
@@ -105,7 +107,8 @@ def main() -> None:
|
|||||||
fees_bp=args.fees_bp,
|
fees_bp=args.fees_bp,
|
||||||
n_sleeves=len(assets),
|
n_sleeves=len(assets),
|
||||||
)
|
)
|
||||||
repo = PaperRepository(settings.db_path)
|
repo = PaperRepository(settings.strategy_crypto_db_path)
|
||||||
|
repo.init_schema()
|
||||||
config = {
|
config = {
|
||||||
"assets": [
|
"assets": [
|
||||||
{"symbol": a.symbol, "strategy": a.strategy_file.name, "exchange": a.exchange}
|
{"symbol": a.symbol, "strategy": a.strategy_file.name, "exchange": a.exchange}
|
||||||
|
|||||||
+86
-12
@@ -1,14 +1,46 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import importlib.resources
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from multi_swarm.cerbero.client import CerberoClient
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
from multi_swarm.config import load_settings
|
from multi_swarm_core.config import load_settings
|
||||||
from multi_swarm.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
from multi_swarm.genome.hypothesis import ModelTier
|
from multi_swarm_core.genome.hypothesis import ModelTier
|
||||||
from multi_swarm.llm.client import LLMClient
|
from multi_swarm_core.genome.prompt_library import PromptLibrary
|
||||||
from multi_swarm.orchestrator.run import RunConfig, run_phase1
|
from multi_swarm_core.llm.client import LLMClient
|
||||||
|
from multi_swarm_core.orchestrator.run import RunConfig, run_phase1
|
||||||
|
|
||||||
|
|
||||||
|
def _default_prompt_library_path() -> Path:
|
||||||
|
"""Default: prompts.json shippato col package strategy_crypto."""
|
||||||
|
return Path(str(importlib.resources.files("strategy_crypto") / "prompts.json"))
|
||||||
|
|
||||||
|
|
||||||
|
# Default v2 hard-kill list: oltre ai degenerate originali, fees_eat_alpha e
|
||||||
|
# negative_net_pnl sono deal-breaker non recuperabili via soft penalty (vedi
|
||||||
|
# 7y-overfit incident 2026-05-16: elite IS Sharpe 1.93 -> net -5% su 7y per fees).
|
||||||
|
_DEFAULT_V2_HARD_KILL: tuple[str, ...] = (
|
||||||
|
"no_trades",
|
||||||
|
"degenerate",
|
||||||
|
"undertrading",
|
||||||
|
"fees_eat_alpha",
|
||||||
|
"negative_net_pnl",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_hard_kill(args) -> tuple[str, ...] | None:
|
||||||
|
"""Resolve la lista hard-kill da CLI args.
|
||||||
|
|
||||||
|
Priority: ``--fitness-hard-kill`` esplicito > default v2 > ``None`` (v1).
|
||||||
|
"""
|
||||||
|
if args.fitness_hard_kill:
|
||||||
|
return tuple(s.strip() for s in args.fitness_hard_kill.split(",") if s.strip())
|
||||||
|
if args.fitness_v2:
|
||||||
|
return _DEFAULT_V2_HARD_KILL
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def parse_args() -> argparse.Namespace:
|
def parse_args() -> argparse.Namespace:
|
||||||
@@ -27,7 +59,10 @@ def parse_args() -> argparse.Namespace:
|
|||||||
)
|
)
|
||||||
p.add_argument("--symbol", default="BTC-PERPETUAL")
|
p.add_argument("--symbol", default="BTC-PERPETUAL")
|
||||||
p.add_argument("--timeframe", default="1h")
|
p.add_argument("--timeframe", default="1h")
|
||||||
p.add_argument("--start", default="2024-01-01T00:00:00+00:00")
|
# Default esteso a 7.3 anni: copre bear 2018-19, halving 2020, COVID,
|
||||||
|
# ATH 2021, winter 2022, ETF rally 2024, regime corrente. Una finestra
|
||||||
|
# corta lascia il GA libero di overfit a un singolo regime.
|
||||||
|
p.add_argument("--start", default="2018-09-01T00:00:00+00:00")
|
||||||
p.add_argument("--end", default="2026-01-01T00:00:00+00:00")
|
p.add_argument("--end", default="2026-01-01T00:00:00+00:00")
|
||||||
p.add_argument("--fees-bp", type=float, default=5.0)
|
p.add_argument("--fees-bp", type=float, default=5.0)
|
||||||
p.add_argument("--n-trials-dsr", type=int, default=50)
|
p.add_argument("--n-trials-dsr", type=int, default=50)
|
||||||
@@ -59,8 +94,10 @@ def parse_args() -> argparse.Namespace:
|
|||||||
"--fitness-v2",
|
"--fitness-v2",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
help=(
|
help=(
|
||||||
"Attiva fitness v2: solo {no_trades, degenerate, undertrading} azzerano; "
|
"Attiva fitness v2: hard-kill su {no_trades, degenerate, undertrading, "
|
||||||
"gli altri HIGH applicano soft penalty multiplicativa"
|
"fees_eat_alpha, negative_net_pnl}; gli altri HIGH applicano soft penalty "
|
||||||
|
"multiplicativa. Versione hardened post 7y-overfit incident: fees + "
|
||||||
|
"net negativo non sono recuperabili."
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
p.add_argument(
|
p.add_argument(
|
||||||
@@ -69,6 +106,16 @@ def parse_args() -> argparse.Namespace:
|
|||||||
default=0.4,
|
default=0.4,
|
||||||
help="v2: fattore soft penalty per HIGH non-hard (default 0.4 → 1 HIGH → 0.71x)",
|
help="v2: fattore soft penalty per HIGH non-hard (default 0.4 → 1 HIGH → 0.71x)",
|
||||||
)
|
)
|
||||||
|
p.add_argument(
|
||||||
|
"--fitness-hard-kill",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help=(
|
||||||
|
"Override comma-separated della lista di finding name che azzerano la "
|
||||||
|
"fitness in modalita' v2. Es: 'no_trades,degenerate'. Default v2: "
|
||||||
|
"no_trades,degenerate,undertrading,fees_eat_alpha,negative_net_pnl."
|
||||||
|
),
|
||||||
|
)
|
||||||
p.add_argument(
|
p.add_argument(
|
||||||
"--wfa-train-split",
|
"--wfa-train-split",
|
||||||
type=float,
|
type=float,
|
||||||
@@ -96,6 +143,26 @@ def parse_args() -> argparse.Namespace:
|
|||||||
default=0.5,
|
default=0.5,
|
||||||
help="Multi-objective: peso IS (1-alpha = OOS). 1.0=solo IS, 0.5=bilanciato, 0.0=solo OOS",
|
help="Multi-objective: peso IS (1-alpha = OOS). 1.0=solo IS, 0.5=bilanciato, 0.0=solo OOS",
|
||||||
)
|
)
|
||||||
|
p.add_argument(
|
||||||
|
"--prompt-library",
|
||||||
|
type=Path,
|
||||||
|
default=None,
|
||||||
|
help=(
|
||||||
|
"Path al file JSON con stili cognitivi + direttive system_prompt. "
|
||||||
|
"Default: strategy_crypto/prompts.json shippato col package. "
|
||||||
|
"Schema: {styles: {<name>: {directive: <testo>}}}"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
p.add_argument(
|
||||||
|
"--llm-concurrency",
|
||||||
|
type=int,
|
||||||
|
default=1,
|
||||||
|
help=(
|
||||||
|
"Numero di propose() LLM concorrenti per generazione (default 1 = "
|
||||||
|
"serial). 6-10 tipicamente accettati da OpenRouter qwen-2.5 senza "
|
||||||
|
"rate-limit; riduce wall time GA loop di 5-8x."
|
||||||
|
),
|
||||||
|
)
|
||||||
return p.parse_args()
|
return p.parse_args()
|
||||||
|
|
||||||
|
|
||||||
@@ -103,6 +170,13 @@ def main() -> None:
|
|||||||
args = parse_args()
|
args = parse_args()
|
||||||
settings = load_settings()
|
settings = load_settings()
|
||||||
|
|
||||||
|
prompt_lib_path = args.prompt_library or _default_prompt_library_path()
|
||||||
|
prompt_library = PromptLibrary.from_json(prompt_lib_path)
|
||||||
|
print(
|
||||||
|
f"PromptLibrary loaded from {prompt_lib_path}: "
|
||||||
|
f"{len(prompt_library.styles)} stili ({', '.join(prompt_library.cognitive_styles)})"
|
||||||
|
)
|
||||||
|
|
||||||
token = (
|
token = (
|
||||||
settings.cerbero_mainnet_token.get_secret_value()
|
settings.cerbero_mainnet_token.get_secret_value()
|
||||||
if settings.cerbero_mainnet_token
|
if settings.cerbero_mainnet_token
|
||||||
@@ -153,14 +227,14 @@ def main() -> None:
|
|||||||
fees_eat_alpha_threshold=args.fees_eat_alpha_threshold,
|
fees_eat_alpha_threshold=args.fees_eat_alpha_threshold,
|
||||||
flat_too_long_threshold=args.flat_too_long_threshold,
|
flat_too_long_threshold=args.flat_too_long_threshold,
|
||||||
undertrading_threshold=args.undertrading_threshold,
|
undertrading_threshold=args.undertrading_threshold,
|
||||||
fitness_hard_kill_findings=(
|
fitness_hard_kill_findings=_resolve_hard_kill(args),
|
||||||
("no_trades", "degenerate", "undertrading") if args.fitness_v2 else None
|
|
||||||
),
|
|
||||||
fitness_adversarial_soft_penalty=args.fitness_soft_penalty,
|
fitness_adversarial_soft_penalty=args.fitness_soft_penalty,
|
||||||
wfa_train_split=args.wfa_train_split,
|
wfa_train_split=args.wfa_train_split,
|
||||||
wfa_top_k=args.wfa_top_k,
|
wfa_top_k=args.wfa_top_k,
|
||||||
eval_oos_during_loop=args.eval_oos_during_loop,
|
eval_oos_during_loop=args.eval_oos_during_loop,
|
||||||
fitness_combined_alpha=args.fitness_combined_alpha,
|
fitness_combined_alpha=args.fitness_combined_alpha,
|
||||||
|
prompt_library=prompt_library,
|
||||||
|
llm_concurrency=args.llm_concurrency,
|
||||||
)
|
)
|
||||||
|
|
||||||
run_id = run_phase1(cfg, ohlcv=ohlcv, llm=llm)
|
run_id = run_phase1(cfg, ohlcv=ohlcv, llm=llm)
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ from pathlib import Path
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd # type: ignore[import-untyped]
|
import pandas as pd # type: ignore[import-untyped]
|
||||||
|
|
||||||
from multi_swarm.genome.hypothesis import HypothesisAgentGenome, ModelTier
|
from multi_swarm_core.genome.hypothesis import HypothesisAgentGenome, ModelTier
|
||||||
from multi_swarm.llm.client import CompletionResult
|
from multi_swarm_core.llm.client import CompletionResult
|
||||||
from multi_swarm.orchestrator.run import RunConfig, run_phase1
|
from multi_swarm_core.orchestrator.run import RunConfig, run_phase1
|
||||||
|
|
||||||
_MOCK_STRATEGY = json.dumps(
|
_MOCK_STRATEGY = json.dumps(
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,271 @@
|
|||||||
|
"""Multi-fold validation di un run esistente.
|
||||||
|
|
||||||
|
Prende un ``run_id`` da ``state/runs.db``, seleziona i top-K genomi per fitness IS,
|
||||||
|
e li rivaluta su N fold expanding-window di un dataset OHLCV (tipicamente piu'
|
||||||
|
lungo del train del GA). Output: per-fold + aggregati (mean / min / std) della
|
||||||
|
fitness OOS.
|
||||||
|
|
||||||
|
Use case: il GA puo' selezionare un "lucky-shot" overfit a uno specifico regime.
|
||||||
|
Validare i top-K su finestre temporali diverse rivela quali strategie sono
|
||||||
|
robuste vs overfitter.
|
||||||
|
|
||||||
|
Esempio::
|
||||||
|
|
||||||
|
python scripts/validate_run.py \\
|
||||||
|
--run-id e263651598894da688d95fda90a34a96 \\
|
||||||
|
--top-k 10 --n-folds 4 \\
|
||||||
|
--symbol BTC-PERPETUAL --timeframe 1h \\
|
||||||
|
--start 2018-09-01 --end 2026-01-01
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import statistics
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pandas as pd # type: ignore[import-untyped]
|
||||||
|
|
||||||
|
from multi_swarm_core.agents.adversarial import AdversarialAgent
|
||||||
|
from multi_swarm_core.agents.falsification import FalsificationAgent
|
||||||
|
from multi_swarm_core.agents.hypothesis import _try_parse
|
||||||
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
|
from multi_swarm_core.config import load_settings
|
||||||
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
|
from multi_swarm_core.data.splits import expanding_walk_forward
|
||||||
|
from multi_swarm_core.ga.fitness import compute_fitness
|
||||||
|
from multi_swarm_core.persistence.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
p = argparse.ArgumentParser(description="Multi-fold validation di top-K genomi")
|
||||||
|
p.add_argument("--run-id", required=True, help="run_id da validare")
|
||||||
|
p.add_argument("--top-k", type=int, default=10, help="quanti genomi top valutare")
|
||||||
|
p.add_argument("--n-folds", type=int, default=4, help="numero fold expanding-window")
|
||||||
|
p.add_argument(
|
||||||
|
"--train-ratio",
|
||||||
|
type=float,
|
||||||
|
default=0.5,
|
||||||
|
help="frazione iniziale per il train iniziale (folds testano la coda)",
|
||||||
|
)
|
||||||
|
p.add_argument("--symbol", default="BTC-PERPETUAL")
|
||||||
|
p.add_argument("--timeframe", default="1h")
|
||||||
|
p.add_argument("--exchange", default="deribit", choices=["deribit", "bybit", "hyperliquid"])
|
||||||
|
p.add_argument("--start", default="2018-09-01T00:00:00+00:00")
|
||||||
|
p.add_argument("--end", default="2026-01-01T00:00:00+00:00")
|
||||||
|
p.add_argument("--fees-bp", type=float, default=5.0)
|
||||||
|
p.add_argument("--n-trials-dsr", type=int, default=50)
|
||||||
|
p.add_argument(
|
||||||
|
"--fees-eat-alpha-threshold", type=float, default=0.5,
|
||||||
|
)
|
||||||
|
p.add_argument(
|
||||||
|
"--flat-too-long-threshold", type=float, default=0.95,
|
||||||
|
)
|
||||||
|
p.add_argument(
|
||||||
|
"--undertrading-threshold", type=int, default=10,
|
||||||
|
)
|
||||||
|
p.add_argument(
|
||||||
|
"--fitness-v2", action="store_true",
|
||||||
|
help="Coerente con --fitness-v2 del run originale",
|
||||||
|
)
|
||||||
|
p.add_argument(
|
||||||
|
"--fitness-soft-penalty", type=float, default=0.4,
|
||||||
|
)
|
||||||
|
p.add_argument(
|
||||||
|
"--output-json",
|
||||||
|
type=Path,
|
||||||
|
default=None,
|
||||||
|
help="Path JSON dove salvare i risultati (default: stdout solo)",
|
||||||
|
)
|
||||||
|
return p.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
args = parse_args()
|
||||||
|
settings = load_settings()
|
||||||
|
|
||||||
|
# Repository: top-K genomi per fitness IS, con raw_text parsable.
|
||||||
|
repo = Repository(settings.ga_db_path)
|
||||||
|
repo.init_schema()
|
||||||
|
run = repo.get_run(args.run_id)
|
||||||
|
if run is None:
|
||||||
|
raise SystemExit(f"run_id non trovato: {args.run_id}")
|
||||||
|
print(f"Validating run: {run['name']} ({args.run_id})")
|
||||||
|
print(f" status: {run['status']}, cost: ${run['total_cost_usd']:.4f}")
|
||||||
|
|
||||||
|
all_evals = repo.list_evaluations(args.run_id)
|
||||||
|
parseable = [
|
||||||
|
e for e in all_evals
|
||||||
|
if e.get("raw_text") and not e.get("parse_error") and e["fitness"] > 0
|
||||||
|
]
|
||||||
|
parseable.sort(key=lambda e: e["fitness"], reverse=True)
|
||||||
|
|
||||||
|
# Dedup by genome_id (gli elite vengono salvati una sola volta ma possono apparire
|
||||||
|
# in evaluations multiple se rivalutati con eval_oos_during_loop).
|
||||||
|
seen_ids: set[str] = set()
|
||||||
|
top_genomes: list[dict] = []
|
||||||
|
for e in parseable:
|
||||||
|
if e["genome_id"] in seen_ids:
|
||||||
|
continue
|
||||||
|
seen_ids.add(e["genome_id"])
|
||||||
|
top_genomes.append(e)
|
||||||
|
if len(top_genomes) >= args.top_k:
|
||||||
|
break
|
||||||
|
print(f" selected top-{len(top_genomes)} genomes for validation")
|
||||||
|
|
||||||
|
# OHLCV: carica il dataset esteso.
|
||||||
|
token = (
|
||||||
|
settings.cerbero_mainnet_token.get_secret_value()
|
||||||
|
if settings.cerbero_mainnet_token
|
||||||
|
else settings.cerbero_testnet_token.get_secret_value()
|
||||||
|
)
|
||||||
|
cerbero = CerberoClient(
|
||||||
|
base_url=settings.cerbero_base_url,
|
||||||
|
token=token,
|
||||||
|
bot_tag=settings.cerbero_bot_tag,
|
||||||
|
)
|
||||||
|
loader = CerberoOHLCVLoader(client=cerbero, cache_dir=settings.series_dir)
|
||||||
|
req = OHLCVRequest(
|
||||||
|
symbol=args.symbol,
|
||||||
|
timeframe=args.timeframe,
|
||||||
|
start=datetime.fromisoformat(args.start),
|
||||||
|
end=datetime.fromisoformat(args.end),
|
||||||
|
exchange=args.exchange,
|
||||||
|
)
|
||||||
|
ohlcv = loader.load(req)
|
||||||
|
print(f" OHLCV: {len(ohlcv)} bars from {ohlcv.index[0]} to {ohlcv.index[-1]}")
|
||||||
|
|
||||||
|
splits = expanding_walk_forward(
|
||||||
|
ohlcv.index, train_ratio=args.train_ratio, n_folds=args.n_folds,
|
||||||
|
)
|
||||||
|
print(f" generated {len(splits)} folds")
|
||||||
|
for s in splits:
|
||||||
|
print(f" fold {s.fold}: test [{s.test_idx[0]} -> {s.test_idx[-1]}] ({len(s.test_idx)} bars)")
|
||||||
|
|
||||||
|
fals_agent = FalsificationAgent(fees_bp=args.fees_bp, n_trials_dsr=args.n_trials_dsr)
|
||||||
|
adv_agent = AdversarialAgent(
|
||||||
|
fees_bp=args.fees_bp,
|
||||||
|
fees_eat_alpha_threshold=args.fees_eat_alpha_threshold,
|
||||||
|
flat_too_long_threshold=args.flat_too_long_threshold,
|
||||||
|
undertrading_threshold=args.undertrading_threshold,
|
||||||
|
)
|
||||||
|
hard_kill = (
|
||||||
|
("no_trades", "degenerate", "undertrading") if args.fitness_v2 else None
|
||||||
|
)
|
||||||
|
|
||||||
|
# Itera per ogni genome + fold.
|
||||||
|
results: list[dict] = []
|
||||||
|
for gi, ev in enumerate(top_genomes):
|
||||||
|
strategy, parse_err = _try_parse(ev["raw_text"] or "")
|
||||||
|
if strategy is None:
|
||||||
|
print(f" [{gi}] {ev['genome_id'][:12]} skip (parse error: {parse_err})")
|
||||||
|
continue
|
||||||
|
|
||||||
|
per_fold: list[dict] = []
|
||||||
|
for s in splits:
|
||||||
|
test_df = ohlcv.loc[s.test_idx]
|
||||||
|
try:
|
||||||
|
fals = fals_agent.evaluate(strategy, test_df)
|
||||||
|
adv = adv_agent.review(strategy, test_df)
|
||||||
|
fit = compute_fitness(
|
||||||
|
fals, adv,
|
||||||
|
hard_kill_findings=hard_kill,
|
||||||
|
adversarial_soft_penalty=args.fitness_soft_penalty,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
print(f" fold {s.fold} eval failed: {e}")
|
||||||
|
continue
|
||||||
|
per_fold.append({
|
||||||
|
"fold": s.fold,
|
||||||
|
"fitness": float(fit),
|
||||||
|
"sharpe": float(fals.sharpe),
|
||||||
|
"dsr": float(fals.dsr),
|
||||||
|
"dsr_pvalue": float(fals.dsr_pvalue),
|
||||||
|
"return": float(fals.total_return),
|
||||||
|
"max_dd": float(fals.max_drawdown),
|
||||||
|
"n_trades": int(fals.n_trades),
|
||||||
|
"test_start": str(s.test_idx[0]),
|
||||||
|
"test_end": str(s.test_idx[-1]),
|
||||||
|
})
|
||||||
|
|
||||||
|
if not per_fold:
|
||||||
|
continue
|
||||||
|
|
||||||
|
fits = [pf["fitness"] for pf in per_fold]
|
||||||
|
sharps = [pf["sharpe"] for pf in per_fold]
|
||||||
|
results.append({
|
||||||
|
"genome_id": ev["genome_id"],
|
||||||
|
"fitness_is": float(ev["fitness"]),
|
||||||
|
"sharpe_is": float(ev["sharpe"]),
|
||||||
|
"folds": per_fold,
|
||||||
|
"fitness_oos_mean": statistics.mean(fits),
|
||||||
|
"fitness_oos_min": min(fits),
|
||||||
|
"fitness_oos_max": max(fits),
|
||||||
|
"fitness_oos_std": statistics.pstdev(fits) if len(fits) > 1 else 0.0,
|
||||||
|
"sharpe_oos_mean": statistics.mean(sharps),
|
||||||
|
"sharpe_oos_min": min(sharps),
|
||||||
|
"robust_score": min(fits), # min across folds = pessimismo
|
||||||
|
})
|
||||||
|
|
||||||
|
# Ranking finale: per robust_score (min fitness) decrescente.
|
||||||
|
results.sort(key=lambda r: r["robust_score"], reverse=True)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(f"{'='*120}")
|
||||||
|
print(f"VALIDATION RESULTS ({len(results)} genomes, {len(splits)} folds)")
|
||||||
|
print(f"{'='*120}")
|
||||||
|
print(
|
||||||
|
f"{'rank':>4} {'genome':12} {'fit_is':>8} {'sh_is':>7} "
|
||||||
|
f"{'fit_mean':>9} {'fit_min':>8} {'fit_max':>8} {'fit_std':>8} "
|
||||||
|
f"{'sh_mean':>8} {'sh_min':>8} {'robust':>7}"
|
||||||
|
)
|
||||||
|
print("-" * 120)
|
||||||
|
for rank, r in enumerate(results, 1):
|
||||||
|
print(
|
||||||
|
f"{rank:>4} {r['genome_id'][:12]:12} "
|
||||||
|
f"{r['fitness_is']:>8.4f} {r['sharpe_is']:>7.3f} "
|
||||||
|
f"{r['fitness_oos_mean']:>9.4f} {r['fitness_oos_min']:>8.4f} "
|
||||||
|
f"{r['fitness_oos_max']:>8.4f} {r['fitness_oos_std']:>8.4f} "
|
||||||
|
f"{r['sharpe_oos_mean']:>8.3f} {r['sharpe_oos_min']:>8.3f} "
|
||||||
|
f"{r['robust_score']:>7.4f}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if results:
|
||||||
|
winner = results[0]
|
||||||
|
print()
|
||||||
|
print(f"ROBUST WINNER: {winner['genome_id']}")
|
||||||
|
print(f" fitness_is={winner['fitness_is']:.4f}, "
|
||||||
|
f"fitness_oos_min={winner['fitness_oos_min']:.4f}, "
|
||||||
|
f"fitness_oos_mean={winner['fitness_oos_mean']:.4f}")
|
||||||
|
print(f" sharpe_is={winner['sharpe_is']:.3f}, "
|
||||||
|
f"sharpe_oos_min={winner['sharpe_oos_min']:.3f}")
|
||||||
|
print(f" per-fold breakdown:")
|
||||||
|
for pf in winner["folds"]:
|
||||||
|
print(
|
||||||
|
f" fold {pf['fold']} [{pf['test_start'][:10]} .. {pf['test_end'][:10]}]: "
|
||||||
|
f"fit={pf['fitness']:.4f} sharpe={pf['sharpe']:.3f} "
|
||||||
|
f"ret={pf['return']:.3f} n_trades={pf['n_trades']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if args.output_json:
|
||||||
|
payload = {
|
||||||
|
"run_id": args.run_id,
|
||||||
|
"run_name": run["name"],
|
||||||
|
"n_folds": len(splits),
|
||||||
|
"top_k_requested": args.top_k,
|
||||||
|
"top_k_evaluated": len(results),
|
||||||
|
"symbol": args.symbol,
|
||||||
|
"timeframe": args.timeframe,
|
||||||
|
"start": args.start,
|
||||||
|
"end": args.end,
|
||||||
|
"ohlcv_bars": len(ohlcv),
|
||||||
|
"results": results,
|
||||||
|
}
|
||||||
|
args.output_json.write_text(json.dumps(payload, indent=2, default=str))
|
||||||
|
print(f"\nResults saved to: {args.output_json}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""Per-year breakdown delle 4 strategie: 2 NEW (BTC 238e4812 + ETH c04dff7086)
|
||||||
|
+ 2 OLD freezate (btc_9cf506b8 hardened-001 + eth_facd6af85d5d).
|
||||||
|
|
||||||
|
Backtest anno-per-anno (2019-2025) sul tick di discovery di ciascuna strategia.
|
||||||
|
Output: trade, wins/losses, win%, return%, max DD%, Sharpe per ogni anno.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from multi_swarm_core.backtest.engine import BacktestEngine
|
||||||
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
|
from multi_swarm_core.config import load_settings
|
||||||
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
|
from multi_swarm_core.metrics.basic import max_drawdown, sharpe_ratio, total_return
|
||||||
|
from multi_swarm_core.protocol.compiler import compile_strategy
|
||||||
|
from multi_swarm_core.protocol.parser import parse_strategy
|
||||||
|
|
||||||
|
|
||||||
|
STRATEGIES = [
|
||||||
|
# (label, path, symbol, timeframe)
|
||||||
|
("BTC NEW (238e4812, paper attuale)", "btc_238e4812.json", "BTC-PERPETUAL", "1h"),
|
||||||
|
("BTC OLD (9cf506b8, hardened-001 prev paper)", "archive/btc_9cf506b8.json", "BTC-PERPETUAL", "1h"),
|
||||||
|
("ETH NEW (c04dff7086, paper attuale)", "eth_c04dff7086.json", "ETH-PERPETUAL", "5m"),
|
||||||
|
("ETH OLD (facd6af85d5d, prev paper)", "archive/eth_facd6af85d5d.json", "ETH-PERPETUAL", "1h"),
|
||||||
|
]
|
||||||
|
|
||||||
|
YEARS = [
|
||||||
|
("2019", "2019-01-01T00:00:00+00:00", "2020-01-01T00:00:00+00:00"),
|
||||||
|
("2020", "2020-01-01T00:00:00+00:00", "2021-01-01T00:00:00+00:00"),
|
||||||
|
("2021", "2021-01-01T00:00:00+00:00", "2022-01-01T00:00:00+00:00"),
|
||||||
|
("2022", "2022-01-01T00:00:00+00:00", "2023-01-01T00:00:00+00:00"),
|
||||||
|
("2023", "2023-01-01T00:00:00+00:00", "2024-01-01T00:00:00+00:00"),
|
||||||
|
("2024", "2024-01-01T00:00:00+00:00", "2025-01-01T00:00:00+00:00"),
|
||||||
|
("2025", "2025-01-01T00:00:00+00:00", "2026-01-01T00:00:00+00:00"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
settings = load_settings()
|
||||||
|
token = (
|
||||||
|
settings.cerbero_mainnet_token.get_secret_value()
|
||||||
|
if settings.cerbero_mainnet_token
|
||||||
|
else settings.cerbero_testnet_token.get_secret_value()
|
||||||
|
)
|
||||||
|
cerbero = CerberoClient(
|
||||||
|
base_url=settings.cerbero_base_url,
|
||||||
|
token=token,
|
||||||
|
bot_tag=settings.cerbero_bot_tag,
|
||||||
|
)
|
||||||
|
loader = CerberoOHLCVLoader(client=cerbero, cache_dir=settings.series_dir)
|
||||||
|
engine = BacktestEngine(fees_bp=5.0)
|
||||||
|
strategies_dir = Path("/app/strategies")
|
||||||
|
|
||||||
|
for label, fname, symbol, timeframe in STRATEGIES:
|
||||||
|
path = strategies_dir / fname
|
||||||
|
strat = parse_strategy(path.read_text())
|
||||||
|
|
||||||
|
# Carica intero range una volta sola
|
||||||
|
ohlcv = loader.load(OHLCVRequest(
|
||||||
|
symbol=symbol, timeframe=timeframe,
|
||||||
|
start=datetime.fromisoformat("2018-09-01T00:00:00+00:00"),
|
||||||
|
end=datetime.fromisoformat("2026-01-01T00:00:00+00:00"),
|
||||||
|
))
|
||||||
|
|
||||||
|
print(f"\n{'=' * 110}")
|
||||||
|
print(f">>> {label}")
|
||||||
|
print(f" symbol={symbol} timeframe={timeframe} | {len(ohlcv)} bars total")
|
||||||
|
print(f" {'year':<6} {'bars':>6} {'trades':>7} {'wins':>5} {'losses':>7} {'win%':>6} {'avg_w':>10} {'avg_l':>10} {'ret':>8} {'maxDD':>7} {'sharpe':>7}")
|
||||||
|
|
||||||
|
sum_ret = 0.0
|
||||||
|
sum_trades = 0
|
||||||
|
sum_wins = 0
|
||||||
|
for year_label, start, end in YEARS:
|
||||||
|
mask = (ohlcv.index >= datetime.fromisoformat(start)) & (ohlcv.index < datetime.fromisoformat(end))
|
||||||
|
slice_df = ohlcv[mask]
|
||||||
|
if len(slice_df) == 0:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
signal_fn = compile_strategy(strat)
|
||||||
|
signals = signal_fn(slice_df)
|
||||||
|
bt = engine.run(slice_df, signals)
|
||||||
|
except Exception as e:
|
||||||
|
print(f" {year_label:<6} ERROR: {e}")
|
||||||
|
continue
|
||||||
|
trades = bt.trades
|
||||||
|
n = len(trades)
|
||||||
|
wins = [t.net_pnl for t in trades if t.net_pnl > 0]
|
||||||
|
losses = [t.net_pnl for t in trades if t.net_pnl <= 0]
|
||||||
|
nw, nl = len(wins), len(losses)
|
||||||
|
wr = (nw / n * 100) if n else 0.0
|
||||||
|
aw = (sum(wins) / nw) if nw else 0.0
|
||||||
|
al = (sum(losses) / nl) if nl else 0.0
|
||||||
|
if n > 0:
|
||||||
|
notional = float(slice_df["close"].iloc[0])
|
||||||
|
eq = (bt.equity_curve / notional) + 1.0
|
||||||
|
ret = total_return(eq)
|
||||||
|
dd = max_drawdown(eq)
|
||||||
|
sr = sharpe_ratio(bt.returns, periods_per_year=8760)
|
||||||
|
else:
|
||||||
|
ret = dd = sr = 0.0
|
||||||
|
print(f" {year_label:<6} {len(slice_df):>6} {n:>7} {nw:>5} {nl:>7} {wr:>5.1f}% {aw:>10.1f} {al:>10.1f} {ret:>7.2%} {dd:>6.2%} {sr:>7.3f}")
|
||||||
|
sum_ret += ret
|
||||||
|
sum_trades += n
|
||||||
|
sum_wins += nw
|
||||||
|
overall_wr = (sum_wins / sum_trades * 100) if sum_trades else 0.0
|
||||||
|
print(f" {'='*5} TOTALS 7y: {sum_trades:>7} {sum_wins:>5} {sum_trades-sum_wins:>7} {overall_wr:>5.1f}% cum_ret={sum_ret:+.2%}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import pandas as pd # type: ignore[import-untyped]
|
|
||||||
from scipy import stats # type: ignore[import-untyped]
|
|
||||||
|
|
||||||
from .hypothesis import MarketSummary
|
|
||||||
|
|
||||||
|
|
||||||
def build_market_summary(
|
|
||||||
ohlcv: pd.DataFrame,
|
|
||||||
symbol: str,
|
|
||||||
timeframe: str,
|
|
||||||
) -> MarketSummary:
|
|
||||||
returns = ohlcv["close"].pct_change().dropna()
|
|
||||||
return_mean = float(returns.mean())
|
|
||||||
return_std = float(returns.std(ddof=1))
|
|
||||||
skew = float(stats.skew(returns, bias=False))
|
|
||||||
kurt = float(stats.kurtosis(returns, fisher=True, bias=False))
|
|
||||||
|
|
||||||
if return_std < 0.005:
|
|
||||||
regime = "low"
|
|
||||||
elif return_std < 0.02:
|
|
||||||
regime = "medium"
|
|
||||||
else:
|
|
||||||
regime = "high"
|
|
||||||
|
|
||||||
return MarketSummary(
|
|
||||||
symbol=symbol,
|
|
||||||
timeframe=timeframe,
|
|
||||||
n_bars=len(ohlcv),
|
|
||||||
return_mean=return_mean,
|
|
||||||
return_std=return_std,
|
|
||||||
skew=skew,
|
|
||||||
kurtosis=kurt,
|
|
||||||
volatility_regime=regime,
|
|
||||||
)
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
|
|
||||||
import pandas as pd # type: ignore[import-untyped]
|
|
||||||
|
|
||||||
from .orders import Position, Side, Trade
|
|
||||||
|
|
||||||
Signal = Side # alias semantico
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class BacktestResult:
|
|
||||||
equity_curve: pd.Series
|
|
||||||
returns: pd.Series
|
|
||||||
trades: list[Trade]
|
|
||||||
|
|
||||||
|
|
||||||
class BacktestEngine:
|
|
||||||
"""Engine event-driven sincrono: itera bar per bar, applica segnali con
|
|
||||||
delay di 1 bar (segnale a t -> eseguito a t+1 open) per evitare lookahead.
|
|
||||||
|
|
||||||
Position sizing: 1 unit per posizione. Fees applicati su entry+exit.
|
|
||||||
Niente leva, niente liquidation, niente funding (semplificazione Phase 1).
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, fees_bp: float = 5.0) -> None:
|
|
||||||
self.fees_bp = fees_bp
|
|
||||||
|
|
||||||
def run(self, ohlcv: pd.DataFrame, signals: pd.Series) -> BacktestResult:
|
|
||||||
signals = signals.reindex(ohlcv.index).ffill().fillna(Side.FLAT)
|
|
||||||
|
|
||||||
# Esecuzione con delay 1: segnale a t-1 esegue a open di t.
|
|
||||||
shifted = [Side.FLAT, *list(signals.iloc[:-1])]
|
|
||||||
executed_side = pd.Series(shifted, index=ohlcv.index, dtype=object)
|
|
||||||
|
|
||||||
position: Position | None = None
|
|
||||||
position_entry_ts: pd.Timestamp | None = None
|
|
||||||
trades: list[Trade] = []
|
|
||||||
equity = 0.0
|
|
||||||
equity_history: list[float] = []
|
|
||||||
returns_history: list[float] = []
|
|
||||||
prev_equity = 0.0
|
|
||||||
|
|
||||||
for ts, row in ohlcv.iterrows():
|
|
||||||
target_side = executed_side.loc[ts]
|
|
||||||
current_side = position.side if position else Side.FLAT
|
|
||||||
|
|
||||||
if target_side != current_side:
|
|
||||||
if position is not None:
|
|
||||||
assert position_entry_ts is not None
|
|
||||||
trade = Trade(
|
|
||||||
entry_ts=position_entry_ts,
|
|
||||||
exit_ts=ts,
|
|
||||||
side=position.side,
|
|
||||||
size=position.size,
|
|
||||||
entry_price=position.entry_price,
|
|
||||||
exit_price=float(row["open"]),
|
|
||||||
fees_bp=self.fees_bp,
|
|
||||||
)
|
|
||||||
trades.append(trade)
|
|
||||||
equity += trade.net_pnl
|
|
||||||
position = None
|
|
||||||
position_entry_ts = None
|
|
||||||
if target_side in (Side.LONG, Side.SHORT):
|
|
||||||
position = Position(
|
|
||||||
side=target_side, entry_price=float(row["open"]), size=1.0
|
|
||||||
)
|
|
||||||
position_entry_ts = ts
|
|
||||||
|
|
||||||
mark = float(row["close"])
|
|
||||||
mtm = position.unrealized_pnl(mark) if position else 0.0
|
|
||||||
current_equity = equity + mtm
|
|
||||||
equity_history.append(current_equity)
|
|
||||||
returns_history.append(current_equity - prev_equity)
|
|
||||||
prev_equity = current_equity
|
|
||||||
|
|
||||||
if position is not None:
|
|
||||||
assert position_entry_ts is not None
|
|
||||||
last_ts = ohlcv.index[-1]
|
|
||||||
last_close = float(ohlcv["close"].iloc[-1])
|
|
||||||
trade = Trade(
|
|
||||||
entry_ts=position_entry_ts,
|
|
||||||
exit_ts=last_ts,
|
|
||||||
side=position.side,
|
|
||||||
size=position.size,
|
|
||||||
entry_price=position.entry_price,
|
|
||||||
exit_price=last_close,
|
|
||||||
fees_bp=self.fees_bp,
|
|
||||||
)
|
|
||||||
trades.append(trade)
|
|
||||||
equity += trade.net_pnl
|
|
||||||
equity_history[-1] = equity
|
|
||||||
if len(returns_history) >= 2:
|
|
||||||
returns_history[-1] = equity - equity_history[-2]
|
|
||||||
|
|
||||||
return BacktestResult(
|
|
||||||
equity_curve=pd.Series(equity_history, index=ohlcv.index, name="equity"),
|
|
||||||
returns=pd.Series(returns_history, index=ohlcv.index, name="returns"),
|
|
||||||
trades=trades,
|
|
||||||
)
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,27 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd # type: ignore[import-untyped]
|
|
||||||
|
|
||||||
|
|
||||||
def sharpe_ratio(returns: pd.Series, periods_per_year: int = 8760, rf: float = 0.0) -> float:
|
|
||||||
"""Sharpe annualizzato. periods_per_year=8760 per dati orari."""
|
|
||||||
excess = returns - rf / periods_per_year
|
|
||||||
std = excess.std(ddof=1)
|
|
||||||
if std == 0 or np.isnan(std):
|
|
||||||
return 0.0
|
|
||||||
return float(np.sqrt(periods_per_year) * excess.mean() / std)
|
|
||||||
|
|
||||||
|
|
||||||
def max_drawdown(equity: pd.Series) -> float:
|
|
||||||
"""Max drawdown percentuale (positivo)."""
|
|
||||||
peak = equity.cummax()
|
|
||||||
dd = (peak - equity) / peak.replace(0, np.nan)
|
|
||||||
dd = dd.fillna(0.0)
|
|
||||||
return float(dd.max())
|
|
||||||
|
|
||||||
|
|
||||||
def total_return(equity: pd.Series) -> float:
|
|
||||||
if equity.iloc[0] == 0:
|
|
||||||
return float(equity.iloc[-1])
|
|
||||||
return float(equity.iloc[-1] / equity.iloc[0] - 1.0)
|
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# Decisione: indicatori `*_pct` per fix bug protocollo unità
|
||||||
|
|
||||||
|
**Data:** 2026-05-15
|
||||||
|
**Status:** Implementato (atr_pct + sma_pct + macd_pct + prompt LLM aggiornato)
|
||||||
|
**Scope:** `multi_swarm_core.protocol.{compiler,grammar,validator}` + `agents/hypothesis.py` + `strategy_crypto/strategies/eth_*.json`
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
Phase 3 baseline-001 abortita il 2026-05-15 dopo 24h+ di paper-trading senza
|
||||||
|
trade. Analisi post-mortem: la strategia `eth_facd6af85d5d.json` aveva 2/4
|
||||||
|
condizioni dead. Bug:
|
||||||
|
|
||||||
|
- `atr(14) > 0.02` su ETH @ ~3000 USDT → ATR vale ~30-50 (unità prezzo
|
||||||
|
assoluto) → **sempre TRUE** → branch neutro
|
||||||
|
- `atr(14) < 0.01` → **sempre FALSE** → branch morto
|
||||||
|
|
||||||
|
L'origine del bug è una **convention mismatch** fra LLM e compiler:
|
||||||
|
- Il LLM in Phase 1-2 ha generato literal frazionali (0.02, 0.01)
|
||||||
|
aspettandosi che `atr` fosse in % del prezzo (convenzione standard quant)
|
||||||
|
- Il compiler restituiva ATR in unità prezzo assoluto
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
**Aggiungere un indicatore separato `atr_pct(length) = atr/close`** che
|
||||||
|
restituisce ATR come frazione del prezzo close. NON modificare `atr` (che
|
||||||
|
resta in unità prezzo assoluto, usato in confronti relativi tipo
|
||||||
|
`atr > sma`).
|
||||||
|
|
||||||
|
## Rationale
|
||||||
|
|
||||||
|
- **Backcompat**: `atr` esistente continua a funzionare per le strategie
|
||||||
|
che lo usano in confronti relativi (es. `btc_fb63e851.json` ha
|
||||||
|
`atr > sma(14)`, entrambi unità prezzo → confronto valido).
|
||||||
|
- **Esplicito**: il nome `atr_pct` segnala chiaramente al lettore (umano
|
||||||
|
e LLM) la convenzione frazionale.
|
||||||
|
- **Diff minimo**: 4 file modificati (compiler, grammar, validator, JSON
|
||||||
|
ETH) + 2 test unitari nuovi. Nessun refactor del prompt LLM richiesto
|
||||||
|
in questa migrazione.
|
||||||
|
- **Replicabilità**: se in futuro emergono altri indicatori con problemi
|
||||||
|
analoghi (sma vs literal, macd vs literal), si applica lo stesso
|
||||||
|
pattern: aggiungere `<indicator>_pct` come variante frazionale.
|
||||||
|
|
||||||
|
## Alternative scartate
|
||||||
|
|
||||||
|
- **Normalizzare `atr` (breaking change)**: avrebbe rotto le strategie
|
||||||
|
che lo usano in confronti relativi. Troppo rischioso post-Phase 1-2.
|
||||||
|
- **Cambiare il prompt LLM per generare literal in unità prezzo**: non
|
||||||
|
scalabile (literal dipende dall'asset corrente) + i 30 run GA già
|
||||||
|
fatti diventano invalidi.
|
||||||
|
- **Auto-detect** (literal piccolo → assume frazione): magic, frangile,
|
||||||
|
hard to debug.
|
||||||
|
|
||||||
|
## Impatto
|
||||||
|
|
||||||
|
- Strategie GA esistenti: nessun impatto su `btc_fb63e851.json`. Patchato
|
||||||
|
`eth_facd6af85d5d.json` (sostituiti 2 `atr` → `atr_pct`).
|
||||||
|
- Prompt LLM: NON aggiornato in questo commit. Future Phase 2.x runs
|
||||||
|
dovranno includere `atr_pct` nella sezione "indicatori disponibili"
|
||||||
|
del system prompt (item separato, fuori scope qui).
|
||||||
|
- Test: +2 test unitari (`test_atr_pct_is_atr_divided_by_close`,
|
||||||
|
`test_atr_pct_in_strategy_eval`) come regression guard.
|
||||||
|
|
||||||
|
## Verifica
|
||||||
|
|
||||||
|
```python
|
||||||
|
from multi_swarm_core.protocol.compiler import _ind_atr, _ind_atr_pct
|
||||||
|
import pandas as pd, numpy as np
|
||||||
|
np.random.seed(42); close = 3000 + np.cumsum(np.random.randn(500) * 30)
|
||||||
|
df = pd.DataFrame({"close": close, "high": close+10, "low": close-10}, ...)
|
||||||
|
_ind_atr(df, 14).mean() # ~32 (unità prezzo)
|
||||||
|
_ind_atr_pct(df, 14).mean() # ~0.011 (1.1% del prezzo)
|
||||||
|
```
|
||||||
|
|
||||||
|
`atr > 0.02` → 500/500 (broken). `atr_pct > 0.02` → 0/500 (real signal).
|
||||||
|
|
||||||
|
## Estensione: sma_pct + macd_pct (2026-05-15)
|
||||||
|
|
||||||
|
Aggiunti anche `sma_pct` e `macd_pct` per coerenza famiglia `*_pct`:
|
||||||
|
|
||||||
|
- **`sma_pct(length) = (close - sma) / sma`** — deviazione frazionale del
|
||||||
|
close dalla SMA. Range tipico ±0.1. NB: NON è `sma/close` (che sarebbe
|
||||||
|
sempre ~1.0, inutile per literal). Uso: `sma_pct(50) > 0.05` significa
|
||||||
|
"close 5% sopra la media a 50 barre" (mean reversion).
|
||||||
|
- **`macd_pct(fast, slow, signal) = macd / close`** — MACD come frazione
|
||||||
|
del prezzo. Range tipico ±0.02. Uso: `macd_pct > 0.005` significa
|
||||||
|
"momentum > 0.5% del prezzo".
|
||||||
|
|
||||||
|
Prompt LLM aggiornato di conseguenza (`agents/hypothesis.py`):
|
||||||
|
- Lista indicatori include `sma_pct` e `macd_pct` con annotazioni unità
|
||||||
|
- Pattern guidance: "Mean reversion strutturale: sma_pct(long) > 0.05",
|
||||||
|
"Momentum positivo conferma: macd_pct(12,26,9) > 0.005"
|
||||||
|
- 3 nuovi test (sma_pct identity, macd_pct identity, validator integration)
|
||||||
|
|
||||||
|
## Open items
|
||||||
|
|
||||||
|
- ~~Aggiornare il system prompt LLM~~ ✅ chiuso 2026-05-15
|
||||||
|
- ~~`sma_pct`, `macd_pct` se emergono usi analoghi~~ ✅ chiuso 2026-05-15
|
||||||
+21
-2
@@ -172,10 +172,11 @@ class AdversarialAgent:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
# Fees-eat-alpha: gross_pnl > 0 ma fees > 50% del lordo.
|
# Fees-eat-alpha: gross_pnl > 0 ma fees > soglia del lordo.
|
||||||
# La strategia ha edge teorico ma il margine viene mangiato dai
|
# La strategia ha edge teorico ma il margine viene mangiato dai
|
||||||
# costi di transazione: non sostenibile in produzione.
|
# costi di transazione: non sostenibile in produzione.
|
||||||
# Se gross_pnl <= 0 il check non si applica (gia' perdente).
|
# Se gross_pnl <= 0 il check non si applica (la condizione e' coperta
|
||||||
|
# da ``negative_net_pnl`` sotto).
|
||||||
gross_pnl = sum(t.gross_pnl for t in result.trades)
|
gross_pnl = sum(t.gross_pnl for t in result.trades)
|
||||||
total_fees = sum(t.fees for t in result.trades)
|
total_fees = sum(t.fees for t in result.trades)
|
||||||
if gross_pnl > 0 and total_fees / gross_pnl > self._fees_eat_alpha_threshold:
|
if gross_pnl > 0 and total_fees / gross_pnl > self._fees_eat_alpha_threshold:
|
||||||
@@ -190,4 +191,22 @@ class AdversarialAgent:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Negative-net-pnl: somma di ``trade.net_pnl`` < 0 sul training.
|
||||||
|
# Cattura sia il caso "gross negativo" (no edge direzionale) sia il
|
||||||
|
# caso "gross positivo ma fees superiori a gross" (edge insufficiente).
|
||||||
|
# Sintesi del net-after-fees su finestra continua: deal-breaker, non
|
||||||
|
# negoziabile via soft penalty.
|
||||||
|
net_pnl = gross_pnl - total_fees
|
||||||
|
if net_pnl < 0:
|
||||||
|
report.findings.append(
|
||||||
|
Finding(
|
||||||
|
name="negative_net_pnl",
|
||||||
|
severity=Severity.HIGH,
|
||||||
|
detail=(
|
||||||
|
f"Net PnL ${net_pnl:.2f} < 0 after fees over {n_bars} bars; "
|
||||||
|
f"gross ${gross_pnl:.2f}, fees ${total_fees:.2f}"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
return report
|
return report
|
||||||
+182
-40
@@ -2,10 +2,12 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import re
|
import re
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
import openai
|
import openai
|
||||||
|
|
||||||
from ..genome.hypothesis import HypothesisAgentGenome
|
from ..genome.hypothesis import HypothesisAgentGenome
|
||||||
|
from ..genome.prompt_library import PromptLibrary
|
||||||
from ..llm.client import CompletionResult, EmptyCompletionError, LLMClient
|
from ..llm.client import CompletionResult, EmptyCompletionError, LLMClient
|
||||||
from ..protocol.parser import ParseError, Strategy, parse_strategy
|
from ..protocol.parser import ParseError, Strategy, parse_strategy
|
||||||
from ..protocol.validator import ValidationError, validate_strategy
|
from ..protocol.validator import ValidationError, validate_strategy
|
||||||
@@ -21,6 +23,19 @@ class MarketSummary:
|
|||||||
skew: float
|
skew: float
|
||||||
kurtosis: float
|
kurtosis: float
|
||||||
volatility_regime: str
|
volatility_regime: str
|
||||||
|
autocorr_lag1_recent: float = 0.0 # AR(1) ultimi 500 bar
|
||||||
|
autocorr_lag1_baseline: float = 0.0 # AR(1) full sample (riferimento)
|
||||||
|
hurst_recent: float = 0.5 # Hurst ultimi 500 bar
|
||||||
|
vol_percentile: float = 50.0 # 0-100 percentile della vol corrente
|
||||||
|
seasonality_hour: float = 0.0 # 0-1 varianza spiegata da hour
|
||||||
|
seasonality_dow: float = 0.0 # 0-1 varianza spiegata da dow
|
||||||
|
efficiency_ratio: float = 0.0 # Kaufman, 0-1
|
||||||
|
tail_index_left: float = 5.0 # Hill left tail
|
||||||
|
tail_index_right: float = 5.0 # Hill right tail
|
||||||
|
structural_uptrend: float = 0.5 # HH/HL score 0-1
|
||||||
|
compression: float = 1.0 # range recent / range ref
|
||||||
|
spectral_entropy: float = 1.0 # 0-1, Shannon FFT normalizzata
|
||||||
|
dominant_cycle: float | None = None # periodo barre, None se spectrum piatto
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -41,12 +56,9 @@ class HypothesisProposal:
|
|||||||
n_attempts: int = 1
|
n_attempts: int = 1
|
||||||
|
|
||||||
|
|
||||||
SYSTEM_TEMPLATE = """\
|
# === CORE SCAFFOLD constants (universal, legato al protocol/compiler) ===
|
||||||
Sei un agente generatore di ipotesi di trading quantitativo per un sistema swarm.
|
|
||||||
|
|
||||||
Il tuo stile cognitivo: {cognitive_style}
|
|
||||||
Direttiva personale: {system_prompt}
|
|
||||||
|
|
||||||
|
_SYSTEM_GRAMMAR_SPEC = """\
|
||||||
Devi proporre una strategia di trading espressa in JSON STRETTO.
|
Devi proporre una strategia di trading espressa in JSON STRETTO.
|
||||||
La risposta deve essere un singolo oggetto JSON dentro fence ```json...```
|
La risposta deve essere un singolo oggetto JSON dentro fence ```json...```
|
||||||
con questa shape:
|
con questa shape:
|
||||||
@@ -76,12 +88,30 @@ Crossover (eventi su 2 serie):
|
|||||||
{{"op": "crossunder", "args": [<serie_a>, <serie_b>]}}
|
{{"op": "crossunder", "args": [<serie_a>, <serie_b>]}}
|
||||||
|
|
||||||
Leaf - indicatori (calcolati su close):
|
Leaf - indicatori (calcolati su close):
|
||||||
{{"kind": "indicator", "name": "sma", "params": [<length>]}}
|
{{"kind": "indicator", "name": "sma", "params": [<length>]}} // media mobile, UNITÀ PREZZO
|
||||||
{{"kind": "indicator", "name": "rsi", "params": [<length>]}}
|
{{"kind": "indicator", "name": "sma_pct", "params": [<length>]}} // (close-sma)/sma, FRAZIONE ±0.1
|
||||||
{{"kind": "indicator", "name": "atr", "params": [<length>]}}
|
{{"kind": "indicator", "name": "rsi", "params": [<length>]}} // 0-100, adimensionale
|
||||||
{{"kind": "indicator", "name": "realized_vol", "params": [<window>]}}
|
{{"kind": "indicator", "name": "atr", "params": [<length>]}} // true range, UNITÀ PREZZO
|
||||||
{{"kind": "indicator", "name": "macd", "params": [<fast>, <slow>, <signal>]}}
|
{{"kind": "indicator", "name": "atr_pct", "params": [<length>]}} // atr/close, FRAZIONE 0.0-0.1
|
||||||
// 0-3 numeri (tutti opzionali con default 12, 26, 9)
|
{{"kind": "indicator", "name": "realized_vol", "params": [<window>]}} // std dei returns, FRAZIONE
|
||||||
|
{{"kind": "indicator", "name": "macd", "params": [<fast>, <slow>, <signal>]}} // UNITÀ PREZZO
|
||||||
|
{{"kind": "indicator", "name": "macd_pct", "params": [<fast>, <slow>, <signal>]}} // macd/close, FRAZIONE ±0.02
|
||||||
|
// params: 0-3 numeri (tutti opzionali, default 12, 26, 9)
|
||||||
|
|
||||||
|
UNITÀ — REGOLA CRITICA per i confronti con literal numerici:
|
||||||
|
* Confronti con literal FRAZIONALI (0.01, 0.02, 0.05): usa le varianti _pct
|
||||||
|
Esempi CORRETTI:
|
||||||
|
`atr_pct(14) > 0.02` "ATR > 2% del prezzo" (volatilità alta)
|
||||||
|
`sma_pct(50) > 0.05` "close 5% sopra SMA(50)" (deviazione media)
|
||||||
|
`macd_pct(12,26,9) > 0.005` "momentum > 0.5% del prezzo"
|
||||||
|
Esempi ERRATI (sempre TRUE/FALSE su crypto, dead branch):
|
||||||
|
`atr(14) > 0.02` atr in dollari (~30 su ETH) >> 0.02
|
||||||
|
`sma(50) > 0.02` sma in dollari (~3000) >> 0.02
|
||||||
|
`macd > 0.02` macd in dollari, ordine ±10
|
||||||
|
* Confronti RELATIVI fra indicatori in stessa unità: usa nomi senza _pct
|
||||||
|
Esempi: `atr(14) > sma(14)` (entrambi $), `sma(50) > sma(200)` (golden cross)
|
||||||
|
`close > sma(50)` (entrambi $) — preferito su `sma_pct(50) > 0` (equivalente)
|
||||||
|
* RSI usa literal 0-100 (mai frazione): `rsi(14) > 70`, `rsi(14) < 30`
|
||||||
|
|
||||||
Leaf - feature OHLCV:
|
Leaf - feature OHLCV:
|
||||||
{{"kind": "feature", "name": "open|high|low|close|volume"}}
|
{{"kind": "feature", "name": "open|high|low|close|volume"}}
|
||||||
@@ -103,34 +133,18 @@ Esempi di gating temporale:
|
|||||||
{{"op": "eq", "args": [{{"kind": "feature", "name": "is_weekend"}}, {{"kind": "literal", "value": 1}}]}}
|
{{"op": "eq", "args": [{{"kind": "feature", "name": "is_weekend"}}, {{"kind": "literal", "value": 1}}]}}
|
||||||
|
|
||||||
Leaf - letterale numerico:
|
Leaf - letterale numerico:
|
||||||
{{"kind": "literal", "value": 70.0}}
|
{{"kind": "literal", "value": 70.0}}"""
|
||||||
|
|
||||||
PATTERN GUIDANCE (oltre agli indicatori, considera forma delle curve e ripetibilità):
|
|
||||||
|
|
||||||
Forme di curva:
|
|
||||||
- Trend ascendente: SMA(short) > SMA(long) E close > SMA(short)
|
|
||||||
- Trend discendente: SMA(short) < SMA(long) E close < SMA(short)
|
|
||||||
- Compressione di volatilità (pre-breakout): ATR(N) < soglia bassa
|
|
||||||
- Espansione di volatilità: ATR(N) > ATR(N*2) (vol corta > vol lunga)
|
|
||||||
- Mean reversion strutturale: |close - SMA(long)| eccessivo → reversal atteso
|
|
||||||
|
|
||||||
Ripetibilità dell'andamento:
|
|
||||||
- Eventi crossover/crossunder ricorrenti (golden/death cross, RSI cross zone)
|
|
||||||
- Pattern intra-day: usa 'hour' per sfruttare orari di forte volatilità ricorrente
|
|
||||||
- Pattern settimanali: usa 'dow' o 'is_weekend' per cicli mercato
|
|
||||||
- Doppio top approx: RSI > 70 + crossunder RSI 70 (1° picco), poi entro N bar
|
|
||||||
nuovo crossover RSI 70 a livello close simile → entry short
|
|
||||||
- Range breakout: close > SMA(N) con SMA(short) > SMA(long) (compressione + spinta)
|
|
||||||
|
|
||||||
Cerca pattern che si REPLICANO nei dati storici, non singoli eventi rari.
|
|
||||||
|
|
||||||
|
_SYSTEM_CONSTRAINTS = """\
|
||||||
VINCOLI
|
VINCOLI
|
||||||
- Gli indicator NON sono annidabili: 'params' accetta solo numeri, mai altri nodi.
|
- Gli indicator NON sono annidabili: 'params' accetta solo numeri, mai altri nodi.
|
||||||
- Le regole sono valutate in ordine; la prima che matcha vince per ogni timestamp.
|
- Le regole sono valutate in ordine; la prima che matcha vince per ogni timestamp.
|
||||||
- Default action se nessuna regola matcha = flat.
|
- Default action se nessuna regola matcha = flat.
|
||||||
- 'op' e 'kind' sono mutuamente esclusivi sullo stesso nodo.
|
- 'op' e 'kind' sono mutuamente esclusivi sullo stesso nodo.
|
||||||
|
|
||||||
Rispondi SOLO con il fence ```json...``` contenente l'oggetto strategy.
|
Rispondi SOLO con il fence ```json...``` contenente l'oggetto strategy."""
|
||||||
|
|
||||||
|
_SYSTEM_EXAMPLE = """\
|
||||||
Esempio:
|
Esempio:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
@@ -152,8 +166,49 @@ Esempio:
|
|||||||
}}
|
}}
|
||||||
]
|
]
|
||||||
}}
|
}}
|
||||||
```
|
```"""
|
||||||
"""
|
|
||||||
|
|
||||||
|
def _build_system_prompt(lib: PromptLibrary, genome: HypothesisAgentGenome) -> str:
|
||||||
|
"""Compone il SYSTEM prompt da scaffold core + contenuto strategy-specific."""
|
||||||
|
parts: list[str] = []
|
||||||
|
# 1. Header strategy-specific (da prompts.json)
|
||||||
|
parts.append(lib.agent_role)
|
||||||
|
parts.append("")
|
||||||
|
# 2. Cognitive style + directive (sempre, dal genome)
|
||||||
|
parts.append(f"Il tuo stile cognitivo: {genome.cognitive_style}")
|
||||||
|
parts.append(f"Direttiva personale: {genome.system_prompt}")
|
||||||
|
parts.append("")
|
||||||
|
# 3. Grammar spec (core scaffold)
|
||||||
|
parts.append(_SYSTEM_GRAMMAR_SPEC)
|
||||||
|
# 4. Pattern guidance (da prompts.json, opzionale)
|
||||||
|
if lib.pattern_guidance:
|
||||||
|
parts.append(
|
||||||
|
"\nPATTERN GUIDANCE (oltre agli indicatori, considera forma delle curve e ripetibilità):\n"
|
||||||
|
)
|
||||||
|
parts.append(lib.pattern_guidance)
|
||||||
|
parts.append(
|
||||||
|
"\n Cerca pattern che si REPLICANO nei dati storici, non singoli eventi rari.\n"
|
||||||
|
)
|
||||||
|
# 5. Domain warnings (da prompts.json, opzionale)
|
||||||
|
if lib.domain_warnings:
|
||||||
|
parts.append("\nWARNING DI DOMINIO:\n")
|
||||||
|
parts.append(lib.domain_warnings)
|
||||||
|
parts.append("")
|
||||||
|
# 6. Vincoli (core scaffold)
|
||||||
|
parts.append(_SYSTEM_CONSTRAINTS)
|
||||||
|
# 7. NEW v3.1: anti-pattern e output priorities (da prompts.json, opzionali)
|
||||||
|
if lib.anti_patterns:
|
||||||
|
parts.append("\nANTI-PATTERN DA EVITARE:\n")
|
||||||
|
parts.append(lib.anti_patterns)
|
||||||
|
parts.append("")
|
||||||
|
if lib.output_priorities:
|
||||||
|
parts.append("\nPRIORITA' DI OUTPUT (trade-off):\n")
|
||||||
|
parts.append(lib.output_priorities)
|
||||||
|
parts.append("")
|
||||||
|
# 8. Esempio (core scaffold)
|
||||||
|
parts.append(_SYSTEM_EXAMPLE)
|
||||||
|
return "\n".join(parts)
|
||||||
|
|
||||||
|
|
||||||
USER_TEMPLATE = """\
|
USER_TEMPLATE = """\
|
||||||
@@ -162,13 +217,72 @@ Statistiche return: mean={return_mean:.5f}, std={return_std:.5f}, \
|
|||||||
skew={skew:.3f}, kurt={kurtosis:.3f}.
|
skew={skew:.3f}, kurt={kurtosis:.3f}.
|
||||||
Regime volatilità: {volatility_regime}.
|
Regime volatilità: {volatility_regime}.
|
||||||
|
|
||||||
|
Regime recente (ultime 500 barre):
|
||||||
|
autocorr_lag1: {autocorr_lag1_recent:.3f} (baseline storica: {autocorr_lag1_baseline:.3f})
|
||||||
|
hurst: {hurst_recent:.3f} (0.5 = random walk, >0.55 trending, <0.45 mean rev)
|
||||||
|
vol_pct: {vol_percentile:.0f}° percentile storico
|
||||||
|
stagionalita: hour={seasonality_hour:.2f}, dow={seasonality_dow:.2f} (0-1, varianza spiegata)
|
||||||
|
|
||||||
|
Geometria & frattali:
|
||||||
|
efficiency_ratio: {efficiency_ratio:.3f} (Kaufman, 0=noise, 1=trend efficiente)
|
||||||
|
tail_index: left={tail_index_left:.2f}, right={tail_index_right:.2f} (Hill; <2 fat tail, >5 light)
|
||||||
|
structural_uptrend: {structural_uptrend:.2f} (HH/HL score, 0.5=range)
|
||||||
|
compression: {compression:.2f} (range recent / ref; <1 compressione, >1 espansione)
|
||||||
|
spectral_entropy: {spectral_entropy:.2f} (0=struttura, 1=rumore bianco)
|
||||||
|
dominant_cycle: {dominant_cycle_str} (None se spettro piatto)
|
||||||
|
|
||||||
Feature accessibili dal tuo genoma: {feature_access}.
|
Feature accessibili dal tuo genoma: {feature_access}.
|
||||||
Lookback massimo che puoi usare nel ragionamento: {lookback_window} barre.
|
Lookback massimo che puoi usare nel ragionamento: {lookback_window} barre.
|
||||||
|
|
||||||
Genera una strategia che cerchi anomalie sfruttabili in questo regime.
|
{instruction}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _render_focus_block(keys: list[str], market: MarketSummary) -> str:
|
||||||
|
"""Renderizza 'Focus per la tua lente' come riga del USER_TEMPLATE.
|
||||||
|
|
||||||
|
Mappa nomi simbolici a valori della MarketSummary. Skippa silenziosamente
|
||||||
|
chiavi sconosciute (fault-tolerant per evoluzione futura).
|
||||||
|
"""
|
||||||
|
field_map: dict[str, Any] = {
|
||||||
|
# Statistiche base
|
||||||
|
"mean": market.return_mean,
|
||||||
|
"std": market.return_std,
|
||||||
|
"skew": market.skew,
|
||||||
|
"kurt": market.kurtosis,
|
||||||
|
"vol_regime": market.volatility_regime,
|
||||||
|
# Regime recente
|
||||||
|
"autocorr_recent": market.autocorr_lag1_recent,
|
||||||
|
"autocorr_baseline": market.autocorr_lag1_baseline,
|
||||||
|
"hurst": market.hurst_recent,
|
||||||
|
"vol_pct": market.vol_percentile,
|
||||||
|
"seasonality_hour": market.seasonality_hour,
|
||||||
|
"seasonality_dow": market.seasonality_dow,
|
||||||
|
# Geometria/frattali
|
||||||
|
"efficiency_ratio": market.efficiency_ratio,
|
||||||
|
"tail_left": market.tail_index_left,
|
||||||
|
"tail_right": market.tail_index_right,
|
||||||
|
"structural_uptrend": market.structural_uptrend,
|
||||||
|
"compression": market.compression,
|
||||||
|
"spectral_entropy": market.spectral_entropy,
|
||||||
|
"dominant_cycle": market.dominant_cycle,
|
||||||
|
}
|
||||||
|
parts: list[str] = []
|
||||||
|
for k in keys:
|
||||||
|
if k not in field_map:
|
||||||
|
continue
|
||||||
|
v = field_map[k]
|
||||||
|
if v is None:
|
||||||
|
parts.append(f"{k}=N/A")
|
||||||
|
elif isinstance(v, float):
|
||||||
|
parts.append(f"{k}={v:.3f}")
|
||||||
|
else:
|
||||||
|
parts.append(f"{k}={v}")
|
||||||
|
if not parts:
|
||||||
|
return ""
|
||||||
|
return "\nFocus per la tua lente: " + ", ".join(parts) + "\n"
|
||||||
|
|
||||||
|
|
||||||
_RETRY_TEMPLATE = """\
|
_RETRY_TEMPLATE = """\
|
||||||
{original_user}
|
{original_user}
|
||||||
|
|
||||||
@@ -251,20 +365,34 @@ def _try_parse(text: str) -> tuple[Strategy | None, str | None]:
|
|||||||
|
|
||||||
|
|
||||||
class HypothesisAgent:
|
class HypothesisAgent:
|
||||||
def __init__(self, llm: LLMClient, max_retries: int = 1):
|
def __init__(
|
||||||
|
self,
|
||||||
|
llm: LLMClient,
|
||||||
|
max_retries: int = 1,
|
||||||
|
prompt_library: PromptLibrary | None = None,
|
||||||
|
):
|
||||||
if max_retries < 0:
|
if max_retries < 0:
|
||||||
raise ValueError("max_retries must be >= 0")
|
raise ValueError("max_retries must be >= 0")
|
||||||
self._llm = llm
|
self._llm = llm
|
||||||
self._max_retries = max_retries
|
self._max_retries = max_retries
|
||||||
|
self._prompt_library = prompt_library or PromptLibrary.default()
|
||||||
|
|
||||||
def propose(
|
def propose(
|
||||||
self,
|
self,
|
||||||
genome: HypothesisAgentGenome,
|
genome: HypothesisAgentGenome,
|
||||||
market: MarketSummary,
|
market: MarketSummary,
|
||||||
) -> HypothesisProposal:
|
) -> HypothesisProposal:
|
||||||
system = SYSTEM_TEMPLATE.format(
|
system = _build_system_prompt(self._prompt_library, genome)
|
||||||
cognitive_style=genome.cognitive_style,
|
dominant_cycle_str = (
|
||||||
system_prompt=genome.system_prompt,
|
f"{market.dominant_cycle:.0f} barre"
|
||||||
|
if market.dominant_cycle is not None
|
||||||
|
else "N/A (spettro piatto)"
|
||||||
|
)
|
||||||
|
focus_keys = self._prompt_library.focus_metrics_for(genome.cognitive_style)
|
||||||
|
focus_block = _render_focus_block(focus_keys, market) if focus_keys else ""
|
||||||
|
instruction = (
|
||||||
|
self._prompt_library.instruction
|
||||||
|
or "Genera una strategia che cerchi anomalie sfruttabili in questo regime."
|
||||||
)
|
)
|
||||||
original_user = USER_TEMPLATE.format(
|
original_user = USER_TEMPLATE.format(
|
||||||
symbol=market.symbol,
|
symbol=market.symbol,
|
||||||
@@ -275,9 +403,23 @@ class HypothesisAgent:
|
|||||||
skew=market.skew,
|
skew=market.skew,
|
||||||
kurtosis=market.kurtosis,
|
kurtosis=market.kurtosis,
|
||||||
volatility_regime=market.volatility_regime,
|
volatility_regime=market.volatility_regime,
|
||||||
|
autocorr_lag1_recent=market.autocorr_lag1_recent,
|
||||||
|
autocorr_lag1_baseline=market.autocorr_lag1_baseline,
|
||||||
|
hurst_recent=market.hurst_recent,
|
||||||
|
vol_percentile=market.vol_percentile,
|
||||||
|
seasonality_hour=market.seasonality_hour,
|
||||||
|
seasonality_dow=market.seasonality_dow,
|
||||||
|
efficiency_ratio=market.efficiency_ratio,
|
||||||
|
tail_index_left=market.tail_index_left,
|
||||||
|
tail_index_right=market.tail_index_right,
|
||||||
|
structural_uptrend=market.structural_uptrend,
|
||||||
|
compression=market.compression,
|
||||||
|
spectral_entropy=market.spectral_entropy,
|
||||||
|
dominant_cycle_str=dominant_cycle_str,
|
||||||
feature_access=", ".join(genome.feature_access),
|
feature_access=", ".join(genome.feature_access),
|
||||||
lookback_window=genome.lookback_window,
|
lookback_window=genome.lookback_window,
|
||||||
)
|
instruction=instruction,
|
||||||
|
) + focus_block
|
||||||
|
|
||||||
completions: list[CompletionResult] = []
|
completions: list[CompletionResult] = []
|
||||||
errors: list[str] = []
|
errors: list[str] = []
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pandas as pd # type: ignore[import-untyped]
|
||||||
|
from scipy import stats # type: ignore[import-untyped]
|
||||||
|
|
||||||
|
from ..metrics.basic import (
|
||||||
|
autocorr_lag1,
|
||||||
|
compression_ratio,
|
||||||
|
efficiency_ratio_kaufman,
|
||||||
|
hurst_exponent,
|
||||||
|
seasonality_strength,
|
||||||
|
spectral_entropy_and_cycle,
|
||||||
|
structural_uptrend_score,
|
||||||
|
tail_index_hill,
|
||||||
|
vol_percentile_historical,
|
||||||
|
)
|
||||||
|
from .hypothesis import MarketSummary
|
||||||
|
|
||||||
|
|
||||||
|
def build_market_summary(
|
||||||
|
ohlcv: pd.DataFrame,
|
||||||
|
symbol: str,
|
||||||
|
timeframe: str,
|
||||||
|
) -> MarketSummary:
|
||||||
|
returns = ohlcv["close"].pct_change().dropna()
|
||||||
|
return_mean = float(returns.mean())
|
||||||
|
return_std = float(returns.std(ddof=1))
|
||||||
|
skew = float(stats.skew(returns, bias=False))
|
||||||
|
kurt = float(stats.kurtosis(returns, fisher=True, bias=False))
|
||||||
|
|
||||||
|
if return_std < 0.005:
|
||||||
|
regime = "low"
|
||||||
|
elif return_std < 0.02:
|
||||||
|
regime = "medium"
|
||||||
|
else:
|
||||||
|
regime = "high"
|
||||||
|
|
||||||
|
recent_window = min(500, len(returns))
|
||||||
|
recent_returns = returns.iloc[-recent_window:]
|
||||||
|
|
||||||
|
autocorr_recent = autocorr_lag1(recent_returns)
|
||||||
|
autocorr_baseline = autocorr_lag1(returns)
|
||||||
|
hurst_r = hurst_exponent(recent_returns)
|
||||||
|
vol_pct = vol_percentile_historical(returns, current_window=24, ref_window=2000)
|
||||||
|
season_h = seasonality_strength(returns, by="hour")
|
||||||
|
season_d = seasonality_strength(returns, by="dow")
|
||||||
|
|
||||||
|
eff_ratio = efficiency_ratio_kaufman(ohlcv["close"], length=100)
|
||||||
|
tail_l = tail_index_hill(returns, side="left")
|
||||||
|
tail_r = tail_index_hill(returns, side="right")
|
||||||
|
hh_hl = structural_uptrend_score(ohlcv["close"], window=5)
|
||||||
|
compress = compression_ratio(ohlcv["close"], recent_window=50, ref_window=200)
|
||||||
|
spec_entropy, dom_cycle = spectral_entropy_and_cycle(returns, length=256)
|
||||||
|
|
||||||
|
return MarketSummary(
|
||||||
|
symbol=symbol,
|
||||||
|
timeframe=timeframe,
|
||||||
|
n_bars=len(ohlcv),
|
||||||
|
return_mean=return_mean,
|
||||||
|
return_std=return_std,
|
||||||
|
skew=skew,
|
||||||
|
kurtosis=kurt,
|
||||||
|
volatility_regime=regime,
|
||||||
|
autocorr_lag1_recent=autocorr_recent,
|
||||||
|
autocorr_lag1_baseline=autocorr_baseline,
|
||||||
|
hurst_recent=hurst_r,
|
||||||
|
vol_percentile=vol_pct,
|
||||||
|
seasonality_hour=season_h,
|
||||||
|
seasonality_dow=season_d,
|
||||||
|
efficiency_ratio=eff_ratio,
|
||||||
|
tail_index_left=tail_l,
|
||||||
|
tail_index_right=tail_r,
|
||||||
|
structural_uptrend=hh_hl,
|
||||||
|
compression=compress,
|
||||||
|
spectral_entropy=spec_entropy,
|
||||||
|
dominant_cycle=dom_cycle,
|
||||||
|
)
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd # type: ignore[import-untyped]
|
||||||
|
|
||||||
|
from .orders import Position, Side, Trade
|
||||||
|
|
||||||
|
Signal = Side # alias semantico
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class BacktestResult:
|
||||||
|
equity_curve: pd.Series
|
||||||
|
returns: pd.Series
|
||||||
|
trades: list[Trade]
|
||||||
|
|
||||||
|
|
||||||
|
class BacktestEngine:
|
||||||
|
"""Engine event-driven sincrono: itera bar per bar, applica segnali con
|
||||||
|
delay di 1 bar (segnale a t -> eseguito a t+1 open) per evitare lookahead.
|
||||||
|
|
||||||
|
Position sizing: 1 unit per posizione. Fees applicati su entry+exit.
|
||||||
|
Niente leva, niente liquidation, niente funding (semplificazione Phase 1).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, fees_bp: float = 5.0) -> None:
|
||||||
|
self.fees_bp = fees_bp
|
||||||
|
|
||||||
|
def run(self, ohlcv: pd.DataFrame, signals: pd.Series) -> BacktestResult:
|
||||||
|
n = len(ohlcv)
|
||||||
|
if n == 0:
|
||||||
|
empty = pd.Series([], dtype=float)
|
||||||
|
return BacktestResult(equity_curve=empty, returns=empty, trades=[])
|
||||||
|
|
||||||
|
signals = signals.reindex(ohlcv.index).ffill().fillna(Side.FLAT)
|
||||||
|
# Esecuzione con delay 1: segnale a t-1 esegue a open di t.
|
||||||
|
executed = pd.Series(
|
||||||
|
[Side.FLAT, *list(signals.iloc[:-1])],
|
||||||
|
index=ohlcv.index,
|
||||||
|
dtype=object,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Codifica side in int per vectorizzazione: 0=FLAT, +1=LONG, -1=SHORT.
|
||||||
|
side_code = np.where(
|
||||||
|
executed.values == Side.LONG, 1,
|
||||||
|
np.where(executed.values == Side.SHORT, -1, 0),
|
||||||
|
).astype(np.int8)
|
||||||
|
opens = ohlcv["open"].to_numpy(dtype=np.float64)
|
||||||
|
closes = ohlcv["close"].to_numpy(dtype=np.float64)
|
||||||
|
ts_index = ohlcv.index
|
||||||
|
|
||||||
|
# Identifica transizioni: punto in cui side[i] != side[i-1] (con side[-1]=0).
|
||||||
|
prev = np.concatenate(([0], side_code[:-1]))
|
||||||
|
change = side_code != prev
|
||||||
|
|
||||||
|
# Indici di entry (cambio verso side != 0).
|
||||||
|
entry_idxs = np.flatnonzero(change & (side_code != 0))
|
||||||
|
# Indici di chiusura: per ogni entry, il prossimo indice dove side[i] != side_entry.
|
||||||
|
# Vectorized: per ogni entry_idx, cerca change & side != side_entry oltre l'entry.
|
||||||
|
|
||||||
|
trades: list[Trade] = []
|
||||||
|
# realized_pnl[t]: PnL netto cumulato dopo le chiusure avvenute a OPEN di t.
|
||||||
|
realized_pnl = np.zeros(n, dtype=np.float64)
|
||||||
|
fees_rate = self.fees_bp / 10000.0
|
||||||
|
size = 1.0
|
||||||
|
|
||||||
|
# Posizione corrente all'inizio di ogni indice t (prima di applicare il transitorio):
|
||||||
|
# used per MtM computation. open_side_at_t / open_entry_at_t.
|
||||||
|
open_side = np.zeros(n, dtype=np.int8)
|
||||||
|
open_entry = np.zeros(n, dtype=np.float64)
|
||||||
|
|
||||||
|
for entry_idx in entry_idxs:
|
||||||
|
entry_side = int(side_code[entry_idx])
|
||||||
|
entry_price = opens[entry_idx]
|
||||||
|
# Cerca exit: primo indice > entry_idx dove side differisce.
|
||||||
|
after = side_code[entry_idx + 1:]
|
||||||
|
rel = np.flatnonzero(after != entry_side)
|
||||||
|
if rel.size > 0:
|
||||||
|
exit_idx = entry_idx + 1 + int(rel[0])
|
||||||
|
exit_price = opens[exit_idx]
|
||||||
|
exit_ts = ts_index[exit_idx]
|
||||||
|
gross = entry_side * (exit_price - entry_price) * size
|
||||||
|
fees = fees_rate * size * (entry_price + exit_price)
|
||||||
|
net = gross - fees
|
||||||
|
# La chiusura avviene a open[exit_idx]: dal bar exit_idx in poi il
|
||||||
|
# PnL e' realizzato (non piu' MtM).
|
||||||
|
realized_pnl[exit_idx:] += net
|
||||||
|
# Posizione aperta in [entry_idx, exit_idx-1].
|
||||||
|
open_side[entry_idx:exit_idx] = entry_side
|
||||||
|
open_entry[entry_idx:exit_idx] = entry_price
|
||||||
|
trades.append(Trade(
|
||||||
|
entry_ts=ts_index[entry_idx],
|
||||||
|
exit_ts=exit_ts,
|
||||||
|
side=Side.LONG if entry_side == 1 else Side.SHORT,
|
||||||
|
size=size,
|
||||||
|
entry_price=entry_price,
|
||||||
|
exit_price=exit_price,
|
||||||
|
fees_bp=self.fees_bp,
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
# Ultima posizione ancora aperta: chiusura forced a close[-1].
|
||||||
|
# Parita' col loop legacy: MtM su [entry_idx, n-1), realized totale
|
||||||
|
# SOLO al bar n-1 (legacy fa equity_history[-1] = equity).
|
||||||
|
last_close = closes[-1]
|
||||||
|
gross = entry_side * (last_close - entry_price) * size
|
||||||
|
fees = fees_rate * size * (entry_price + last_close)
|
||||||
|
net = gross - fees
|
||||||
|
if entry_idx < n - 1:
|
||||||
|
open_side[entry_idx:n - 1] = entry_side
|
||||||
|
open_entry[entry_idx:n - 1] = entry_price
|
||||||
|
realized_pnl[-1] += net
|
||||||
|
trades.append(Trade(
|
||||||
|
entry_ts=ts_index[entry_idx],
|
||||||
|
exit_ts=ts_index[-1],
|
||||||
|
side=Side.LONG if entry_side == 1 else Side.SHORT,
|
||||||
|
size=size,
|
||||||
|
entry_price=entry_price,
|
||||||
|
exit_price=last_close,
|
||||||
|
fees_bp=self.fees_bp,
|
||||||
|
))
|
||||||
|
|
||||||
|
# MtM unrealized per ogni bar in cui c'e' una posizione aperta.
|
||||||
|
mtm = open_side.astype(np.float64) * (closes - open_entry) * size
|
||||||
|
equity_arr = realized_pnl + mtm
|
||||||
|
# Returns = first diff dell'equity (col loop legacy il primo bar e' equity[0]-0).
|
||||||
|
returns_arr = np.concatenate(([equity_arr[0]], np.diff(equity_arr)))
|
||||||
|
|
||||||
|
return BacktestResult(
|
||||||
|
equity_curve=pd.Series(equity_arr, index=ts_index, name="equity"),
|
||||||
|
returns=pd.Series(returns_arr, index=ts_index, name="returns"),
|
||||||
|
trades=trades,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Lo facade Position re-export e' tenuto per backward-compat con import legacy.
|
||||||
|
__all__ = ["BacktestEngine", "BacktestResult", "Position", "Side", "Signal", "Trade"]
|
||||||
@@ -6,7 +6,7 @@ in the project root. Required secrets are validated at instantiation time.
|
|||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from pydantic import Field, SecretStr
|
from pydantic import AliasChoices, Field, SecretStr
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
@@ -35,7 +35,24 @@ class Settings(BaseSettings):
|
|||||||
run_name: str = "phase1-spike-001"
|
run_name: str = "phase1-spike-001"
|
||||||
data_dir: Path = Field(default=Path("./data"))
|
data_dir: Path = Field(default=Path("./data"))
|
||||||
series_dir: Path = Field(default=Path("./series"))
|
series_dir: Path = Field(default=Path("./series"))
|
||||||
db_path: Path = Field(default=Path("./runs.db"))
|
|
||||||
|
# GA core DB (tabelle universali: runs, generations, genomes, evaluations, ...)
|
||||||
|
# Alias DB_PATH legacy mantenuto per backcompat (deprecato, rimuovere nei prossimi cicli).
|
||||||
|
ga_db_path: Path = Field(
|
||||||
|
default=Path("./state/runs.db"),
|
||||||
|
validation_alias=AliasChoices("GA_DB_PATH", "DB_PATH"),
|
||||||
|
)
|
||||||
|
|
||||||
|
# DB per la strategia crypto (tabelle paper_trading_*, isolato dal core)
|
||||||
|
strategy_crypto_db_path: Path = Field(
|
||||||
|
default=Path("./state/strategy_crypto.db"),
|
||||||
|
validation_alias="STRATEGY_CRYPTO_DB_PATH",
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def db_path(self) -> Path:
|
||||||
|
"""Backcompat alias: legge ga_db_path. Deprecato — usare ga_db_path."""
|
||||||
|
return self.ga_db_path
|
||||||
|
|
||||||
|
|
||||||
def load_settings() -> Settings:
|
def load_settings() -> Settings:
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""GA data access functions for the core dashboard.
|
||||||
|
|
||||||
|
Reads exclusively from runs.db (GA tables).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pandas as pd # type: ignore[import-untyped]
|
||||||
|
|
||||||
|
from multi_swarm_core.persistence.repository import Repository
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"get_repo",
|
||||||
|
"list_runs_df",
|
||||||
|
"get_run_overview",
|
||||||
|
"generations_df",
|
||||||
|
"evaluations_df",
|
||||||
|
"genomes_df",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def get_repo(db_path: str | Path) -> Repository:
|
||||||
|
return Repository(db_path=db_path)
|
||||||
|
|
||||||
|
|
||||||
|
def list_runs_df(repo: Repository) -> pd.DataFrame:
|
||||||
|
return pd.DataFrame(repo.list_runs())
|
||||||
|
|
||||||
|
|
||||||
|
def get_run_overview(repo: Repository, run_id: str) -> dict[str, Any]:
|
||||||
|
run = repo.get_run(run_id)
|
||||||
|
return {
|
||||||
|
"name": run["name"],
|
||||||
|
"started_at": run["started_at"],
|
||||||
|
"completed_at": run["completed_at"],
|
||||||
|
"status": run["status"],
|
||||||
|
"total_cost_usd": run["total_cost_usd"],
|
||||||
|
"config": json.loads(run["config_json"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def generations_df(repo: Repository, run_id: str) -> pd.DataFrame:
|
||||||
|
return pd.DataFrame(repo.list_generations(run_id))
|
||||||
|
|
||||||
|
|
||||||
|
def evaluations_df(repo: Repository, run_id: str) -> pd.DataFrame:
|
||||||
|
return pd.DataFrame(repo.list_evaluations(run_id))
|
||||||
|
|
||||||
|
|
||||||
|
def genomes_df(
|
||||||
|
repo: Repository, run_id: str, generation_idx: int | None = None
|
||||||
|
) -> pd.DataFrame:
|
||||||
|
rows = repo.list_genomes(run_id, generation_idx)
|
||||||
|
flat: list[dict[str, Any]] = []
|
||||||
|
for r in rows:
|
||||||
|
payload = json.loads(r["payload_json"])
|
||||||
|
flat.append(
|
||||||
|
{
|
||||||
|
"id": r["id"],
|
||||||
|
"generation_idx": r["generation_idx"],
|
||||||
|
**payload,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return pd.DataFrame(flat)
|
||||||
@@ -0,0 +1,560 @@
|
|||||||
|
"""Multi-Swarm Core Dashboard — GA pages: /, /convergence, /genomes.
|
||||||
|
|
||||||
|
Avvio: ``uv run python -m multi_swarm_core.dashboard.nicegui_app``
|
||||||
|
Legge SOLO runs.db (tabelle GA).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import plotly.graph_objects as go # type: ignore[import-untyped]
|
||||||
|
from nicegui import app, ui
|
||||||
|
|
||||||
|
from multi_swarm_core.dashboard.data import (
|
||||||
|
evaluations_df,
|
||||||
|
generations_df,
|
||||||
|
genomes_df,
|
||||||
|
get_repo,
|
||||||
|
get_run_overview,
|
||||||
|
list_runs_df,
|
||||||
|
)
|
||||||
|
from multi_swarm_core.dashboard.theme import (
|
||||||
|
COLOR_ACCENT,
|
||||||
|
COLOR_PRIMARY,
|
||||||
|
COLOR_SECONDARY,
|
||||||
|
COLOR_SURFACE,
|
||||||
|
COLOR_TEXT,
|
||||||
|
COLOR_TEXT_MUTED,
|
||||||
|
_STATUS_BADGE,
|
||||||
|
_apply_theme,
|
||||||
|
_build_header,
|
||||||
|
_json_to_html,
|
||||||
|
)
|
||||||
|
|
||||||
|
GA_DB_PATH = os.environ.get("GA_DB_PATH", "./state/runs.db")
|
||||||
|
DASHBOARD_ROOT_PATH = os.environ.get("DASHBOARD_ROOT_PATH", "")
|
||||||
|
REFRESH_INTERVAL_S = 3.0
|
||||||
|
|
||||||
|
|
||||||
|
def _runs_options() -> dict[str, str]:
|
||||||
|
repo = get_repo(GA_DB_PATH)
|
||||||
|
runs = list_runs_df(repo)
|
||||||
|
if runs.empty:
|
||||||
|
return {}
|
||||||
|
return {
|
||||||
|
row["id"]: f"{row['name']} — {row['status']} ({row['started_at'][:16]})"
|
||||||
|
for _, row in runs.iterrows()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _snapshot(run_id: str) -> dict[str, Any]:
|
||||||
|
repo = get_repo(GA_DB_PATH)
|
||||||
|
ov = get_run_overview(repo, run_id)
|
||||||
|
evals = evaluations_df(repo, run_id)
|
||||||
|
gens = generations_df(repo, run_id)
|
||||||
|
|
||||||
|
cfg = ov["config"]
|
||||||
|
pop_size = int(cfg.get("population_size", 0))
|
||||||
|
n_gens = int(cfg.get("n_generations", 0))
|
||||||
|
evals_total = max(pop_size * n_gens, 1)
|
||||||
|
evals_done = len(evals)
|
||||||
|
gens_done = int(gens["completed_at"].notna().sum()) if not gens.empty else 0
|
||||||
|
live_cost = float(repo.total_cost(run_id)) if ov["status"] == "running" else float(
|
||||||
|
ov["total_cost_usd"]
|
||||||
|
)
|
||||||
|
|
||||||
|
top_fit = float(evals["fitness"].max()) if evals_done else float("nan")
|
||||||
|
median_fit = float(evals["fitness"].median()) if evals_done else float("nan")
|
||||||
|
parse_success = (
|
||||||
|
100.0 * float(evals["parse_error"].isna().sum()) / evals_done if evals_done else 0.0
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"status": ov["status"],
|
||||||
|
"name": cfg.get("run_name", "—"),
|
||||||
|
"started_at": ov["started_at"],
|
||||||
|
"completed_at": ov["completed_at"] or "—",
|
||||||
|
"cost_usd": live_cost,
|
||||||
|
"pop_size": pop_size,
|
||||||
|
"n_gens": n_gens,
|
||||||
|
"evals_done": evals_done,
|
||||||
|
"evals_total": evals_total,
|
||||||
|
"gens_done": gens_done,
|
||||||
|
"top_fit": top_fit,
|
||||||
|
"median_fit": median_fit,
|
||||||
|
"parse_success": parse_success,
|
||||||
|
"config": cfg,
|
||||||
|
"gens_df": gens,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _convergence_figure(gens_df: Any) -> go.Figure:
|
||||||
|
fig = go.Figure()
|
||||||
|
if gens_df.empty:
|
||||||
|
fig.add_annotation(
|
||||||
|
text="Nessuna generazione registrata", x=0.5, y=0.5, showarrow=False,
|
||||||
|
font={"color": COLOR_TEXT_MUTED, "size": 14},
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
fig.add_trace(
|
||||||
|
go.Scatter(
|
||||||
|
x=gens_df["generation_idx"], y=gens_df["fitness_max"],
|
||||||
|
name="max", mode="lines+markers",
|
||||||
|
line={"color": COLOR_PRIMARY, "width": 3, "shape": "spline", "smoothing": 0.6},
|
||||||
|
marker={"size": 9, "color": COLOR_PRIMARY,
|
||||||
|
"line": {"color": "#fff", "width": 1}},
|
||||||
|
fill="tozeroy",
|
||||||
|
fillcolor="rgba(255, 45, 135, 0.12)",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
fig.add_trace(
|
||||||
|
go.Scatter(
|
||||||
|
x=gens_df["generation_idx"], y=gens_df["fitness_p90"],
|
||||||
|
name="p90", mode="lines+markers",
|
||||||
|
line={"color": COLOR_ACCENT, "width": 2, "dash": "dot", "shape": "spline"},
|
||||||
|
marker={"size": 7, "color": COLOR_ACCENT},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
fig.add_trace(
|
||||||
|
go.Scatter(
|
||||||
|
x=gens_df["generation_idx"], y=gens_df["fitness_median"],
|
||||||
|
name="median", mode="lines+markers",
|
||||||
|
line={"color": COLOR_SECONDARY, "width": 2, "shape": "spline"},
|
||||||
|
marker={"size": 7, "color": COLOR_SECONDARY},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
fig.update_layout(
|
||||||
|
template="plotly_dark",
|
||||||
|
paper_bgcolor=COLOR_SURFACE,
|
||||||
|
plot_bgcolor=COLOR_SURFACE,
|
||||||
|
font={"color": COLOR_TEXT},
|
||||||
|
xaxis={"title": "generation", "gridcolor": "rgba(148, 163, 184, 0.08)", "dtick": 1},
|
||||||
|
yaxis={"title": "fitness", "gridcolor": "rgba(148, 163, 184, 0.08)"},
|
||||||
|
title={"text": "Fitness convergence", "font": {"color": COLOR_TEXT, "size": 18}},
|
||||||
|
legend={"bgcolor": "rgba(19, 19, 26, 0.95)", "bordercolor": COLOR_PRIMARY, "borderwidth": 1},
|
||||||
|
margin={"l": 50, "r": 30, "t": 50, "b": 50},
|
||||||
|
)
|
||||||
|
return fig
|
||||||
|
|
||||||
|
|
||||||
|
def _entropy_figure(gens_df: Any) -> go.Figure:
|
||||||
|
fig = go.Figure()
|
||||||
|
if not gens_df.empty:
|
||||||
|
fig.add_trace(
|
||||||
|
go.Scatter(
|
||||||
|
x=gens_df["generation_idx"], y=gens_df["entropy"],
|
||||||
|
mode="lines+markers",
|
||||||
|
line={"color": COLOR_SECONDARY, "width": 3, "shape": "spline", "smoothing": 0.6},
|
||||||
|
marker={"size": 9, "color": COLOR_SECONDARY,
|
||||||
|
"line": {"color": "#fff", "width": 1}},
|
||||||
|
fill="tozeroy",
|
||||||
|
fillcolor="rgba(0, 217, 255, 0.12)",
|
||||||
|
name="entropy",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
fig.add_hline(
|
||||||
|
y=0.5, line_dash="dash", line_color=COLOR_ACCENT,
|
||||||
|
annotation_text="gate threshold (0.5)",
|
||||||
|
annotation_font_color=COLOR_ACCENT,
|
||||||
|
)
|
||||||
|
fig.update_layout(
|
||||||
|
template="plotly_dark",
|
||||||
|
paper_bgcolor=COLOR_SURFACE,
|
||||||
|
plot_bgcolor=COLOR_SURFACE,
|
||||||
|
font={"color": COLOR_TEXT},
|
||||||
|
xaxis={"title": "generation", "gridcolor": "rgba(148, 163, 184, 0.08)", "dtick": 1},
|
||||||
|
yaxis={"title": "entropy", "gridcolor": "rgba(148, 163, 184, 0.08)"},
|
||||||
|
title={"text": "Diversity (fitness entropy)", "font": {"color": COLOR_TEXT, "size": 18}},
|
||||||
|
margin={"l": 50, "r": 30, "t": 50, "b": 50},
|
||||||
|
)
|
||||||
|
return fig
|
||||||
|
|
||||||
|
|
||||||
|
@ui.page("/")
|
||||||
|
def index() -> None:
|
||||||
|
_apply_theme()
|
||||||
|
_build_header(
|
||||||
|
active="/",
|
||||||
|
brand_subtitle="Coevolutivo / GA",
|
||||||
|
nav_items=[("/", "Overview"), ("/convergence", "Convergence"), ("/genomes", "Genomes")],
|
||||||
|
db_label=f"⛁ {Path(GA_DB_PATH).resolve().name}",
|
||||||
|
)
|
||||||
|
|
||||||
|
options = _runs_options()
|
||||||
|
if not options:
|
||||||
|
ui.label("Nessuna run nel database.").classes("text-h5")
|
||||||
|
return
|
||||||
|
|
||||||
|
state: dict[str, Any] = {"run_id": next(iter(options))}
|
||||||
|
|
||||||
|
with ui.row().classes("w-full items-center gap-4 q-mb-md"):
|
||||||
|
select = ui.select(options=options, value=state["run_id"], label="Run").classes(
|
||||||
|
"flex-grow"
|
||||||
|
)
|
||||||
|
status_badge = ui.badge("…", color="primary").classes("text-body1 q-pa-sm")
|
||||||
|
ui.button("🔄 Refresh", on_click=lambda: refresh()).props("outline color=primary")
|
||||||
|
|
||||||
|
with ui.card().classes("w-full"):
|
||||||
|
ui.label("Progresso run").classes("text-subtitle1")
|
||||||
|
gen_label = ui.label("Generations: 0/0")
|
||||||
|
gen_bar = ui.linear_progress(0.0, show_value=False).props("size=20px color=primary")
|
||||||
|
eval_label = ui.label("Evaluations: 0/0 (0.0%)")
|
||||||
|
eval_bar = ui.linear_progress(0.0, show_value=False).props("size=20px color=accent")
|
||||||
|
|
||||||
|
with ui.row().classes("w-full gap-4"):
|
||||||
|
with ui.card().classes("flex-grow metric-card accent-cyan"):
|
||||||
|
ui.label("Top fitness").classes("text-caption")
|
||||||
|
top_lbl = ui.label("—").classes("text-h4")
|
||||||
|
with ui.card().classes("flex-grow metric-card accent-purple"):
|
||||||
|
ui.label("Median fitness").classes("text-caption")
|
||||||
|
median_lbl = ui.label("—").classes("text-h4")
|
||||||
|
with ui.card().classes("flex-grow metric-card accent-amber"):
|
||||||
|
ui.label("Parse success").classes("text-caption")
|
||||||
|
parse_lbl = ui.label("—").classes("text-h4")
|
||||||
|
with ui.card().classes("flex-grow metric-card accent-green"):
|
||||||
|
ui.label("Cost (USD)").classes("text-caption")
|
||||||
|
cost_lbl = ui.label("—").classes("text-h4")
|
||||||
|
|
||||||
|
with ui.row().classes("w-full gap-4 q-mt-md"):
|
||||||
|
started_lbl = ui.label("Started: —")
|
||||||
|
completed_lbl = ui.label("Completed: —")
|
||||||
|
ui.separator()
|
||||||
|
ui.label("Config").classes("text-subtitle1")
|
||||||
|
cfg_code = ui.html('<pre class="config-block"></pre>').classes("w-full")
|
||||||
|
|
||||||
|
def refresh() -> None:
|
||||||
|
run_id = select.value
|
||||||
|
if not run_id:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
s = _snapshot(run_id)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
ui.notify(f"Errore: {e}", type="negative")
|
||||||
|
return
|
||||||
|
|
||||||
|
text, color = _STATUS_BADGE.get(s["status"], (s["status"], "primary"))
|
||||||
|
status_badge.text = text
|
||||||
|
status_badge.props(f"color={color}")
|
||||||
|
|
||||||
|
gen_frac = min(s["gens_done"] / max(s["n_gens"], 1), 1.0)
|
||||||
|
eval_frac = min(s["evals_done"] / s["evals_total"], 1.0)
|
||||||
|
gen_bar.value = gen_frac
|
||||||
|
eval_bar.value = eval_frac
|
||||||
|
gen_label.text = f"Generations: {s['gens_done']}/{s['n_gens']}"
|
||||||
|
eval_label.text = (
|
||||||
|
f"Evaluations: {s['evals_done']}/{s['evals_total']} ({100 * eval_frac:.1f}%)"
|
||||||
|
)
|
||||||
|
|
||||||
|
top_lbl.text = f"{s['top_fit']:.4f}" if s["evals_done"] else "—"
|
||||||
|
median_lbl.text = f"{s['median_fit']:.4f}" if s["evals_done"] else "—"
|
||||||
|
parse_lbl.text = f"{s['parse_success']:.1f}%" if s["evals_done"] else "—"
|
||||||
|
cost_lbl.text = f"${s['cost_usd']:.4f}"
|
||||||
|
|
||||||
|
started_lbl.text = f"Started: {s['started_at']}"
|
||||||
|
completed_lbl.text = f"Completed: {s['completed_at']}"
|
||||||
|
cfg_code.content = f'<pre class="config-block">{_json_to_html(s["config"])}</pre>'
|
||||||
|
|
||||||
|
def on_select_change() -> None:
|
||||||
|
state["run_id"] = select.value
|
||||||
|
refresh()
|
||||||
|
|
||||||
|
select.on_value_change(on_select_change)
|
||||||
|
ui.timer(REFRESH_INTERVAL_S, refresh)
|
||||||
|
refresh()
|
||||||
|
|
||||||
|
|
||||||
|
@ui.page("/convergence")
|
||||||
|
def convergence() -> None:
|
||||||
|
_apply_theme()
|
||||||
|
_build_header(
|
||||||
|
active="/convergence",
|
||||||
|
brand_subtitle="Coevolutivo / GA",
|
||||||
|
nav_items=[("/", "Overview"), ("/convergence", "Convergence"), ("/genomes", "Genomes")],
|
||||||
|
db_label=f"⛁ {Path(GA_DB_PATH).resolve().name}",
|
||||||
|
)
|
||||||
|
|
||||||
|
options = _runs_options()
|
||||||
|
if not options:
|
||||||
|
ui.label("Nessuna run nel database.").classes("text-h5")
|
||||||
|
return
|
||||||
|
|
||||||
|
state: dict[str, Any] = {"run_id": next(iter(options))}
|
||||||
|
|
||||||
|
with ui.row().classes("w-full items-center gap-4 q-mb-md"):
|
||||||
|
select = ui.select(options=options, value=state["run_id"], label="Run").classes(
|
||||||
|
"flex-grow"
|
||||||
|
)
|
||||||
|
gen_count_lbl = ui.label("Gens: 0/0").classes("text-body1").style(
|
||||||
|
f"color: {COLOR_PRIMARY}; font-weight: 600;"
|
||||||
|
)
|
||||||
|
ui.button("🔄 Refresh", on_click=lambda: refresh()).props("outline color=primary")
|
||||||
|
|
||||||
|
fitness_plot = ui.plotly(_convergence_figure(generations_df(get_repo(GA_DB_PATH), state["run_id"]))).classes("w-full")
|
||||||
|
entropy_plot = ui.plotly(_entropy_figure(generations_df(get_repo(GA_DB_PATH), state["run_id"]))).classes("w-full q-mt-md")
|
||||||
|
|
||||||
|
ui.separator()
|
||||||
|
ui.label("Tabella generazioni").classes("text-subtitle1 q-mt-md")
|
||||||
|
gens_table = ui.table(
|
||||||
|
columns=[
|
||||||
|
{"name": "generation_idx", "label": "gen", "field": "generation_idx", "sortable": True},
|
||||||
|
{"name": "n_genomes", "label": "n", "field": "n_genomes"},
|
||||||
|
{"name": "fitness_max", "label": "max", "field": "fitness_max"},
|
||||||
|
{"name": "fitness_p90", "label": "p90", "field": "fitness_p90"},
|
||||||
|
{"name": "fitness_median", "label": "median", "field": "fitness_median"},
|
||||||
|
{"name": "entropy", "label": "entropy", "field": "entropy"},
|
||||||
|
{"name": "completed_at", "label": "completed", "field": "completed_at"},
|
||||||
|
],
|
||||||
|
rows=[],
|
||||||
|
row_key="generation_idx",
|
||||||
|
).classes("w-full")
|
||||||
|
|
||||||
|
def refresh() -> None:
|
||||||
|
run_id = select.value
|
||||||
|
if not run_id:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
gens = generations_df(get_repo(GA_DB_PATH), run_id)
|
||||||
|
ov = get_run_overview(get_repo(GA_DB_PATH), run_id)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
ui.notify(f"Errore: {e}", type="negative")
|
||||||
|
return
|
||||||
|
|
||||||
|
n_gens = int(ov["config"].get("n_generations", 0))
|
||||||
|
gens_done = int(gens["completed_at"].notna().sum()) if not gens.empty else 0
|
||||||
|
gen_count_lbl.text = f"Gens: {gens_done}/{n_gens}"
|
||||||
|
|
||||||
|
fitness_plot.update_figure(_convergence_figure(gens))
|
||||||
|
entropy_plot.update_figure(_entropy_figure(gens))
|
||||||
|
|
||||||
|
if gens.empty:
|
||||||
|
gens_table.rows = []
|
||||||
|
else:
|
||||||
|
display_cols = [
|
||||||
|
"generation_idx", "n_genomes",
|
||||||
|
"fitness_max", "fitness_p90", "fitness_median",
|
||||||
|
"entropy", "completed_at",
|
||||||
|
]
|
||||||
|
gens_table.rows = [
|
||||||
|
{
|
||||||
|
col: (round(v, 6) if isinstance(v, float) else v)
|
||||||
|
for col, v in row.items()
|
||||||
|
if col in display_cols
|
||||||
|
}
|
||||||
|
for _, row in gens.iterrows()
|
||||||
|
]
|
||||||
|
gens_table.update()
|
||||||
|
|
||||||
|
def on_select_change() -> None:
|
||||||
|
state["run_id"] = select.value
|
||||||
|
refresh()
|
||||||
|
|
||||||
|
select.on_value_change(on_select_change)
|
||||||
|
ui.timer(REFRESH_INTERVAL_S, refresh)
|
||||||
|
refresh()
|
||||||
|
|
||||||
|
|
||||||
|
@ui.page("/genomes")
|
||||||
|
def genomes() -> None:
|
||||||
|
_apply_theme()
|
||||||
|
_build_header(
|
||||||
|
active="/genomes",
|
||||||
|
brand_subtitle="Coevolutivo / GA",
|
||||||
|
nav_items=[("/", "Overview"), ("/convergence", "Convergence"), ("/genomes", "Genomes")],
|
||||||
|
db_label=f"⛁ {Path(GA_DB_PATH).resolve().name}",
|
||||||
|
)
|
||||||
|
|
||||||
|
options = _runs_options()
|
||||||
|
if not options:
|
||||||
|
ui.label("Nessuna run nel database.").classes("text-h5")
|
||||||
|
return
|
||||||
|
|
||||||
|
state: dict[str, Any] = {
|
||||||
|
"run_id": next(iter(options)),
|
||||||
|
"selected_gid": None,
|
||||||
|
"merged": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
with ui.row().classes("w-full items-center gap-4 q-mb-md"):
|
||||||
|
select = ui.select(options=options, value=state["run_id"], label="Run").classes(
|
||||||
|
"flex-grow"
|
||||||
|
)
|
||||||
|
top_k_select = ui.select(
|
||||||
|
options={10: "Top 10", 25: "Top 25", 50: "Top 50"},
|
||||||
|
value=10,
|
||||||
|
label="Top K",
|
||||||
|
)
|
||||||
|
ui.button("🔄 Refresh", on_click=lambda: refresh()).props("outline color=primary")
|
||||||
|
|
||||||
|
ui.label("Top genomi per fitness").classes("text-subtitle1 q-mt-sm")
|
||||||
|
top_table = ui.table(
|
||||||
|
columns=[
|
||||||
|
{"name": "genome_id", "label": "id", "field": "genome_id", "align": "left"},
|
||||||
|
{"name": "fitness", "label": "fitness", "field": "fitness", "sortable": True},
|
||||||
|
{"name": "dsr", "label": "DSR", "field": "dsr"},
|
||||||
|
{"name": "sharpe", "label": "Sharpe", "field": "sharpe"},
|
||||||
|
{"name": "max_dd", "label": "max DD", "field": "max_dd"},
|
||||||
|
{"name": "n_trades", "label": "trades", "field": "n_trades"},
|
||||||
|
{"name": "cognitive_style", "label": "style", "field": "cognitive_style"},
|
||||||
|
{"name": "temperature", "label": "T", "field": "temperature"},
|
||||||
|
{"name": "lookback_window", "label": "lookback", "field": "lookback_window"},
|
||||||
|
],
|
||||||
|
rows=[],
|
||||||
|
row_key="genome_id",
|
||||||
|
selection="single",
|
||||||
|
).classes("w-full")
|
||||||
|
|
||||||
|
ui.separator().classes("q-my-md")
|
||||||
|
|
||||||
|
with ui.card().classes("w-full"):
|
||||||
|
ui.label("Ispezione genoma").classes("text-subtitle1")
|
||||||
|
detail_hint = ui.label("Seleziona un genoma dalla tabella sopra.").classes(
|
||||||
|
"text-caption"
|
||||||
|
).style(f"color: {COLOR_TEXT_MUTED};")
|
||||||
|
|
||||||
|
with ui.row().classes("w-full gap-4 q-mt-sm"):
|
||||||
|
with ui.card().classes("flex-grow metric-card accent-cyan"):
|
||||||
|
ui.label("fitness").classes("text-caption")
|
||||||
|
fit_lbl = ui.label("—").classes("text-h4")
|
||||||
|
with ui.card().classes("flex-grow metric-card accent-purple"):
|
||||||
|
ui.label("DSR").classes("text-caption")
|
||||||
|
dsr_lbl = ui.label("—").classes("text-h4")
|
||||||
|
with ui.card().classes("flex-grow metric-card accent-amber"):
|
||||||
|
ui.label("Sharpe").classes("text-caption")
|
||||||
|
sharpe_lbl = ui.label("—").classes("text-h4")
|
||||||
|
with ui.card().classes("flex-grow metric-card"):
|
||||||
|
ui.label("max DD").classes("text-caption")
|
||||||
|
dd_lbl = ui.label("—").classes("text-h4")
|
||||||
|
with ui.card().classes("flex-grow metric-card accent-green"):
|
||||||
|
ui.label("trades").classes("text-caption")
|
||||||
|
trades_lbl = ui.label("—").classes("text-h4")
|
||||||
|
with ui.card().classes("flex-grow metric-card"):
|
||||||
|
ui.label("style").classes("text-caption")
|
||||||
|
style_lbl = ui.label("—").classes("text-h4")
|
||||||
|
|
||||||
|
ui.label("System prompt").classes("text-subtitle1 q-mt-md")
|
||||||
|
prompt_code = ui.html('<pre class="raw-block">—</pre>').classes("w-full")
|
||||||
|
|
||||||
|
ui.label("Raw LLM output").classes("text-subtitle1 q-mt-md")
|
||||||
|
raw_code = ui.html('<pre class="raw-block">—</pre>').classes("w-full")
|
||||||
|
|
||||||
|
parse_error_lbl = ui.label("").classes("q-mt-sm").style(
|
||||||
|
"color: #FF6B6B; font-weight: 600;"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _render_detail(row: dict[str, Any]) -> None:
|
||||||
|
detail_hint.text = f"Genoma: {row.get('genome_id', '—')}"
|
||||||
|
fit_lbl.text = f"{float(row.get('fitness', 0)):.4f}"
|
||||||
|
dsr_lbl.text = f"{float(row.get('dsr', 0)):.4f}"
|
||||||
|
sharpe_lbl.text = f"{float(row.get('sharpe', 0)):.3f}"
|
||||||
|
dd_lbl.text = f"{float(row.get('max_dd', 0)):.3f}"
|
||||||
|
trades_lbl.text = str(int(row.get("n_trades", 0)))
|
||||||
|
style_lbl.text = str(row.get("cognitive_style", "—"))
|
||||||
|
prompt_code.content = (
|
||||||
|
f'<pre class="raw-block">{html.escape(str(row.get("system_prompt", "—")))}</pre>'
|
||||||
|
)
|
||||||
|
raw_code.content = (
|
||||||
|
f'<pre class="raw-block">{html.escape(str(row.get("raw_text", "—") or "—"))}</pre>'
|
||||||
|
)
|
||||||
|
pe = row.get("parse_error")
|
||||||
|
parse_error_lbl.text = f"❌ Parse error: {pe}" if pe else ""
|
||||||
|
|
||||||
|
def refresh() -> None:
|
||||||
|
run_id = select.value
|
||||||
|
if not run_id:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
repo = get_repo(GA_DB_PATH)
|
||||||
|
evals = evaluations_df(repo, run_id)
|
||||||
|
gens = genomes_df(repo, run_id)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
ui.notify(f"Errore: {e}", type="negative")
|
||||||
|
return
|
||||||
|
|
||||||
|
if evals.empty:
|
||||||
|
top_table.rows = []
|
||||||
|
top_table.update()
|
||||||
|
return
|
||||||
|
|
||||||
|
merged = evals.merge(
|
||||||
|
gens, left_on="genome_id", right_on="id", how="left", suffixes=("", "_g")
|
||||||
|
)
|
||||||
|
state["merged"] = merged
|
||||||
|
|
||||||
|
k = int(top_k_select.value)
|
||||||
|
top = merged.sort_values("fitness", ascending=False).head(k)
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
for _, r in top.iterrows():
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"genome_id": str(r.get("genome_id", "—"))[:12] + "…",
|
||||||
|
"fitness": round(float(r.get("fitness", 0)), 4),
|
||||||
|
"dsr": round(float(r.get("dsr", 0)), 4),
|
||||||
|
"sharpe": round(float(r.get("sharpe", 0)), 3),
|
||||||
|
"max_dd": round(float(r.get("max_dd", 0)), 3),
|
||||||
|
"n_trades": int(r.get("n_trades", 0)),
|
||||||
|
"cognitive_style": str(r.get("cognitive_style", "—")),
|
||||||
|
"temperature": round(float(r.get("temperature", 0)), 2),
|
||||||
|
"lookback_window": int(r.get("lookback_window", 0)),
|
||||||
|
"_full_id": str(r.get("genome_id", "")),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
top_table.rows = rows
|
||||||
|
top_table.update()
|
||||||
|
|
||||||
|
sel = state.get("selected_gid")
|
||||||
|
if sel:
|
||||||
|
match = merged[merged["genome_id"] == sel]
|
||||||
|
if not match.empty:
|
||||||
|
_render_detail(match.iloc[0].to_dict())
|
||||||
|
|
||||||
|
def on_row_selected(e: Any) -> None:
|
||||||
|
rows = (e.args or {}).get("rows") or []
|
||||||
|
if not rows:
|
||||||
|
return
|
||||||
|
full_id = rows[0].get("_full_id")
|
||||||
|
if not full_id:
|
||||||
|
return
|
||||||
|
state["selected_gid"] = full_id
|
||||||
|
merged = state.get("merged")
|
||||||
|
if merged is None:
|
||||||
|
return
|
||||||
|
match = merged[merged["genome_id"] == full_id]
|
||||||
|
if not match.empty:
|
||||||
|
_render_detail(match.iloc[0].to_dict())
|
||||||
|
|
||||||
|
def on_select_change() -> None:
|
||||||
|
state["run_id"] = select.value
|
||||||
|
state["selected_gid"] = None
|
||||||
|
refresh()
|
||||||
|
|
||||||
|
select.on_value_change(on_select_change)
|
||||||
|
top_k_select.on_value_change(lambda _: refresh())
|
||||||
|
top_table.on("selection", on_row_selected)
|
||||||
|
ui.timer(REFRESH_INTERVAL_S, refresh)
|
||||||
|
refresh()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
app.on_startup(
|
||||||
|
lambda: print(
|
||||||
|
f"GA DB: {Path(GA_DB_PATH).resolve()} | root_path: {DASHBOARD_ROOT_PATH or '/'}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
ui.run(
|
||||||
|
host="0.0.0.0",
|
||||||
|
port=int(os.environ.get("SWARM_DASHBOARD_PORT", "8080")),
|
||||||
|
title="Multi-Swarm Core Dashboard",
|
||||||
|
reload=False,
|
||||||
|
show=False,
|
||||||
|
dark=True,
|
||||||
|
root_path=DASHBOARD_ROOT_PATH,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ in {"__main__", "__mp_main__"}:
|
||||||
|
main()
|
||||||
@@ -0,0 +1,383 @@
|
|||||||
|
"""Shared theme module for NiceGUI dashboards.
|
||||||
|
|
||||||
|
Exports palette constants, CSS, and helper functions used by both
|
||||||
|
multi_swarm_core.dashboard and strategy_crypto.frontend dashboards.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from nicegui import ui
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"COLOR_BG",
|
||||||
|
"COLOR_SURFACE",
|
||||||
|
"COLOR_SURFACE_2",
|
||||||
|
"COLOR_BORDER",
|
||||||
|
"COLOR_BORDER_HOVER",
|
||||||
|
"COLOR_PRIMARY",
|
||||||
|
"COLOR_SECONDARY",
|
||||||
|
"COLOR_ACCENT",
|
||||||
|
"COLOR_SUCCESS",
|
||||||
|
"COLOR_DANGER",
|
||||||
|
"COLOR_TEXT",
|
||||||
|
"COLOR_TEXT_MUTED",
|
||||||
|
"_STATUS_BADGE",
|
||||||
|
"_CUSTOM_CSS",
|
||||||
|
"_json_to_html",
|
||||||
|
"_apply_theme",
|
||||||
|
"_build_header",
|
||||||
|
]
|
||||||
|
|
||||||
|
# --- Neon Trading Dashboard palette ---
|
||||||
|
COLOR_BG = "#0A0A0F"
|
||||||
|
COLOR_SURFACE = "#13131A"
|
||||||
|
COLOR_SURFACE_2 = "#1C1C26"
|
||||||
|
COLOR_BORDER = "rgba(255, 45, 135, 0.12)"
|
||||||
|
COLOR_BORDER_HOVER = "rgba(255, 45, 135, 0.45)"
|
||||||
|
COLOR_PRIMARY = "#FF2D87"
|
||||||
|
COLOR_SECONDARY = "#00D9FF"
|
||||||
|
COLOR_ACCENT = "#FFB800"
|
||||||
|
COLOR_SUCCESS = "#00E676"
|
||||||
|
COLOR_DANGER = "#FF3D60"
|
||||||
|
COLOR_TEXT = "#FFFFFF"
|
||||||
|
COLOR_TEXT_MUTED = "#7A7A8C"
|
||||||
|
|
||||||
|
_STATUS_BADGE: dict[str, tuple[str, str]] = {
|
||||||
|
"running": ("● running", "positive"),
|
||||||
|
"completed": ("✓ completed", "positive"),
|
||||||
|
"failed": ("✕ failed", "negative"),
|
||||||
|
}
|
||||||
|
|
||||||
|
_CUSTOM_CSS = f"""
|
||||||
|
<style>
|
||||||
|
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
|
||||||
|
|
||||||
|
html, body, .q-page, .q-card, .q-btn, .q-field, .q-table, .text-h4, .text-h6, .text-subtitle1, .text-caption, .text-body1, .nav-link, .brand, label, p, span, div {{
|
||||||
|
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
|
||||||
|
letter-spacing: -0.01em;
|
||||||
|
}}
|
||||||
|
.material-icons, .material-icons-outlined, .material-symbols-outlined, .q-icon, i.q-icon, i[class*="material"] {{
|
||||||
|
font-family: 'Material Icons' !important;
|
||||||
|
font-feature-settings: 'liga';
|
||||||
|
letter-spacing: normal !important;
|
||||||
|
}}
|
||||||
|
code, pre, .q-code, .nicegui-code {{ font-family: 'JetBrains Mono', 'Fira Code', monospace !important; font-size: 13.5px !important; }}
|
||||||
|
|
||||||
|
body, .q-page-container, .q-page {{
|
||||||
|
background: {COLOR_BG} !important;
|
||||||
|
color: {COLOR_TEXT};
|
||||||
|
background-image:
|
||||||
|
radial-gradient(ellipse 800px 400px at 20% 0%, rgba(255, 45, 135, 0.08) 0%, transparent 60%),
|
||||||
|
radial-gradient(ellipse 600px 400px at 80% 100%, rgba(0, 217, 255, 0.06) 0%, transparent 60%);
|
||||||
|
background-attachment: fixed;
|
||||||
|
}}
|
||||||
|
|
||||||
|
.q-card {{
|
||||||
|
background: {COLOR_SURFACE} !important;
|
||||||
|
color: {COLOR_TEXT} !important;
|
||||||
|
border: 1px solid {COLOR_BORDER};
|
||||||
|
border-radius: 14px !important;
|
||||||
|
box-shadow:
|
||||||
|
0 1px 2px rgba(0,0,0,0.5),
|
||||||
|
0 8px 24px rgba(0,0,0,0.25),
|
||||||
|
inset 0 1px 0 rgba(255,255,255,0.04);
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
}}
|
||||||
|
.q-card::before {{
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
top: 0; left: 0; right: 0;
|
||||||
|
height: 1px;
|
||||||
|
background: linear-gradient(90deg, transparent, rgba(255, 45, 135, 0.4), transparent);
|
||||||
|
opacity: 0.5;
|
||||||
|
}}
|
||||||
|
.q-card:hover {{
|
||||||
|
border-color: rgba(255, 45, 135, 0.5);
|
||||||
|
box-shadow:
|
||||||
|
0 1px 2px rgba(0,0,0,0.5),
|
||||||
|
0 8px 32px rgba(255, 45, 135, 0.15),
|
||||||
|
inset 0 1px 0 rgba(255,255,255,0.05);
|
||||||
|
}}
|
||||||
|
|
||||||
|
.metric-card {{
|
||||||
|
padding: 20px 16px;
|
||||||
|
text-align: left;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 140px;
|
||||||
|
}}
|
||||||
|
.metric-card .text-caption {{
|
||||||
|
color: {COLOR_TEXT_MUTED} !important;
|
||||||
|
font-size: 11px !important;
|
||||||
|
font-weight: 500 !important;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
}}
|
||||||
|
.metric-card .text-h4 {{
|
||||||
|
color: {COLOR_TEXT} !important;
|
||||||
|
font-weight: 600 !important;
|
||||||
|
font-size: 26px !important;
|
||||||
|
line-height: 1.2 !important;
|
||||||
|
font-feature-settings: 'tnum';
|
||||||
|
}}
|
||||||
|
.metric-card.accent-cyan .text-h4 {{ color: {COLOR_PRIMARY} !important; }}
|
||||||
|
.metric-card.accent-purple .text-h4 {{ color: {COLOR_SECONDARY} !important; }}
|
||||||
|
.metric-card.accent-amber .text-h4 {{ color: {COLOR_ACCENT} !important; }}
|
||||||
|
.metric-card.accent-green .text-h4 {{ color: {COLOR_SUCCESS} !important; }}
|
||||||
|
|
||||||
|
.q-header {{
|
||||||
|
background: rgba(10, 10, 15, 0.75) !important;
|
||||||
|
backdrop-filter: blur(20px) saturate(180%);
|
||||||
|
-webkit-backdrop-filter: blur(20px) saturate(180%);
|
||||||
|
border-bottom: 1px solid {COLOR_BORDER} !important;
|
||||||
|
box-shadow: 0 1px 0 rgba(255, 45, 135, 0.15) !important;
|
||||||
|
}}
|
||||||
|
|
||||||
|
.nav-link {{
|
||||||
|
color: {COLOR_TEXT_MUTED} !important;
|
||||||
|
padding: 8px 14px;
|
||||||
|
border-radius: 8px;
|
||||||
|
text-decoration: none;
|
||||||
|
font-size: 13.5px;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: all 0.15s ease;
|
||||||
|
position: relative;
|
||||||
|
}}
|
||||||
|
.nav-link:hover {{
|
||||||
|
color: {COLOR_TEXT} !important;
|
||||||
|
background: {COLOR_SURFACE_2};
|
||||||
|
}}
|
||||||
|
.nav-link.active {{
|
||||||
|
color: {COLOR_PRIMARY} !important;
|
||||||
|
background: rgba(255, 45, 135, 0.08);
|
||||||
|
}}
|
||||||
|
.nav-link.active::after {{
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
bottom: -16px;
|
||||||
|
left: 14px;
|
||||||
|
right: 14px;
|
||||||
|
height: 2px;
|
||||||
|
background: {COLOR_PRIMARY};
|
||||||
|
border-radius: 2px 2px 0 0;
|
||||||
|
}}
|
||||||
|
|
||||||
|
.brand {{
|
||||||
|
color: {COLOR_TEXT};
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 15px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}}
|
||||||
|
.brand-dot {{
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: {COLOR_PRIMARY};
|
||||||
|
box-shadow: 0 0 16px {COLOR_PRIMARY}, 0 0 4px {COLOR_PRIMARY};
|
||||||
|
animation: pulse-pink 2s ease-in-out infinite;
|
||||||
|
}}
|
||||||
|
@keyframes pulse-pink {{
|
||||||
|
0%, 100% {{ box-shadow: 0 0 16px {COLOR_PRIMARY}, 0 0 4px {COLOR_PRIMARY}; }}
|
||||||
|
50% {{ box-shadow: 0 0 24px {COLOR_PRIMARY}, 0 0 8px {COLOR_PRIMARY}; }}
|
||||||
|
}}
|
||||||
|
|
||||||
|
.q-linear-progress {{ height: 8px !important; border-radius: 6px !important; }}
|
||||||
|
.q-linear-progress__track {{ background: {COLOR_SURFACE_2} !important; }}
|
||||||
|
.q-linear-progress__model {{ border-radius: 6px !important; }}
|
||||||
|
|
||||||
|
.q-separator {{ background: {COLOR_BORDER} !important; }}
|
||||||
|
|
||||||
|
.q-field--outlined .q-field__control {{
|
||||||
|
background: {COLOR_SURFACE} !important;
|
||||||
|
border-radius: 8px !important;
|
||||||
|
}}
|
||||||
|
.q-field--outlined .q-field__control:before {{ border-color: {COLOR_BORDER} !important; }}
|
||||||
|
.q-field--outlined.q-field--focused .q-field__control:after {{ border-color: {COLOR_PRIMARY} !important; }}
|
||||||
|
.q-field__label {{ color: {COLOR_TEXT_MUTED} !important; }}
|
||||||
|
.q-field__native, .q-field__input {{ color: {COLOR_TEXT} !important; }}
|
||||||
|
|
||||||
|
.q-btn {{ border-radius: 8px !important; font-weight: 500 !important; text-transform: none !important; letter-spacing: 0 !important; }}
|
||||||
|
|
||||||
|
.q-table {{ background: transparent !important; color: {COLOR_TEXT} !important; }}
|
||||||
|
.q-table thead tr {{ background: {COLOR_SURFACE_2} !important; }}
|
||||||
|
.q-table th {{
|
||||||
|
color: {COLOR_TEXT_MUTED} !important;
|
||||||
|
font-size: 11px !important;
|
||||||
|
font-weight: 600 !important;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
}}
|
||||||
|
.q-table tbody tr {{ transition: background 0.15s; }}
|
||||||
|
.q-table tbody tr:hover {{ background: rgba(255, 45, 135, 0.05) !important; }}
|
||||||
|
.q-table tbody tr.selected {{ background: rgba(255, 45, 135, 0.12) !important; }}
|
||||||
|
.q-table td {{ border-bottom: 1px solid {COLOR_BORDER} !important; font-feature-settings: 'tnum'; }}
|
||||||
|
|
||||||
|
.text-h6 {{ font-weight: 600 !important; letter-spacing: -0.015em !important; }}
|
||||||
|
.text-subtitle1 {{
|
||||||
|
color: {COLOR_TEXT_MUTED} !important;
|
||||||
|
font-size: 11px !important;
|
||||||
|
font-weight: 600 !important;
|
||||||
|
text-transform: uppercase !important;
|
||||||
|
letter-spacing: 0.08em !important;
|
||||||
|
margin-bottom: 8px !important;
|
||||||
|
}}
|
||||||
|
|
||||||
|
code, pre, .nicegui-code {{
|
||||||
|
background: #1A1A24 !important;
|
||||||
|
color: {COLOR_TEXT} !important;
|
||||||
|
border: 1px solid {COLOR_BORDER};
|
||||||
|
border-radius: 10px !important;
|
||||||
|
padding: 16px !important;
|
||||||
|
font-size: 13.5px !important;
|
||||||
|
line-height: 1.6 !important;
|
||||||
|
}}
|
||||||
|
.hljs {{ background: transparent !important; color: {COLOR_TEXT} !important; }}
|
||||||
|
.hljs-attr, .hljs-attribute {{ color: {COLOR_SECONDARY} !important; font-weight: 500; }}
|
||||||
|
.hljs-string {{ color: {COLOR_SUCCESS} !important; }}
|
||||||
|
.hljs-number, .hljs-literal {{ color: {COLOR_PRIMARY} !important; font-weight: 500; }}
|
||||||
|
.hljs-keyword, .hljs-built_in {{ color: {COLOR_ACCENT} !important; }}
|
||||||
|
.hljs-punctuation, .hljs-meta {{ color: {COLOR_TEXT_MUTED} !important; }}
|
||||||
|
.hljs-comment {{ color: {COLOR_TEXT_MUTED} !important; font-style: italic; }}
|
||||||
|
.hljs-name, .hljs-title {{ color: {COLOR_PRIMARY} !important; }}
|
||||||
|
|
||||||
|
/* Prism.js tokens (NiceGUI usa Prism per ui.code) */
|
||||||
|
.token.property, .token.attr-name, .token.tag {{ color: {COLOR_SECONDARY} !important; font-weight: 500; }}
|
||||||
|
.token.string, .token.url {{ color: {COLOR_SUCCESS} !important; }}
|
||||||
|
.token.number, .token.boolean, .token.null, .token.symbol {{ color: {COLOR_PRIMARY} !important; font-weight: 500; }}
|
||||||
|
.token.keyword, .token.constant, .token.builtin, .token.atrule {{ color: {COLOR_ACCENT} !important; }}
|
||||||
|
.token.punctuation, .token.operator {{ color: {COLOR_TEXT_MUTED} !important; }}
|
||||||
|
.token.comment {{ color: {COLOR_TEXT_MUTED} !important; font-style: italic; }}
|
||||||
|
.token.function, .token.class-name {{ color: {COLOR_PRIMARY} !important; }}
|
||||||
|
pre[class*="language-"], code[class*="language-"] {{
|
||||||
|
color: {COLOR_TEXT} !important;
|
||||||
|
text-shadow: none !important;
|
||||||
|
}}
|
||||||
|
|
||||||
|
.q-badge {{ border-radius: 6px !important; font-weight: 500 !important; padding: 4px 10px !important; font-size: 12px !important; }}
|
||||||
|
|
||||||
|
.config-block {{
|
||||||
|
background: #1A1A24;
|
||||||
|
color: {COLOR_TEXT};
|
||||||
|
border: 1px solid {COLOR_BORDER};
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 18px 20px;
|
||||||
|
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||||
|
font-size: 13.5px;
|
||||||
|
line-height: 1.7;
|
||||||
|
overflow-x: auto;
|
||||||
|
white-space: pre;
|
||||||
|
margin: 0;
|
||||||
|
}}
|
||||||
|
.config-block .cb-key {{ color: {COLOR_SECONDARY}; font-weight: 500; }}
|
||||||
|
.config-block .cb-string {{ color: {COLOR_SUCCESS}; }}
|
||||||
|
.config-block .cb-number {{ color: {COLOR_PRIMARY}; font-weight: 500; }}
|
||||||
|
.config-block .cb-bool {{ color: {COLOR_ACCENT}; }}
|
||||||
|
.config-block .cb-null {{ color: {COLOR_ACCENT}; font-style: italic; }}
|
||||||
|
.config-block .cb-punct {{ color: {COLOR_TEXT_MUTED}; }}
|
||||||
|
|
||||||
|
.raw-block {{
|
||||||
|
background: #1A1A24;
|
||||||
|
color: {COLOR_TEXT};
|
||||||
|
border: 1px solid {COLOR_BORDER};
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 18px 20px;
|
||||||
|
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.6;
|
||||||
|
overflow-x: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
max-height: 400px;
|
||||||
|
overflow-y: auto;
|
||||||
|
margin: 0;
|
||||||
|
}}
|
||||||
|
</style>
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _json_to_html(obj: Any, indent: int = 0) -> str:
|
||||||
|
"""Render JSON con span colorati espliciti. Garantisce leggibilità ovunque."""
|
||||||
|
pad = " " * indent
|
||||||
|
inner_pad = " " * (indent + 1)
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
if not obj:
|
||||||
|
return '<span class="cb-punct">{}</span>'
|
||||||
|
items = []
|
||||||
|
for k, v in obj.items():
|
||||||
|
key = f'<span class="cb-key">"{html.escape(str(k))}"</span>'
|
||||||
|
val = _json_to_html(v, indent + 1)
|
||||||
|
items.append(f"{inner_pad}{key}<span class=\"cb-punct\">:</span> {val}")
|
||||||
|
return ('<span class="cb-punct">{</span>\n'
|
||||||
|
+ '<span class="cb-punct">,</span>\n'.join(items)
|
||||||
|
+ f'\n{pad}<span class="cb-punct">}}</span>')
|
||||||
|
if isinstance(obj, list):
|
||||||
|
if not obj:
|
||||||
|
return '<span class="cb-punct">[]</span>'
|
||||||
|
items = [_json_to_html(x, indent + 1) for x in obj]
|
||||||
|
return ('<span class="cb-punct">[</span>\n'
|
||||||
|
+ '<span class="cb-punct">,</span>\n'.join(inner_pad + i for i in items)
|
||||||
|
+ f'\n{pad}<span class="cb-punct">]</span>')
|
||||||
|
if isinstance(obj, bool):
|
||||||
|
return f'<span class="cb-bool">{str(obj).lower()}</span>'
|
||||||
|
if obj is None:
|
||||||
|
return '<span class="cb-null">null</span>'
|
||||||
|
if isinstance(obj, (int, float)):
|
||||||
|
return f'<span class="cb-number">{obj}</span>'
|
||||||
|
return f'<span class="cb-string">"{html.escape(str(obj))}"</span>'
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_theme() -> None:
|
||||||
|
ui.add_head_html(_CUSTOM_CSS)
|
||||||
|
ui.dark_mode().enable()
|
||||||
|
ui.colors(
|
||||||
|
primary=COLOR_PRIMARY,
|
||||||
|
secondary=COLOR_SECONDARY,
|
||||||
|
accent=COLOR_ACCENT,
|
||||||
|
dark=COLOR_BG,
|
||||||
|
dark_page=COLOR_BG,
|
||||||
|
positive=COLOR_SUCCESS,
|
||||||
|
negative=COLOR_DANGER,
|
||||||
|
info=COLOR_PRIMARY,
|
||||||
|
warning=COLOR_ACCENT,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_header(
|
||||||
|
active: str,
|
||||||
|
brand_subtitle: str,
|
||||||
|
nav_items: list[tuple[str, str]],
|
||||||
|
db_label: str,
|
||||||
|
) -> None:
|
||||||
|
"""Render the top navigation header.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
active: URL path of the currently active page (e.g. "/").
|
||||||
|
brand_subtitle: Text shown after the brand dot, e.g. "Coevolutivo / GA".
|
||||||
|
nav_items: List of (path, label) tuples for nav links.
|
||||||
|
db_label: Short DB identifier shown in the top-right corner.
|
||||||
|
"""
|
||||||
|
with ui.header().classes("items-center justify-between q-px-lg q-py-md"):
|
||||||
|
with ui.row().classes("items-center gap-8"):
|
||||||
|
with ui.row().classes("items-center gap-2").classes("brand"):
|
||||||
|
ui.html('<span class="brand-dot"></span>')
|
||||||
|
ui.html(
|
||||||
|
f'<span class="brand">Multi-Swarm <span style="color:{COLOR_TEXT_MUTED}'
|
||||||
|
f';font-weight:400;">/ {brand_subtitle}</span></span>'
|
||||||
|
)
|
||||||
|
with ui.row().classes("items-center gap-1"):
|
||||||
|
for path, label in nav_items:
|
||||||
|
cls = "nav-link active" if active == path else "nav-link"
|
||||||
|
ui.link(label, path).classes(cls)
|
||||||
|
with ui.row().classes("items-center gap-3"):
|
||||||
|
ui.html(
|
||||||
|
f'<span style="color:{COLOR_TEXT_MUTED};font-size:12px;'
|
||||||
|
f'font-family:JetBrains Mono,monospace;">{db_label}</span>'
|
||||||
|
)
|
||||||
+15
-30
@@ -3,34 +3,12 @@ from __future__ import annotations
|
|||||||
import random
|
import random
|
||||||
|
|
||||||
from ..genome.hypothesis import HypothesisAgentGenome, ModelTier
|
from ..genome.hypothesis import HypothesisAgentGenome, ModelTier
|
||||||
from ..genome.mutation import COGNITIVE_STYLES
|
from ..genome.prompt_library import PromptLibrary
|
||||||
|
|
||||||
STYLE_PROMPTS: dict[str, str] = {
|
# Mantenuto come alias backcompat: equivalente a PromptLibrary.default().styles.
|
||||||
"physicist": (
|
# Nuovi caller dovrebbero usare PromptLibrary direttamente per supportare
|
||||||
"Cerca leggi conservative, simmetrie, regimi di scala. "
|
# l'override via prompts.json di una strategia.
|
||||||
"Pensa in termini di flussi e potenziali."
|
STYLE_PROMPTS: dict[str, str] = PromptLibrary.default().styles
|
||||||
),
|
|
||||||
"biologist": (
|
|
||||||
"Cerca pattern adattivi, nicchie ecologiche, "
|
|
||||||
"predator-prey dynamics tra partecipanti del mercato."
|
|
||||||
),
|
|
||||||
"historian": (
|
|
||||||
"Cerca pattern ricorrenti su scale temporali multiple, "
|
|
||||||
"analogie con regimi storici, mean reversion strutturali."
|
|
||||||
),
|
|
||||||
"meteorologist": (
|
|
||||||
"Cerca regimi di volatilità che si autoalimentano, "
|
|
||||||
"transizioni di stato come fronti, persistenza locale."
|
|
||||||
),
|
|
||||||
"ecologist": (
|
|
||||||
"Cerca interazioni multi-asset, correlazioni cluster, "
|
|
||||||
"segnali di stress sistemico nelle dinamiche di flusso."
|
|
||||||
),
|
|
||||||
"engineer": (
|
|
||||||
"Cerca segnali con rapporto S/N favorevole, filtri causali, "
|
|
||||||
"robustezza a perturbazioni di calibrazione."
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def build_initial_population(
|
def build_initial_population(
|
||||||
@@ -38,15 +16,22 @@ def build_initial_population(
|
|||||||
model_tier: ModelTier,
|
model_tier: ModelTier,
|
||||||
rng: random.Random,
|
rng: random.Random,
|
||||||
feature_pool: tuple[str, ...] = ("close", "high", "low", "volume"),
|
feature_pool: tuple[str, ...] = ("close", "high", "low", "volume"),
|
||||||
|
prompt_library: PromptLibrary | None = None,
|
||||||
) -> list[HypothesisAgentGenome]:
|
) -> list[HypothesisAgentGenome]:
|
||||||
"""Costruisce una popolazione iniziale K varia per stile cognitivo + parametri."""
|
"""Costruisce una popolazione iniziale K varia per stile cognitivo + parametri.
|
||||||
|
|
||||||
|
``prompt_library`` controlla quali stili sono disponibili e quale system_prompt
|
||||||
|
iniziale viene assegnato. Default = builtin 6 stili (physicist, biologist, ...).
|
||||||
|
Override tipico: ``PromptLibrary.from_json(strategy_crypto/prompts.json)``.
|
||||||
|
"""
|
||||||
|
lib = prompt_library or PromptLibrary.default()
|
||||||
population: list[HypothesisAgentGenome] = []
|
population: list[HypothesisAgentGenome] = []
|
||||||
for i in range(k):
|
for i in range(k):
|
||||||
style = COGNITIVE_STYLES[i % len(COGNITIVE_STYLES)]
|
style = lib.style_at(i)
|
||||||
n_features = rng.randint(1, len(feature_pool))
|
n_features = rng.randint(1, len(feature_pool))
|
||||||
feats = sorted(rng.sample(feature_pool, k=n_features))
|
feats = sorted(rng.sample(feature_pool, k=n_features))
|
||||||
g = HypothesisAgentGenome(
|
g = HypothesisAgentGenome(
|
||||||
system_prompt=STYLE_PROMPTS[style],
|
system_prompt=lib.directive(style),
|
||||||
feature_access=feats,
|
feature_access=feats,
|
||||||
temperature=round(rng.uniform(0.7, 1.2), 2),
|
temperature=round(rng.uniform(0.7, 1.2), 2),
|
||||||
top_p=0.95,
|
top_p=0.95,
|
||||||
+16
@@ -7,6 +7,10 @@ from .hypothesis import HypothesisAgentGenome
|
|||||||
|
|
||||||
FEATURE_POOL: tuple[str, ...] = ("open", "high", "low", "close", "volume")
|
FEATURE_POOL: tuple[str, ...] = ("open", "high", "low", "close", "volume")
|
||||||
|
|
||||||
|
# Lista di default builtin (allineata con PromptLibrary.default()).
|
||||||
|
# Il dispatcher run_phase1 sovrascrive `COGNITIVE_STYLES` con la lista letta
|
||||||
|
# da prompts.json prima del loop GA, cosi' `mutate_cognitive_style` pesca
|
||||||
|
# dai candidati corretti per la strategia in corso.
|
||||||
COGNITIVE_STYLES: tuple[str, ...] = (
|
COGNITIVE_STYLES: tuple[str, ...] = (
|
||||||
"physicist",
|
"physicist",
|
||||||
"biologist",
|
"biologist",
|
||||||
@@ -17,6 +21,18 @@ COGNITIVE_STYLES: tuple[str, ...] = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def set_cognitive_styles(styles: tuple[str, ...]) -> None:
|
||||||
|
"""Sovrascrive la lista globale di stili candidati per la mutation.
|
||||||
|
|
||||||
|
Da chiamare PRIMA del GA loop (es. in run_phase1 dopo aver caricato la
|
||||||
|
PromptLibrary). Non thread-safe: pensata per uno script CLI.
|
||||||
|
"""
|
||||||
|
global COGNITIVE_STYLES
|
||||||
|
if not styles:
|
||||||
|
raise ValueError("set_cognitive_styles: lista vuota")
|
||||||
|
COGNITIVE_STYLES = tuple(styles)
|
||||||
|
|
||||||
|
|
||||||
def _clone_with(g: HypothesisAgentGenome, **overrides: Any) -> HypothesisAgentGenome:
|
def _clone_with(g: HypothesisAgentGenome, **overrides: Any) -> HypothesisAgentGenome:
|
||||||
payload: dict[str, Any] = g.to_dict()
|
payload: dict[str, Any] = g.to_dict()
|
||||||
payload.update(overrides)
|
payload.update(overrides)
|
||||||
+3
-2
@@ -51,8 +51,9 @@ MUTATION_INSTRUCTIONS: dict[str, str] = {
|
|||||||
|
|
||||||
# Keyword tecniche minime per validare che il prompt sia ancora "una strategia".
|
# Keyword tecniche minime per validare che il prompt sia ancora "una strategia".
|
||||||
_VALID_KEYWORDS = (
|
_VALID_KEYWORDS = (
|
||||||
"rsi", "sma", "ema", "atr", "momentum", "breakout", "mean", "reversion",
|
"rsi", "sma", "sma_pct", "ema", "atr", "atr_pct", "realized_vol",
|
||||||
"macd", "vwap", "bb", "bollinger", "stoch", "trend", "signal", "buy",
|
"momentum", "breakout", "mean", "reversion",
|
||||||
|
"macd", "macd_pct", "vwap", "bb", "bollinger", "stoch", "trend", "signal", "buy",
|
||||||
"sell", "long", "short", "entry", "exit", "stop", "rule", "condition",
|
"sell", "long", "short", "entry", "exit", "stop", "rule", "condition",
|
||||||
"if", "when", "and", "or", "gt", "lt", ">", "<", "ge", "le",
|
"if", "when", "and", "or", "gt", "lt", ">", "<", "ge", "le",
|
||||||
"hour", "dow", "weekend", "indicator", "feature",
|
"hour", "dow", "weekend", "indicator", "feature",
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
"""Libreria di stili cognitivi + direttive system_prompt per il GA.
|
||||||
|
|
||||||
|
Carica da un file JSON esterno (tipicamente shippato dal singolo strategy
|
||||||
|
member, es. ``strategy_crypto/prompts.json``) le coppie ``style -> directive``
|
||||||
|
usate da:
|
||||||
|
- :func:`multi_swarm_core.ga.initial.build_initial_population` per il
|
||||||
|
bootstrap della popolazione (style assegnato round-robin, directive
|
||||||
|
come system_prompt iniziale).
|
||||||
|
- :func:`multi_swarm_core.genome.mutation.mutate_cognitive_style` per
|
||||||
|
pescare i candidati di mutazione (range = key del JSON).
|
||||||
|
|
||||||
|
Schema JSON atteso::
|
||||||
|
|
||||||
|
{
|
||||||
|
"styles": {
|
||||||
|
"<name>": {"directive": "<testo system_prompt>"},
|
||||||
|
...
|
||||||
|
},
|
||||||
|
"agent_role": "<descrizione agente, opzionale>",
|
||||||
|
"pattern_guidance": "<sezione PATTERN GUIDANCE, opzionale>",
|
||||||
|
"instruction": "<frase finale USER, opzionale>",
|
||||||
|
"domain_warnings": "<warning di dominio, opzionale>"
|
||||||
|
}
|
||||||
|
|
||||||
|
I 6 stili default (physicist, biologist, historian, meteorologist,
|
||||||
|
ecologist, engineer) sono comunque disponibili via :meth:`PromptLibrary.default`
|
||||||
|
per backcompat con test/script senza file esterno.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_DEFAULT_STYLES: dict[str, str] = {
|
||||||
|
"physicist": (
|
||||||
|
"Cerca leggi conservative, simmetrie, regimi di scala. "
|
||||||
|
"Pensa in termini di flussi e potenziali."
|
||||||
|
),
|
||||||
|
"biologist": (
|
||||||
|
"Cerca pattern adattivi, nicchie ecologiche, "
|
||||||
|
"predator-prey dynamics tra partecipanti del mercato."
|
||||||
|
),
|
||||||
|
"historian": (
|
||||||
|
"Cerca pattern ricorrenti su scale temporali multiple, "
|
||||||
|
"analogie con regimi storici, mean reversion strutturali."
|
||||||
|
),
|
||||||
|
"meteorologist": (
|
||||||
|
"Cerca regimi di volatilità che si autoalimentano, "
|
||||||
|
"transizioni di stato come fronti, persistenza locale."
|
||||||
|
),
|
||||||
|
"ecologist": (
|
||||||
|
"Cerca interazioni multi-asset, correlazioni cluster, "
|
||||||
|
"segnali di stress sistemico nelle dinamiche di flusso."
|
||||||
|
),
|
||||||
|
"engineer": (
|
||||||
|
"Cerca segnali con rapporto S/N favorevole, filtri causali, "
|
||||||
|
"robustezza a perturbazioni di calibrazione."
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class PromptLibraryError(ValueError):
|
||||||
|
"""Sollevata su JSON malformato o stili invalid."""
|
||||||
|
|
||||||
|
|
||||||
|
_DEFAULT_PATTERN_GUIDANCE = (
|
||||||
|
"Forme di curva: trend (SMA cross), compressione volatilita (atr_pct basso), "
|
||||||
|
"espansione volatilita (atr_pct alto), mean reversion (sma_pct estremo), "
|
||||||
|
"momentum (macd_pct, rsi zone).\n\n"
|
||||||
|
" Ripetibilita dell'andamento: crossover/crossunder ricorrenti, pattern intra-day "
|
||||||
|
"(hour gate), pattern settimanali (dow/is_weekend), range breakout."
|
||||||
|
)
|
||||||
|
|
||||||
|
_DEFAULT_AGENT_ROLE = (
|
||||||
|
"Sei un agente generatore di ipotesi di trading quantitativo per un sistema swarm."
|
||||||
|
)
|
||||||
|
|
||||||
|
_DEFAULT_INSTRUCTION = (
|
||||||
|
"Genera una strategia che cerchi anomalie sfruttabili in questo regime."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PromptLibrary:
|
||||||
|
"""Set immutabile di stili cognitivi + direttive system_prompt.
|
||||||
|
|
||||||
|
v3.0: aggiunge 4 campi top-level strategy-specific iniettabili nel prompt
|
||||||
|
dal compositor ``_build_system_prompt``. Tutti opzionali con default sensati
|
||||||
|
per backcompat.
|
||||||
|
v3.1: aggiunge anti_patterns e output_priorities iniettati dopo i VINCOLI core.
|
||||||
|
"""
|
||||||
|
|
||||||
|
styles: dict[str, str]
|
||||||
|
focus: dict[str, list[str]] # style -> lista metriche prioritarie
|
||||||
|
# NEW v3.0: contenuto strategy-specific iniettabile nel prompt
|
||||||
|
agent_role: str = field(default="") # header SYSTEM, descrive chi e' l'agente
|
||||||
|
pattern_guidance: str = field(default="") # sezione PATTERN GUIDANCE del SYSTEM
|
||||||
|
instruction: str = field(default="") # frase finale USER ("Genera una strategia...")
|
||||||
|
domain_warnings: str = field(default="") # opzionale: warning di dominio (es. crypto 24/7)
|
||||||
|
anti_patterns: str = field(default="") # NEW v3.1: lista esplicita di pattern da evitare
|
||||||
|
output_priorities: str = field(default="") # NEW v3.1: trade-off espliciti di output
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if not self.styles:
|
||||||
|
raise PromptLibraryError("PromptLibrary deve avere almeno uno stile")
|
||||||
|
for name, directive in self.styles.items():
|
||||||
|
if not isinstance(name, str) or not name.strip():
|
||||||
|
raise PromptLibraryError(f"nome stile invalido: {name!r}")
|
||||||
|
if not isinstance(directive, str) or not directive.strip():
|
||||||
|
raise PromptLibraryError(
|
||||||
|
f"directive vuota o invalida per stile {name!r}"
|
||||||
|
)
|
||||||
|
# Validate new optional string fields: if provided must be non-whitespace
|
||||||
|
for field_name, value in (
|
||||||
|
("agent_role", self.agent_role),
|
||||||
|
("pattern_guidance", self.pattern_guidance),
|
||||||
|
("instruction", self.instruction),
|
||||||
|
("domain_warnings", self.domain_warnings),
|
||||||
|
("anti_patterns", self.anti_patterns),
|
||||||
|
("output_priorities", self.output_priorities),
|
||||||
|
):
|
||||||
|
if not isinstance(value, str):
|
||||||
|
raise PromptLibraryError(
|
||||||
|
f"campo '{field_name}' deve essere stringa, non {type(value)}"
|
||||||
|
)
|
||||||
|
if value and not value.strip():
|
||||||
|
raise PromptLibraryError(
|
||||||
|
f"campo '{field_name}' fornito ma contiene solo whitespace"
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def default(cls) -> PromptLibrary:
|
||||||
|
"""Libreria builtin con i 6 stili originali (fallback senza file)."""
|
||||||
|
return cls(
|
||||||
|
styles=dict(_DEFAULT_STYLES),
|
||||||
|
focus={},
|
||||||
|
agent_role=_DEFAULT_AGENT_ROLE,
|
||||||
|
pattern_guidance=_DEFAULT_PATTERN_GUIDANCE,
|
||||||
|
instruction=_DEFAULT_INSTRUCTION,
|
||||||
|
domain_warnings="",
|
||||||
|
anti_patterns="",
|
||||||
|
output_priorities="",
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_json(cls, path: Path | str) -> PromptLibrary:
|
||||||
|
"""Carica da file JSON.
|
||||||
|
|
||||||
|
Schema::
|
||||||
|
|
||||||
|
{
|
||||||
|
"styles": {<name>: {"directive": "...", "focus_metrics": [...]}},
|
||||||
|
"agent_role": "...", // opzionale
|
||||||
|
"pattern_guidance": "...", // opzionale
|
||||||
|
"instruction": "...", // opzionale
|
||||||
|
"domain_warnings": "..." // opzionale
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
p = Path(path)
|
||||||
|
try:
|
||||||
|
data = json.loads(p.read_text(encoding="utf-8"))
|
||||||
|
except FileNotFoundError as e:
|
||||||
|
raise PromptLibraryError(f"file non trovato: {p}") from e
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
raise PromptLibraryError(f"JSON malformato in {p}: {e}") from e
|
||||||
|
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise PromptLibraryError(f"root JSON deve essere un object, non {type(data)}")
|
||||||
|
styles_raw = data.get("styles")
|
||||||
|
if not isinstance(styles_raw, dict):
|
||||||
|
raise PromptLibraryError("manca chiave 'styles' (object) nel JSON")
|
||||||
|
|
||||||
|
styles: dict[str, str] = {}
|
||||||
|
focus: dict[str, list[str]] = {}
|
||||||
|
for name, entry in styles_raw.items():
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
raise PromptLibraryError(
|
||||||
|
f"entry per stile {name!r} deve essere object, non {type(entry)}"
|
||||||
|
)
|
||||||
|
directive = entry.get("directive")
|
||||||
|
if not isinstance(directive, str):
|
||||||
|
raise PromptLibraryError(
|
||||||
|
f"manca 'directive' (string) per stile {name!r}"
|
||||||
|
)
|
||||||
|
styles[name] = directive
|
||||||
|
fm = entry.get("focus_metrics", [])
|
||||||
|
if not isinstance(fm, list):
|
||||||
|
raise PromptLibraryError(
|
||||||
|
f"focus_metrics di {name!r} deve essere lista, non {type(fm)}"
|
||||||
|
)
|
||||||
|
focus[name] = [str(x) for x in fm]
|
||||||
|
|
||||||
|
# Parse new optional top-level fields (v3.0)
|
||||||
|
agent_role = data.get("agent_role", "")
|
||||||
|
pattern_guidance = data.get("pattern_guidance", "")
|
||||||
|
instruction = data.get("instruction", "")
|
||||||
|
domain_warnings = data.get("domain_warnings", "")
|
||||||
|
# Parse new optional top-level fields (v3.1)
|
||||||
|
anti_patterns_raw = data.get("anti_patterns", "")
|
||||||
|
output_priorities_raw = data.get("output_priorities", "")
|
||||||
|
if not isinstance(anti_patterns_raw, str):
|
||||||
|
raise PromptLibraryError(f"anti_patterns deve essere stringa, non {type(anti_patterns_raw)}")
|
||||||
|
if not isinstance(output_priorities_raw, str):
|
||||||
|
raise PromptLibraryError(f"output_priorities deve essere stringa, non {type(output_priorities_raw)}")
|
||||||
|
|
||||||
|
return cls(
|
||||||
|
styles=styles,
|
||||||
|
focus=focus,
|
||||||
|
agent_role=agent_role,
|
||||||
|
pattern_guidance=pattern_guidance,
|
||||||
|
instruction=instruction,
|
||||||
|
domain_warnings=domain_warnings,
|
||||||
|
anti_patterns=anti_patterns_raw,
|
||||||
|
output_priorities=output_priorities_raw,
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cognitive_styles(self) -> tuple[str, ...]:
|
||||||
|
"""Tupla immutabile dei nomi degli stili, nell'ordine di insertion del JSON."""
|
||||||
|
return tuple(self.styles)
|
||||||
|
|
||||||
|
def directive(self, style: str) -> str:
|
||||||
|
"""Ritorna la directive di ``style`` o solleva KeyError."""
|
||||||
|
return self.styles[style]
|
||||||
|
|
||||||
|
def style_at(self, index: int) -> str:
|
||||||
|
"""Round-robin: ``cognitive_styles[index % len()]``."""
|
||||||
|
return self.cognitive_styles[index % len(self.cognitive_styles)]
|
||||||
|
|
||||||
|
def focus_metrics_for(self, style: str) -> list[str]:
|
||||||
|
"""Ritorna lista delle metriche prioritarie per ``style``. Empty list se non specificate."""
|
||||||
|
return self.focus.get(style, [])
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd # type: ignore[import-untyped]
|
||||||
|
|
||||||
|
|
||||||
|
def autocorr_lag1(returns: pd.Series) -> float:
|
||||||
|
"""Autocorrelazione dei ritorni con lag 1 (correlazione di Pearson)."""
|
||||||
|
if len(returns) < 2:
|
||||||
|
return 0.0
|
||||||
|
val = returns.autocorr(lag=1)
|
||||||
|
return float(val) if pd.notna(val) else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def hurst_exponent(returns: pd.Series) -> float:
|
||||||
|
"""Hurst exponent via R/S analysis (rescaled range).
|
||||||
|
|
||||||
|
Range 0-1: 0.5 random walk, >0.55 trending persistente, <0.45 mean reverting.
|
||||||
|
Implementazione classica con scale multiple (2^k bins).
|
||||||
|
"""
|
||||||
|
n = len(returns)
|
||||||
|
if n < 100:
|
||||||
|
return 0.5 # insufficiente dati, ritorna random-walk default
|
||||||
|
|
||||||
|
series = returns.dropna().values
|
||||||
|
n = len(series)
|
||||||
|
if n < 100:
|
||||||
|
return 0.5
|
||||||
|
|
||||||
|
# Scale: 2^k che dividono n in segmenti
|
||||||
|
scales = [2**k for k in range(4, int(np.log2(n // 2)) + 1)]
|
||||||
|
if not scales:
|
||||||
|
return 0.5
|
||||||
|
|
||||||
|
rs_values: list[float] = []
|
||||||
|
for scale in scales:
|
||||||
|
n_chunks = n // scale
|
||||||
|
if n_chunks < 1:
|
||||||
|
continue
|
||||||
|
rs_chunk: list[float] = []
|
||||||
|
for i in range(n_chunks):
|
||||||
|
chunk = series[i * scale : (i + 1) * scale]
|
||||||
|
mean = chunk.mean()
|
||||||
|
cumdev = (chunk - mean).cumsum()
|
||||||
|
r = cumdev.max() - cumdev.min()
|
||||||
|
s = chunk.std()
|
||||||
|
if s > 0:
|
||||||
|
rs_chunk.append(r / s)
|
||||||
|
if rs_chunk:
|
||||||
|
rs_values.append(float(np.mean(rs_chunk)))
|
||||||
|
|
||||||
|
if len(rs_values) < 2:
|
||||||
|
return 0.5
|
||||||
|
|
||||||
|
log_scales = np.log(scales[: len(rs_values)])
|
||||||
|
log_rs = np.log(rs_values)
|
||||||
|
# Hurst = slope della regressione log-log
|
||||||
|
h, _ = np.polyfit(log_scales, log_rs, 1)
|
||||||
|
return float(np.clip(h, 0.0, 1.0))
|
||||||
|
|
||||||
|
|
||||||
|
def vol_percentile_historical(
|
||||||
|
returns: pd.Series,
|
||||||
|
current_window: int = 24,
|
||||||
|
ref_window: int = 2000,
|
||||||
|
) -> float:
|
||||||
|
"""Percentile (0-100) della vol corrente nella distribuzione storica.
|
||||||
|
|
||||||
|
Vol = std rolling su current_window barre. Confronta l'ultimo valore contro
|
||||||
|
la distribuzione dei valori della stessa std rolling sugli ultimi ref_window.
|
||||||
|
Output: 0 (vol attuale tra le piu basse), 100 (tra le piu alte).
|
||||||
|
"""
|
||||||
|
if len(returns) < max(current_window, 100):
|
||||||
|
return 50.0
|
||||||
|
|
||||||
|
rolling_vol = returns.rolling(current_window, min_periods=current_window).std()
|
||||||
|
rolling_vol = rolling_vol.dropna()
|
||||||
|
if len(rolling_vol) < 10:
|
||||||
|
return 50.0
|
||||||
|
|
||||||
|
# Limita ref_window all'effettiva disponibilita
|
||||||
|
ref = rolling_vol.iloc[-ref_window:] if len(rolling_vol) > ref_window else rolling_vol
|
||||||
|
current = float(rolling_vol.iloc[-1])
|
||||||
|
pct = float((ref < current).sum()) / len(ref) * 100.0
|
||||||
|
return pct
|
||||||
|
|
||||||
|
|
||||||
|
def seasonality_strength(
|
||||||
|
returns: pd.Series,
|
||||||
|
by: str,
|
||||||
|
) -> float:
|
||||||
|
"""Frazione di varianza dei ritorni spiegata dalla feature temporale `by`.
|
||||||
|
|
||||||
|
`by` in {"hour", "dow"}. Output 0-1: 0 = no seasonality, 1 = tutta la varianza
|
||||||
|
e dovuta al ciclo. Calcolato come 1 - (var residua / var totale) usando i
|
||||||
|
gruppi indotti dalla feature.
|
||||||
|
"""
|
||||||
|
if not isinstance(returns.index, pd.DatetimeIndex):
|
||||||
|
return 0.0
|
||||||
|
if len(returns) < 50:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
if by == "hour":
|
||||||
|
groups = returns.index.hour
|
||||||
|
elif by == "dow":
|
||||||
|
groups = returns.index.dayofweek
|
||||||
|
else:
|
||||||
|
raise ValueError(f"by deve essere 'hour' o 'dow', non {by!r}")
|
||||||
|
|
||||||
|
total_var = float(returns.var())
|
||||||
|
if total_var <= 0:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
grouped = returns.groupby(groups)
|
||||||
|
group_means = grouped.transform("mean")
|
||||||
|
residuals = returns - group_means
|
||||||
|
residual_var = float(residuals.var())
|
||||||
|
|
||||||
|
explained = 1.0 - (residual_var / total_var)
|
||||||
|
return float(np.clip(explained, 0.0, 1.0))
|
||||||
|
|
||||||
|
|
||||||
|
def sharpe_ratio(returns: pd.Series, periods_per_year: int = 8760, rf: float = 0.0) -> float:
|
||||||
|
"""Sharpe annualizzato. periods_per_year=8760 per dati orari."""
|
||||||
|
excess = returns - rf / periods_per_year
|
||||||
|
std = excess.std(ddof=1)
|
||||||
|
if std == 0 or np.isnan(std):
|
||||||
|
return 0.0
|
||||||
|
return float(np.sqrt(periods_per_year) * excess.mean() / std)
|
||||||
|
|
||||||
|
|
||||||
|
def max_drawdown(equity: pd.Series) -> float:
|
||||||
|
"""Max drawdown percentuale (positivo)."""
|
||||||
|
peak = equity.cummax()
|
||||||
|
dd = (peak - equity) / peak.replace(0, np.nan)
|
||||||
|
dd = dd.fillna(0.0)
|
||||||
|
return float(dd.max())
|
||||||
|
|
||||||
|
|
||||||
|
def total_return(equity: pd.Series) -> float:
|
||||||
|
if equity.iloc[0] == 0:
|
||||||
|
return float(equity.iloc[-1])
|
||||||
|
return float(equity.iloc[-1] / equity.iloc[0] - 1.0)
|
||||||
|
|
||||||
|
|
||||||
|
def efficiency_ratio_kaufman(prices: pd.Series, length: int = 100) -> float:
|
||||||
|
"""Kaufman Efficiency Ratio: |net move| / sum(|step|) su rolling length.
|
||||||
|
|
||||||
|
Output 0-1: 0 = puro noise (movimento dissipativo), 1 = puro trend efficiente.
|
||||||
|
Discriminatore trending/ranging robusto.
|
||||||
|
"""
|
||||||
|
if len(prices) < length + 1:
|
||||||
|
return 0.0
|
||||||
|
recent = prices.iloc[-length:]
|
||||||
|
net_move = abs(recent.iloc[-1] - recent.iloc[0])
|
||||||
|
total_move = recent.diff().abs().sum()
|
||||||
|
if total_move == 0 or pd.isna(total_move):
|
||||||
|
return 0.0
|
||||||
|
return float(net_move / total_move)
|
||||||
|
|
||||||
|
|
||||||
|
def tail_index_hill(returns: pd.Series, side: str, top_frac: float = 0.05) -> float:
|
||||||
|
"""Hill estimator del tail index (pendenza coda) per side in {'left', 'right'}.
|
||||||
|
|
||||||
|
Output: indice di pesantezza coda. Valori piu bassi = coda piu pesante.
|
||||||
|
<2 = varianza infinita (Cauchy-like), 3-4 = tipico crypto, >5 = quasi-Gaussiana.
|
||||||
|
Robusto al singolo outlier (vs kurtosis).
|
||||||
|
"""
|
||||||
|
r = returns.dropna()
|
||||||
|
n = len(r)
|
||||||
|
if n < 50:
|
||||||
|
return 5.0 # default quasi-Gaussiano
|
||||||
|
k = max(int(n * top_frac), 5)
|
||||||
|
if side == "left":
|
||||||
|
tail = (-r).nlargest(k)
|
||||||
|
elif side == "right":
|
||||||
|
tail = r.nlargest(k)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"side deve essere 'left' o 'right', non {side!r}")
|
||||||
|
# Filtra valori non-positivi (Hill richiede tail positiva)
|
||||||
|
tail = tail[tail > 0]
|
||||||
|
if len(tail) < 5:
|
||||||
|
return 5.0
|
||||||
|
log_tail = np.log(tail.values)
|
||||||
|
threshold = log_tail[-1]
|
||||||
|
excess = log_tail[:-1] - threshold
|
||||||
|
if excess.sum() <= 0:
|
||||||
|
return 5.0
|
||||||
|
hill = (len(excess)) / excess.sum()
|
||||||
|
return float(np.clip(hill, 1.0, 10.0))
|
||||||
|
|
||||||
|
|
||||||
|
def structural_uptrend_score(prices: pd.Series, window: int = 5) -> float:
|
||||||
|
"""Frazione di periodi in struttura HH/HL (Dow-style uptrend).
|
||||||
|
|
||||||
|
Identifica swing high/low usando rolling max/min con finestra ``window``.
|
||||||
|
Conta sequenze higher-high + higher-low (uptrend) vs lower-high + lower-low (downtrend).
|
||||||
|
Output: 0 (puro downtrend) - 0.5 (range/mixed) - 1 (puro uptrend).
|
||||||
|
"""
|
||||||
|
if len(prices) < 4 * window:
|
||||||
|
return 0.5
|
||||||
|
swing_high = prices.rolling(2 * window + 1, center=True).max() == prices
|
||||||
|
swing_low = prices.rolling(2 * window + 1, center=True).min() == prices
|
||||||
|
|
||||||
|
highs = prices[swing_high].dropna()
|
||||||
|
lows = prices[swing_low].dropna()
|
||||||
|
|
||||||
|
if len(highs) < 3 or len(lows) < 3:
|
||||||
|
return 0.5
|
||||||
|
|
||||||
|
hh = (highs.diff() > 0).sum()
|
||||||
|
lh = (highs.diff() < 0).sum()
|
||||||
|
hl = (lows.diff() > 0).sum()
|
||||||
|
ll = (lows.diff() < 0).sum()
|
||||||
|
|
||||||
|
up_signals = hh + hl
|
||||||
|
down_signals = lh + ll
|
||||||
|
total = up_signals + down_signals
|
||||||
|
if total == 0:
|
||||||
|
return 0.5
|
||||||
|
return float(up_signals / total)
|
||||||
|
|
||||||
|
|
||||||
|
def compression_ratio(prices: pd.Series, recent_window: int = 50, ref_window: int = 200) -> float:
|
||||||
|
"""Range(recent) / Range(ref). <1 = compressione vol, >1 = espansione.
|
||||||
|
|
||||||
|
Range = high - low della finestra. Cattura il "coil" pre-breakout.
|
||||||
|
"""
|
||||||
|
if len(prices) < ref_window:
|
||||||
|
return 1.0
|
||||||
|
recent = prices.iloc[-recent_window:]
|
||||||
|
ref = prices.iloc[-ref_window:]
|
||||||
|
recent_range = float(recent.max() - recent.min())
|
||||||
|
ref_range = float(ref.max() - ref.min())
|
||||||
|
if ref_range <= 0:
|
||||||
|
return 1.0
|
||||||
|
return recent_range / ref_range
|
||||||
|
|
||||||
|
|
||||||
|
def spectral_entropy_and_cycle(
|
||||||
|
returns: pd.Series, length: int = 256
|
||||||
|
) -> tuple[float, float | None]:
|
||||||
|
"""FFT su returns -> (entropy normalizzata, dominant_cycle gated).
|
||||||
|
|
||||||
|
entropy: 0-1, Shannon entropy normalizzata dello spettro di potenza.
|
||||||
|
0 = una sola frequenza domina, 1 = spettro piatto (rumore bianco).
|
||||||
|
dominant_cycle: periodo (barre) della frequenza dominante,
|
||||||
|
MA solo se entropy < 0.6 (struttura presente). Altrimenti None.
|
||||||
|
"""
|
||||||
|
r = returns.dropna()
|
||||||
|
if len(r) < length:
|
||||||
|
return 1.0, None
|
||||||
|
series = r.iloc[-length:].values
|
||||||
|
# Detrend
|
||||||
|
series = series - series.mean()
|
||||||
|
fft = np.fft.rfft(series)
|
||||||
|
power = np.abs(fft) ** 2
|
||||||
|
if power.sum() <= 0:
|
||||||
|
return 1.0, None
|
||||||
|
p = power / power.sum()
|
||||||
|
# Entropy normalizzata (Shannon / log(N))
|
||||||
|
nonzero = p[p > 0]
|
||||||
|
entropy = float(-(nonzero * np.log(nonzero)).sum() / np.log(len(nonzero)))
|
||||||
|
entropy = max(0.0, min(1.0, entropy))
|
||||||
|
|
||||||
|
if entropy >= 0.6:
|
||||||
|
return entropy, None
|
||||||
|
# Skip DC component (index 0)
|
||||||
|
if len(power) <= 1:
|
||||||
|
return entropy, None
|
||||||
|
peak_idx = int(np.argmax(power[1:])) + 1
|
||||||
|
if peak_idx == 0:
|
||||||
|
return entropy, None
|
||||||
|
cycle = float(length / peak_idx)
|
||||||
|
return entropy, cycle
|
||||||
+63
-9
@@ -13,6 +13,7 @@ possa leggere lo stato a run terminato (o in corso).
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import random
|
import random
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -20,13 +21,15 @@ import pandas as pd # type: ignore[import-untyped]
|
|||||||
|
|
||||||
from ..agents.adversarial import AdversarialAgent
|
from ..agents.adversarial import AdversarialAgent
|
||||||
from ..agents.falsification import FalsificationAgent
|
from ..agents.falsification import FalsificationAgent
|
||||||
from ..agents.hypothesis import HypothesisAgent
|
from ..agents.hypothesis import HypothesisAgent, HypothesisProposal, MarketSummary
|
||||||
from ..agents.market_summary import build_market_summary
|
from ..agents.market_summary import build_market_summary
|
||||||
from ..ga.fitness import compute_fitness
|
from ..ga.fitness import compute_fitness
|
||||||
from ..ga.initial import build_initial_population
|
from ..ga.initial import build_initial_population
|
||||||
from ..ga.loop import GAConfig, next_generation
|
from ..ga.loop import GAConfig, next_generation
|
||||||
from ..ga.summary import generation_summary
|
from ..ga.summary import generation_summary
|
||||||
from ..genome.hypothesis import ModelTier
|
from ..genome.hypothesis import HypothesisAgentGenome, ModelTier
|
||||||
|
from ..genome.mutation import set_cognitive_styles
|
||||||
|
from ..genome.prompt_library import PromptLibrary
|
||||||
from ..llm.client import LLMClient
|
from ..llm.client import LLMClient
|
||||||
from ..llm.cost_tracker import CostTracker
|
from ..llm.cost_tracker import CostTracker
|
||||||
from ..persistence.repository import Repository
|
from ..persistence.repository import Repository
|
||||||
@@ -67,6 +70,33 @@ class RunConfig:
|
|||||||
# 2x costo backtest engine.
|
# 2x costo backtest engine.
|
||||||
eval_oos_during_loop: bool = False
|
eval_oos_during_loop: bool = False
|
||||||
fitness_combined_alpha: float = 0.5 # peso IS (1-alpha = OOS)
|
fitness_combined_alpha: float = 0.5 # peso IS (1-alpha = OOS)
|
||||||
|
# Libreria di stili cognitivi + system_prompt iniziali. Se None usa
|
||||||
|
# i 6 builtin (PromptLibrary.default()). Tipicamente caricata da
|
||||||
|
# strategy_crypto/prompts.json via PromptLibrary.from_json().
|
||||||
|
prompt_library: PromptLibrary | None = None
|
||||||
|
# Numero di propose() LLM concorrenti per generazione. 1 = sequenziale (default,
|
||||||
|
# backward compat). 6-10 tipicamente accettati da OpenRouter qwen-2.5 senza
|
||||||
|
# rate-limit. Riduce wall time GA loop di 5-8x su tier C.
|
||||||
|
llm_concurrency: int = 1
|
||||||
|
|
||||||
|
|
||||||
|
def _parallel_propose(
|
||||||
|
agent: HypothesisAgent,
|
||||||
|
genomes: list[HypothesisAgentGenome],
|
||||||
|
market: MarketSummary,
|
||||||
|
n_workers: int,
|
||||||
|
) -> list[HypothesisProposal]:
|
||||||
|
"""Esegue ``agent.propose()`` su una lista di genomi, opzionalmente in parallelo.
|
||||||
|
|
||||||
|
``n_workers <= 1`` mantiene il comportamento serial originale (ordine fisso,
|
||||||
|
determinismo data un seed). ``n_workers > 1`` usa un thread pool: l'order
|
||||||
|
dei risultati e' preservato (1:1 con ``genomes``). OpenAI/openrouter client
|
||||||
|
e' thread-safe; ``PromptLibrary`` e ``HypothesisAgent`` non hanno stato mutabile.
|
||||||
|
"""
|
||||||
|
if n_workers <= 1 or len(genomes) <= 1:
|
||||||
|
return [agent.propose(g, market) for g in genomes]
|
||||||
|
with ThreadPoolExecutor(max_workers=n_workers) as pool:
|
||||||
|
return list(pool.map(lambda g: agent.propose(g, market), genomes))
|
||||||
|
|
||||||
|
|
||||||
def run_phase1(
|
def run_phase1(
|
||||||
@@ -82,10 +112,16 @@ def run_phase1(
|
|||||||
|
|
||||||
repo = Repository(cfg.db_path)
|
repo = Repository(cfg.db_path)
|
||||||
repo.init_schema()
|
repo.init_schema()
|
||||||
|
# Escludi prompt_library (PromptLibrary dataclass non e' JSON-serializable);
|
||||||
|
# salva solo i nomi degli stili per reproducibility.
|
||||||
config_dict = {
|
config_dict = {
|
||||||
**cfg.__dict__,
|
**{k: v for k, v in cfg.__dict__.items() if k != "prompt_library"},
|
||||||
"db_path": str(cfg.db_path),
|
"db_path": str(cfg.db_path),
|
||||||
"model_tier": cfg.model_tier.value,
|
"model_tier": cfg.model_tier.value,
|
||||||
|
"prompt_library_styles": (
|
||||||
|
list(cfg.prompt_library.cognitive_styles)
|
||||||
|
if cfg.prompt_library is not None else None
|
||||||
|
),
|
||||||
}
|
}
|
||||||
run_id = repo.create_run(name=cfg.run_name, config=config_dict)
|
run_id = repo.create_run(name=cfg.run_name, config=config_dict)
|
||||||
|
|
||||||
@@ -100,7 +136,13 @@ def run_phase1(
|
|||||||
|
|
||||||
market = build_market_summary(train_ohlcv, symbol=cfg.symbol, timeframe=cfg.timeframe)
|
market = build_market_summary(train_ohlcv, symbol=cfg.symbol, timeframe=cfg.timeframe)
|
||||||
|
|
||||||
hypothesis_agent = HypothesisAgent(llm=llm)
|
# Propaga la libreria di stili al modulo mutation (cosi' mutate_cognitive_style
|
||||||
|
# pesca dai candidati coerenti col JSON della strategia in corso). Va FATTO
|
||||||
|
# PRIMA di istanziare HypothesisAgent (che la riceve in costruttore).
|
||||||
|
prompt_library = cfg.prompt_library or PromptLibrary.default()
|
||||||
|
set_cognitive_styles(prompt_library.cognitive_styles)
|
||||||
|
|
||||||
|
hypothesis_agent = HypothesisAgent(llm=llm, prompt_library=prompt_library)
|
||||||
falsification_agent = FalsificationAgent(
|
falsification_agent = FalsificationAgent(
|
||||||
fees_bp=cfg.fees_bp, n_trials_dsr=cfg.n_trials_dsr
|
fees_bp=cfg.fees_bp, n_trials_dsr=cfg.n_trials_dsr
|
||||||
)
|
)
|
||||||
@@ -113,7 +155,10 @@ def run_phase1(
|
|||||||
cost_tracker = CostTracker()
|
cost_tracker = CostTracker()
|
||||||
|
|
||||||
population = build_initial_population(
|
population = build_initial_population(
|
||||||
k=cfg.population_size, model_tier=cfg.model_tier, rng=rng
|
k=cfg.population_size,
|
||||||
|
model_tier=cfg.model_tier,
|
||||||
|
rng=rng,
|
||||||
|
prompt_library=prompt_library,
|
||||||
)
|
)
|
||||||
fitnesses: dict[str, float] = {}
|
fitnesses: dict[str, float] = {}
|
||||||
|
|
||||||
@@ -127,11 +172,20 @@ def run_phase1(
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
for gen in range(cfg.n_generations):
|
for gen in range(cfg.n_generations):
|
||||||
|
# Step 1: raccogli i genomi da valutare in questa generazione (esclude
|
||||||
|
# elite gia' presenti nella cache fitnesses) e lancia propose() in
|
||||||
|
# parallelo. La sezione DB-write resta serial sotto.
|
||||||
|
uncached = [g for g in population if g.id not in fitnesses]
|
||||||
|
proposals = _parallel_propose(
|
||||||
|
hypothesis_agent, uncached, market, cfg.llm_concurrency
|
||||||
|
)
|
||||||
|
proposal_by_id = {g.id: p for g, p in zip(uncached, proposals, strict=True)}
|
||||||
|
|
||||||
for genome in population:
|
for genome in population:
|
||||||
if genome.id in fitnesses:
|
if genome.id in fitnesses:
|
||||||
continue # elite gia' valutata in generazione precedente
|
continue # elite gia' valutata in generazione precedente
|
||||||
repo.save_genome(run_id=run_id, generation_idx=gen, genome=genome)
|
repo.save_genome(run_id=run_id, generation_idx=gen, genome=genome)
|
||||||
proposal = hypothesis_agent.propose(genome, market)
|
proposal = proposal_by_id[genome.id]
|
||||||
# Registra costo per OGNI completion (incluse retry).
|
# Registra costo per OGNI completion (incluse retry).
|
||||||
for completion in proposal.completions:
|
for completion in proposal.completions:
|
||||||
cost_record = cost_tracker.record(
|
cost_record = cost_tracker.record(
|
||||||
@@ -205,7 +259,7 @@ def run_phase1(
|
|||||||
cfg.fitness_combined_alpha * fit
|
cfg.fitness_combined_alpha * fit
|
||||||
+ (1.0 - cfg.fitness_combined_alpha) * fit_oos_inloop
|
+ (1.0 - cfg.fitness_combined_alpha) * fit_oos_inloop
|
||||||
)
|
)
|
||||||
except Exception: # noqa: BLE001
|
except Exception:
|
||||||
pass # fallback: usa solo IS
|
pass # fallback: usa solo IS
|
||||||
repo.save_evaluation(
|
repo.save_evaluation(
|
||||||
run_id=run_id,
|
run_id=run_id,
|
||||||
@@ -246,7 +300,7 @@ def run_phase1(
|
|||||||
# WFA re-eval: i top_k genomi (by fitness in-sample > 0) vengono rivalutati
|
# WFA re-eval: i top_k genomi (by fitness in-sample > 0) vengono rivalutati
|
||||||
# sul test_ohlcv. Le metriche OOS finiscono in evaluations.fitness_oos etc.
|
# sul test_ohlcv. Le metriche OOS finiscono in evaluations.fitness_oos etc.
|
||||||
if test_ohlcv is not None and len(test_ohlcv) >= 100:
|
if test_ohlcv is not None and len(test_ohlcv) >= 100:
|
||||||
from ..agents.hypothesis import _try_parse # noqa: PLC0415
|
from ..agents.hypothesis import _try_parse
|
||||||
|
|
||||||
all_evals = repo.list_evaluations(run_id)
|
all_evals = repo.list_evaluations(run_id)
|
||||||
top_evals = sorted(
|
top_evals = sorted(
|
||||||
@@ -261,7 +315,7 @@ def run_phase1(
|
|||||||
try:
|
try:
|
||||||
fals_oos = falsification_agent.evaluate(strategy, test_ohlcv)
|
fals_oos = falsification_agent.evaluate(strategy, test_ohlcv)
|
||||||
adv_oos = adversarial_agent.review(strategy, test_ohlcv)
|
adv_oos = adversarial_agent.review(strategy, test_ohlcv)
|
||||||
except Exception: # noqa: BLE001
|
except Exception:
|
||||||
continue
|
continue
|
||||||
fit_oos = compute_fitness(
|
fit_oos = compute_fitness(
|
||||||
fals_oos, adv_oos,
|
fals_oos, adv_oos,
|
||||||
-61
@@ -77,68 +77,7 @@ CREATE TABLE IF NOT EXISTS adversarial_findings (
|
|||||||
FOREIGN KEY (run_id) REFERENCES runs(id)
|
FOREIGN KEY (run_id) REFERENCES runs(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS paper_trading_runs (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
started_at TEXT NOT NULL,
|
|
||||||
stopped_at TEXT,
|
|
||||||
status TEXT NOT NULL DEFAULT 'running',
|
|
||||||
initial_capital REAL NOT NULL,
|
|
||||||
config_json TEXT NOT NULL
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS paper_trading_positions (
|
|
||||||
paper_run_id TEXT NOT NULL,
|
|
||||||
symbol TEXT NOT NULL,
|
|
||||||
side TEXT NOT NULL,
|
|
||||||
qty REAL NOT NULL,
|
|
||||||
entry_price REAL NOT NULL,
|
|
||||||
entry_ts TEXT NOT NULL,
|
|
||||||
PRIMARY KEY (paper_run_id, symbol),
|
|
||||||
FOREIGN KEY (paper_run_id) REFERENCES paper_trading_runs(id)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS paper_trading_trades (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
paper_run_id TEXT NOT NULL,
|
|
||||||
symbol TEXT NOT NULL,
|
|
||||||
side TEXT NOT NULL,
|
|
||||||
qty REAL NOT NULL,
|
|
||||||
entry_price REAL NOT NULL,
|
|
||||||
exit_price REAL NOT NULL,
|
|
||||||
entry_ts TEXT NOT NULL,
|
|
||||||
exit_ts TEXT NOT NULL,
|
|
||||||
pnl REAL NOT NULL,
|
|
||||||
fees REAL NOT NULL,
|
|
||||||
FOREIGN KEY (paper_run_id) REFERENCES paper_trading_runs(id)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS paper_trading_equity (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
paper_run_id TEXT NOT NULL,
|
|
||||||
ts TEXT NOT NULL,
|
|
||||||
equity REAL NOT NULL,
|
|
||||||
cash REAL NOT NULL,
|
|
||||||
positions_value REAL NOT NULL,
|
|
||||||
FOREIGN KEY (paper_run_id) REFERENCES paper_trading_runs(id)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS paper_trading_ticks (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
paper_run_id TEXT NOT NULL,
|
|
||||||
symbol TEXT NOT NULL,
|
|
||||||
ts TEXT NOT NULL,
|
|
||||||
bar_ts TEXT NOT NULL,
|
|
||||||
close_price REAL NOT NULL,
|
|
||||||
signal TEXT NOT NULL,
|
|
||||||
action_taken TEXT NOT NULL,
|
|
||||||
FOREIGN KEY (paper_run_id) REFERENCES paper_trading_runs(id)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_evaluations_fitness ON evaluations(run_id, fitness DESC);
|
CREATE INDEX IF NOT EXISTS idx_evaluations_fitness ON evaluations(run_id, fitness DESC);
|
||||||
CREATE INDEX IF NOT EXISTS idx_genomes_generation ON genomes(run_id, generation_idx);
|
CREATE INDEX IF NOT EXISTS idx_genomes_generation ON genomes(run_id, generation_idx);
|
||||||
CREATE INDEX IF NOT EXISTS idx_cost_run ON cost_records(run_id);
|
CREATE INDEX IF NOT EXISTS idx_cost_run ON cost_records(run_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_paper_trades_run ON paper_trading_trades(paper_run_id, exit_ts);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_paper_equity_run ON paper_trading_equity(paper_run_id, ts);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_paper_ticks_run ON paper_trading_ticks(paper_run_id, ts);
|
|
||||||
"""
|
"""
|
||||||
+34
@@ -80,6 +80,37 @@ def _ind_atr(df: pd.DataFrame, length: float) -> pd.Series:
|
|||||||
return _atr(df, int(length))
|
return _atr(df, int(length))
|
||||||
|
|
||||||
|
|
||||||
|
def _ind_atr_pct(df: pd.DataFrame, length: float) -> pd.Series:
|
||||||
|
# ATR normalizzato come frazione del prezzo close.
|
||||||
|
# Convenzione: confronti con literal numerici tipo `atr_pct > 0.02` significano
|
||||||
|
# "ATR > 2% del prezzo". Risolve il bug protocol_unit_bug dove `atr > 0.02`
|
||||||
|
# su asset crypto (close ~3000 USDT, atr ~30) e' sempre TRUE -> dead branch.
|
||||||
|
return _atr(df, int(length)) / df["close"]
|
||||||
|
|
||||||
|
|
||||||
|
def _ind_sma_pct(df: pd.DataFrame, length: float) -> pd.Series:
|
||||||
|
# Deviazione frazionale del close dalla SMA: (close - sma) / sma.
|
||||||
|
# Range tipico +/- 0.1 (close +/- 10% dalla media). Uso ideale:
|
||||||
|
# sma_pct(50) > 0.05 -> "close 5% sopra la media a 50 barre"
|
||||||
|
# NB: non e' "sma/close" perche' quel valore (sempre ~1.0) e' inutile
|
||||||
|
# per confronti con literal frazionali.
|
||||||
|
sma = _sma(df["close"], int(length))
|
||||||
|
return (df["close"] - sma) / sma
|
||||||
|
|
||||||
|
|
||||||
|
def _ind_macd_pct(
|
||||||
|
df: pd.DataFrame,
|
||||||
|
fast: float = 12,
|
||||||
|
slow: float = 26,
|
||||||
|
signal: float = 9,
|
||||||
|
) -> pd.Series:
|
||||||
|
# MACD normalizzato come frazione del prezzo close: macd_value / close.
|
||||||
|
# Range tipico +/- 0.02. Uso: `macd_pct > 0` (momentum positivo) o
|
||||||
|
# `macd_pct > 0.005` (momentum positivo >= 0.5% del prezzo).
|
||||||
|
macd = _ind_macd(df, fast, slow, signal)
|
||||||
|
return macd / df["close"]
|
||||||
|
|
||||||
|
|
||||||
def _ind_realized_vol(df: pd.DataFrame, window: float) -> pd.Series:
|
def _ind_realized_vol(df: pd.DataFrame, window: float) -> pd.Series:
|
||||||
return _realized_vol(df["close"], int(window))
|
return _realized_vol(df["close"], int(window))
|
||||||
|
|
||||||
@@ -101,10 +132,13 @@ def _ind_macd(
|
|||||||
# against this map.
|
# against this map.
|
||||||
INDICATOR_FNS: dict[str, Any] = {
|
INDICATOR_FNS: dict[str, Any] = {
|
||||||
"sma": _ind_sma,
|
"sma": _ind_sma,
|
||||||
|
"sma_pct": _ind_sma_pct,
|
||||||
"rsi": _ind_rsi,
|
"rsi": _ind_rsi,
|
||||||
"atr": _ind_atr,
|
"atr": _ind_atr,
|
||||||
|
"atr_pct": _ind_atr_pct,
|
||||||
"realized_vol": _ind_realized_vol,
|
"realized_vol": _ind_realized_vol,
|
||||||
"macd": _ind_macd,
|
"macd": _ind_macd,
|
||||||
|
"macd_pct": _ind_macd_pct,
|
||||||
}
|
}
|
||||||
|
|
||||||
_TIME_FEATURE_FNS: dict[str, Callable[[pd.DatetimeIndex], pd.Series]] = {
|
_TIME_FEATURE_FNS: dict[str, Callable[[pd.DatetimeIndex], pd.Series]] = {
|
||||||
+1
-1
@@ -17,7 +17,7 @@ ACTION_VALUES: frozenset[str] = frozenset(
|
|||||||
KIND_VALUES: frozenset[str] = frozenset({"indicator", "feature", "literal"})
|
KIND_VALUES: frozenset[str] = frozenset({"indicator", "feature", "literal"})
|
||||||
|
|
||||||
KNOWN_INDICATORS: frozenset[str] = frozenset(
|
KNOWN_INDICATORS: frozenset[str] = frozenset(
|
||||||
{"sma", "rsi", "atr", "macd", "realized_vol"}
|
{"sma", "sma_pct", "rsi", "atr", "atr_pct", "macd", "macd_pct", "realized_vol"}
|
||||||
)
|
)
|
||||||
KNOWN_FEATURES: frozenset[str] = frozenset(
|
KNOWN_FEATURES: frozenset[str] = frozenset(
|
||||||
{"open", "high", "low", "close", "volume",
|
{"open", "high", "low", "close", "volume",
|
||||||
+5
-2
@@ -31,11 +31,14 @@ from .parser import (
|
|||||||
# Numero di parametri numerici accettati dopo il nome dell'indicatore.
|
# Numero di parametri numerici accettati dopo il nome dell'indicatore.
|
||||||
# (min, max) sui soli numeri. Indicatori non sono annidabili in Phase 1.
|
# (min, max) sui soli numeri. Indicatori non sono annidabili in Phase 1.
|
||||||
INDICATOR_ARITY: dict[str, tuple[int, int]] = {
|
INDICATOR_ARITY: dict[str, tuple[int, int]] = {
|
||||||
"sma": (1, 1), # length
|
"sma": (1, 1), # length (assoluto, unita' prezzo)
|
||||||
|
"sma_pct": (1, 1), # length: (close - sma)/sma, deviazione frazionale
|
||||||
"rsi": (1, 1), # length
|
"rsi": (1, 1), # length
|
||||||
"atr": (1, 1), # length
|
"atr": (1, 1), # length (assoluto, unita' prezzo)
|
||||||
|
"atr_pct": (1, 1), # length (frazione del close, per confronti con literal)
|
||||||
"realized_vol": (1, 1), # window
|
"realized_vol": (1, 1), # window
|
||||||
"macd": (0, 3), # fast, slow, signal (tutti opzionali)
|
"macd": (0, 3), # fast, slow, signal (tutti opzionali)
|
||||||
|
"macd_pct": (0, 3), # macd/close, frazionale (per confronti con literal)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
[project]
|
||||||
|
name = "multi-swarm-core"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Multi-Swarm Coevolutive core: GA, genome, protocol, backtest, cerbero, data, llm, persistence"
|
||||||
|
authors = [{ name = "Adriano Dal Pastro", email = "adrianodalpastro@tielogic.com" }]
|
||||||
|
requires-python = ">=3.13"
|
||||||
|
dependencies = [
|
||||||
|
"pandas>=2.2",
|
||||||
|
"numpy>=2.1",
|
||||||
|
"scipy>=1.14",
|
||||||
|
"pydantic>=2.9",
|
||||||
|
"pydantic-settings>=2.6",
|
||||||
|
"sqlmodel>=0.0.22",
|
||||||
|
"openai>=1.55",
|
||||||
|
"httpx>=0.28",
|
||||||
|
"requests>=2.32",
|
||||||
|
"tenacity>=9.0",
|
||||||
|
"pyyaml>=6.0",
|
||||||
|
"pyarrow>=18.0",
|
||||||
|
"yfinance>=1.3.0",
|
||||||
|
"nicegui>=3.11.1",
|
||||||
|
"plotly>=5.24",
|
||||||
|
]
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["hatchling"]
|
||||||
|
build-backend = "hatchling.build"
|
||||||
+12
-5
@@ -5,10 +5,10 @@ import numpy as np
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from multi_swarm.genome.hypothesis import ModelTier
|
from multi_swarm_core.genome.hypothesis import ModelTier
|
||||||
from multi_swarm.llm.client import CompletionResult
|
from multi_swarm_core.llm.client import CompletionResult
|
||||||
from multi_swarm.orchestrator.run import RunConfig, run_phase1
|
from multi_swarm_core.orchestrator.run import RunConfig, run_phase1
|
||||||
from multi_swarm.persistence.repository import Repository
|
from multi_swarm_core.persistence.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -108,7 +108,13 @@ def test_e2e_wfa_populates_fitness_oos(
|
|||||||
fake_llm,
|
fake_llm,
|
||||||
mocker,
|
mocker,
|
||||||
):
|
):
|
||||||
"""WFA: train_split=0.7 → top genomi devono avere fitness_oos popolato."""
|
"""WFA: train_split=0.7 → top genomi devono avere fitness_oos popolato.
|
||||||
|
|
||||||
|
Usa fitness v2 con hard-kill minimale (solo no_trades): il fixture sintetico
|
||||||
|
non produce strategie profittevoli, quindi i check aggressivi
|
||||||
|
fees_eat_alpha/negative_net_pnl azzererebbero tutti i genomi rendendo
|
||||||
|
inverificabile il wiring WFA.
|
||||||
|
"""
|
||||||
cfg = RunConfig(
|
cfg = RunConfig(
|
||||||
run_name="e2e-wfa-test",
|
run_name="e2e-wfa-test",
|
||||||
population_size=5,
|
population_size=5,
|
||||||
@@ -125,6 +131,7 @@ def test_e2e_wfa_populates_fitness_oos(
|
|||||||
db_path=tmp_path / "runs.db",
|
db_path=tmp_path / "runs.db",
|
||||||
wfa_train_split=0.7,
|
wfa_train_split=0.7,
|
||||||
wfa_top_k=3,
|
wfa_top_k=3,
|
||||||
|
fitness_hard_kill_findings=("no_trades",),
|
||||||
)
|
)
|
||||||
run_id = run_phase1(cfg, ohlcv=synthetic_ohlcv, llm=fake_llm)
|
run_id = run_phase1(cfg, ohlcv=synthetic_ohlcv, llm=fake_llm)
|
||||||
repo = Repository(db_path=tmp_path / "runs.db")
|
repo = Repository(db_path=tmp_path / "runs.db")
|
||||||
+2
-2
@@ -9,8 +9,8 @@ from __future__ import annotations
|
|||||||
import random
|
import random
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
from multi_swarm.ga.loop import GAConfig, next_generation
|
from multi_swarm_core.ga.loop import GAConfig, next_generation
|
||||||
from multi_swarm.genome.hypothesis import HypothesisAgentGenome, ModelTier
|
from multi_swarm_core.genome.hypothesis import HypothesisAgentGenome, ModelTier
|
||||||
|
|
||||||
_PROMPT_TEMPLATES = (
|
_PROMPT_TEMPLATES = (
|
||||||
"Strategia mean-reversion 1h. Entry long RSI(14) < 30 e close > SMA(50). Stop 2%.",
|
"Strategia mean-reversion 1h. Entry long RSI(14) < 30 e close > SMA(50). Stop 2%.",
|
||||||
+123
-21
@@ -3,15 +3,14 @@ import json
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
from multi_swarm_core.agents.adversarial import (
|
||||||
from multi_swarm.agents.adversarial import (
|
|
||||||
AdversarialAgent,
|
AdversarialAgent,
|
||||||
AdversarialReport,
|
AdversarialReport,
|
||||||
Severity,
|
Severity,
|
||||||
)
|
)
|
||||||
from multi_swarm.backtest.engine import BacktestResult
|
from multi_swarm_core.backtest.engine import BacktestResult
|
||||||
from multi_swarm.backtest.orders import Side, Trade
|
from multi_swarm_core.backtest.orders import Side, Trade
|
||||||
from multi_swarm.protocol.parser import parse_strategy
|
from multi_swarm_core.protocol.parser import parse_strategy
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -54,7 +53,10 @@ def test_degenerate_always_long_flagged(ohlcv: pd.DataFrame) -> None:
|
|||||||
assert any(f.name == "degenerate" and f.severity == Severity.HIGH for f in report.findings)
|
assert any(f.name == "degenerate" and f.severity == Severity.HIGH for f in report.findings)
|
||||||
|
|
||||||
|
|
||||||
def test_no_findings_on_reasonable_strategy(ohlcv: pd.DataFrame) -> None:
|
def test_rsi_mean_reversion_loses_money_on_synthetic_data(ohlcv: pd.DataFrame) -> None:
|
||||||
|
"""RSI mean-reversion sul fixture sintetico ha net negativo: deve firare
|
||||||
|
negative_net_pnl (deal-breaker). Conferma che il check cattura strategie
|
||||||
|
che perdono sul training, indipendentemente dal motivo (no edge / fees)."""
|
||||||
src = json.dumps(
|
src = json.dumps(
|
||||||
{
|
{
|
||||||
"rules": [
|
"rules": [
|
||||||
@@ -84,8 +86,59 @@ def test_no_findings_on_reasonable_strategy(ohlcv: pd.DataFrame) -> None:
|
|||||||
ast = parse_strategy(src)
|
ast = parse_strategy(src)
|
||||||
agent = AdversarialAgent()
|
agent = AdversarialAgent()
|
||||||
report = agent.review(ast, ohlcv)
|
report = agent.review(ast, ohlcv)
|
||||||
|
assert any(
|
||||||
|
f.name == "negative_net_pnl" and f.severity == Severity.HIGH
|
||||||
|
for f in report.findings
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_profitable_strategy_no_high_findings(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, ohlcv: pd.DataFrame
|
||||||
|
) -> None:
|
||||||
|
"""Sanity test: una strategia con gross > 0 e fees << gross + n_trades ragionevole
|
||||||
|
+ signal misto non deve produrre nessun finding HIGH."""
|
||||||
|
n = 15
|
||||||
|
# entry=100 exit=110 gross=10 per trade, fees a 5bp -> 0.105 per trade
|
||||||
|
# totali: gross=150, fees=1.575 -> net=+148.4
|
||||||
|
fake_trades = [
|
||||||
|
_make_trade(
|
||||||
|
ohlcv.index[i * 30],
|
||||||
|
ohlcv.index[i * 30 + 1],
|
||||||
|
entry_price=100.0,
|
||||||
|
exit_price=110.0,
|
||||||
|
)
|
||||||
|
for i in range(n)
|
||||||
|
]
|
||||||
|
# 50/50 LONG/FLAT per evitare degenerate/flat_too_long/time_in_market.
|
||||||
|
fake_signals = pd.Series(
|
||||||
|
[Side.LONG if i % 2 == 0 else Side.FLAT for i in range(len(ohlcv))],
|
||||||
|
index=ohlcv.index,
|
||||||
|
dtype=object,
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_run(self, ohlcv: pd.DataFrame, signals: pd.Series) -> BacktestResult: # type: ignore[no-untyped-def]
|
||||||
|
return BacktestResult(
|
||||||
|
equity_curve=pd.Series([0.0] * len(ohlcv), index=ohlcv.index, name="equity"),
|
||||||
|
returns=pd.Series([0.0] * len(ohlcv), index=ohlcv.index, name="returns"),
|
||||||
|
trades=fake_trades,
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_compile(strategy): # type: ignore[no-untyped-def]
|
||||||
|
return lambda df: fake_signals
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"multi_swarm_core.agents.adversarial.BacktestEngine.run", fake_run
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"multi_swarm_core.agents.adversarial.compile_strategy", fake_compile
|
||||||
|
)
|
||||||
|
|
||||||
|
ast = parse_strategy(_MINIMAL_STRATEGY_SRC)
|
||||||
|
report = AdversarialAgent().review(ast, ohlcv)
|
||||||
high_findings = [f for f in report.findings if f.severity == Severity.HIGH]
|
high_findings = [f for f in report.findings if f.severity == Severity.HIGH]
|
||||||
assert len(high_findings) == 0
|
assert high_findings == [], (
|
||||||
|
f"expected no HIGH findings, got: {[f.name for f in high_findings]}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_zero_trade_strategy_flagged(ohlcv: pd.DataFrame) -> None:
|
def test_zero_trade_strategy_flagged(ohlcv: pd.DataFrame) -> None:
|
||||||
@@ -178,10 +231,10 @@ def test_undertrading_under_10_is_high(monkeypatch: pytest.MonkeyPatch,
|
|||||||
return lambda df: fake_signals
|
return lambda df: fake_signals
|
||||||
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.BacktestEngine.run", fake_run
|
"multi_swarm_core.agents.adversarial.BacktestEngine.run", fake_run
|
||||||
)
|
)
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.compile_strategy", fake_compile
|
"multi_swarm_core.agents.adversarial.compile_strategy", fake_compile
|
||||||
)
|
)
|
||||||
|
|
||||||
src = _MINIMAL_STRATEGY_SRC
|
src = _MINIMAL_STRATEGY_SRC
|
||||||
@@ -220,8 +273,8 @@ def test_undertrading_threshold_parametric(monkeypatch: pytest.MonkeyPatch,
|
|||||||
def fake_compile(strategy): # type: ignore[no-untyped-def]
|
def fake_compile(strategy): # type: ignore[no-untyped-def]
|
||||||
return lambda df: fake_signals
|
return lambda df: fake_signals
|
||||||
|
|
||||||
monkeypatch.setattr("multi_swarm.agents.adversarial.BacktestEngine.run", fake_run)
|
monkeypatch.setattr("multi_swarm_core.agents.adversarial.BacktestEngine.run", fake_run)
|
||||||
monkeypatch.setattr("multi_swarm.agents.adversarial.compile_strategy", fake_compile)
|
monkeypatch.setattr("multi_swarm_core.agents.adversarial.compile_strategy", fake_compile)
|
||||||
|
|
||||||
ast = parse_strategy(_MINIMAL_STRATEGY_SRC)
|
ast = parse_strategy(_MINIMAL_STRATEGY_SRC)
|
||||||
# Default threshold 10: 15 trade NON killato
|
# Default threshold 10: 15 trade NON killato
|
||||||
@@ -269,10 +322,10 @@ def test_overtrading_with_tighter_threshold(monkeypatch: pytest.MonkeyPatch,
|
|||||||
return lambda df: fake_signals
|
return lambda df: fake_signals
|
||||||
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.BacktestEngine.run", fake_run
|
"multi_swarm_core.agents.adversarial.BacktestEngine.run", fake_run
|
||||||
)
|
)
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.compile_strategy", fake_compile
|
"multi_swarm_core.agents.adversarial.compile_strategy", fake_compile
|
||||||
)
|
)
|
||||||
|
|
||||||
src = _MINIMAL_STRATEGY_SRC
|
src = _MINIMAL_STRATEGY_SRC
|
||||||
@@ -315,10 +368,10 @@ def test_flat_too_long_flagged(monkeypatch: pytest.MonkeyPatch,
|
|||||||
return lambda df: fake_signals
|
return lambda df: fake_signals
|
||||||
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.BacktestEngine.run", fake_run
|
"multi_swarm_core.agents.adversarial.BacktestEngine.run", fake_run
|
||||||
)
|
)
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.compile_strategy", fake_compile
|
"multi_swarm_core.agents.adversarial.compile_strategy", fake_compile
|
||||||
)
|
)
|
||||||
|
|
||||||
src = _MINIMAL_STRATEGY_SRC
|
src = _MINIMAL_STRATEGY_SRC
|
||||||
@@ -367,10 +420,10 @@ def test_fees_eat_alpha_flagged(monkeypatch: pytest.MonkeyPatch,
|
|||||||
return lambda df: fake_signals
|
return lambda df: fake_signals
|
||||||
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.BacktestEngine.run", fake_run
|
"multi_swarm_core.agents.adversarial.BacktestEngine.run", fake_run
|
||||||
)
|
)
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.compile_strategy", fake_compile
|
"multi_swarm_core.agents.adversarial.compile_strategy", fake_compile
|
||||||
)
|
)
|
||||||
|
|
||||||
src = _MINIMAL_STRATEGY_SRC
|
src = _MINIMAL_STRATEGY_SRC
|
||||||
@@ -383,6 +436,55 @@ def test_fees_eat_alpha_flagged(monkeypatch: pytest.MonkeyPatch,
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_negative_net_pnl_fires_on_negative_gross(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, ohlcv: pd.DataFrame
|
||||||
|
) -> None:
|
||||||
|
"""gross_pnl < 0 (perdente direzionale) -> HIGH negative_net_pnl.
|
||||||
|
fees_eat_alpha NON deve firare perche' la sua condizione richiede gross > 0.
|
||||||
|
"""
|
||||||
|
n = 15
|
||||||
|
# entry=100 exit=95 gross=-5 per trade (LONG perdente)
|
||||||
|
fake_trades = [
|
||||||
|
_make_trade(
|
||||||
|
ohlcv.index[i * 30],
|
||||||
|
ohlcv.index[i * 30 + 1],
|
||||||
|
entry_price=100.0,
|
||||||
|
exit_price=95.0,
|
||||||
|
)
|
||||||
|
for i in range(n)
|
||||||
|
]
|
||||||
|
fake_signals = pd.Series(
|
||||||
|
[Side.LONG if i % 2 == 0 else Side.FLAT for i in range(len(ohlcv))],
|
||||||
|
index=ohlcv.index,
|
||||||
|
dtype=object,
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_run(self, ohlcv, signals): # type: ignore[no-untyped-def]
|
||||||
|
return BacktestResult(
|
||||||
|
equity_curve=pd.Series([0.0] * len(ohlcv), index=ohlcv.index, name="equity"),
|
||||||
|
returns=pd.Series([0.0] * len(ohlcv), index=ohlcv.index, name="returns"),
|
||||||
|
trades=fake_trades,
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_compile(strategy): # type: ignore[no-untyped-def]
|
||||||
|
return lambda df: fake_signals
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"multi_swarm_core.agents.adversarial.BacktestEngine.run", fake_run
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"multi_swarm_core.agents.adversarial.compile_strategy", fake_compile
|
||||||
|
)
|
||||||
|
|
||||||
|
ast = parse_strategy(_MINIMAL_STRATEGY_SRC)
|
||||||
|
report = AdversarialAgent().review(ast, ohlcv)
|
||||||
|
assert any(
|
||||||
|
f.name == "negative_net_pnl" and f.severity == Severity.HIGH
|
||||||
|
for f in report.findings
|
||||||
|
)
|
||||||
|
assert not any(f.name == "fees_eat_alpha" for f in report.findings)
|
||||||
|
|
||||||
|
|
||||||
def test_time_in_market_too_high_flagged(monkeypatch: pytest.MonkeyPatch,
|
def test_time_in_market_too_high_flagged(monkeypatch: pytest.MonkeyPatch,
|
||||||
ohlcv: pd.DataFrame) -> None:
|
ohlcv: pd.DataFrame) -> None:
|
||||||
"""Signal LONG per >80% delle bar -> HIGH time_in_market_too_high."""
|
"""Signal LONG per >80% delle bar -> HIGH time_in_market_too_high."""
|
||||||
@@ -413,10 +515,10 @@ def test_time_in_market_too_high_flagged(monkeypatch: pytest.MonkeyPatch,
|
|||||||
return lambda df: fake_signals
|
return lambda df: fake_signals
|
||||||
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.BacktestEngine.run", fake_run
|
"multi_swarm_core.agents.adversarial.BacktestEngine.run", fake_run
|
||||||
)
|
)
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.compile_strategy", fake_compile
|
"multi_swarm_core.agents.adversarial.compile_strategy", fake_compile
|
||||||
)
|
)
|
||||||
|
|
||||||
src = _MINIMAL_STRATEGY_SRC
|
src = _MINIMAL_STRATEGY_SRC
|
||||||
@@ -461,10 +563,10 @@ def test_reasonable_balanced_strategy_not_flagged(monkeypatch: pytest.MonkeyPatc
|
|||||||
return lambda df: fake_signals
|
return lambda df: fake_signals
|
||||||
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.BacktestEngine.run", fake_run
|
"multi_swarm_core.agents.adversarial.BacktestEngine.run", fake_run
|
||||||
)
|
)
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"multi_swarm.agents.adversarial.compile_strategy", fake_compile
|
"multi_swarm_core.agents.adversarial.compile_strategy", fake_compile
|
||||||
)
|
)
|
||||||
|
|
||||||
src = _MINIMAL_STRATEGY_SRC
|
src = _MINIMAL_STRATEGY_SRC
|
||||||
+2
-2
@@ -2,8 +2,8 @@ import numpy as np
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from multi_swarm.backtest.engine import BacktestEngine
|
from multi_swarm_core.backtest.engine import BacktestEngine
|
||||||
from multi_swarm.backtest.orders import Side
|
from multi_swarm_core.backtest.orders import Side
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
"""Parity check: engine vettorializzato vs reference iterrows implementation.
|
||||||
|
|
||||||
|
Mantiene una copia inline del loop ``iterrows`` come reference per garantire
|
||||||
|
che la vettorizzazione produca esattamente gli stessi trades, equity_curve e
|
||||||
|
returns su input pseudocasuali, indipendentemente dal regime di prezzo.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
import pytest
|
||||||
|
from multi_swarm_core.backtest.engine import BacktestEngine, BacktestResult
|
||||||
|
from multi_swarm_core.backtest.orders import Position, Side, Trade
|
||||||
|
|
||||||
|
|
||||||
|
def _legacy_run(
|
||||||
|
ohlcv: pd.DataFrame, signals: pd.Series, fees_bp: float = 5.0
|
||||||
|
) -> BacktestResult:
|
||||||
|
"""Reference implementation: il loop iterrows originale (pre-vectorize).
|
||||||
|
|
||||||
|
Mantenuto qui esclusivamente come oracolo per i test di parità.
|
||||||
|
"""
|
||||||
|
signals = signals.reindex(ohlcv.index).ffill().fillna(Side.FLAT)
|
||||||
|
shifted = [Side.FLAT, *list(signals.iloc[:-1])]
|
||||||
|
executed_side = pd.Series(shifted, index=ohlcv.index, dtype=object)
|
||||||
|
|
||||||
|
position: Position | None = None
|
||||||
|
position_entry_ts: pd.Timestamp | None = None
|
||||||
|
trades: list[Trade] = []
|
||||||
|
equity = 0.0
|
||||||
|
equity_history: list[float] = []
|
||||||
|
returns_history: list[float] = []
|
||||||
|
prev_equity = 0.0
|
||||||
|
|
||||||
|
for ts, row in ohlcv.iterrows():
|
||||||
|
target_side = executed_side.loc[ts]
|
||||||
|
current_side = position.side if position else Side.FLAT
|
||||||
|
if target_side != current_side:
|
||||||
|
if position is not None:
|
||||||
|
assert position_entry_ts is not None
|
||||||
|
trade = Trade(
|
||||||
|
entry_ts=position_entry_ts,
|
||||||
|
exit_ts=ts,
|
||||||
|
side=position.side,
|
||||||
|
size=position.size,
|
||||||
|
entry_price=position.entry_price,
|
||||||
|
exit_price=float(row["open"]),
|
||||||
|
fees_bp=fees_bp,
|
||||||
|
)
|
||||||
|
trades.append(trade)
|
||||||
|
equity += trade.net_pnl
|
||||||
|
position = None
|
||||||
|
position_entry_ts = None
|
||||||
|
if target_side in (Side.LONG, Side.SHORT):
|
||||||
|
position = Position(
|
||||||
|
side=target_side, entry_price=float(row["open"]), size=1.0
|
||||||
|
)
|
||||||
|
position_entry_ts = ts
|
||||||
|
mark = float(row["close"])
|
||||||
|
mtm = position.unrealized_pnl(mark) if position else 0.0
|
||||||
|
current_equity = equity + mtm
|
||||||
|
equity_history.append(current_equity)
|
||||||
|
returns_history.append(current_equity - prev_equity)
|
||||||
|
prev_equity = current_equity
|
||||||
|
if position is not None:
|
||||||
|
assert position_entry_ts is not None
|
||||||
|
last_ts = ohlcv.index[-1]
|
||||||
|
last_close = float(ohlcv["close"].iloc[-1])
|
||||||
|
trade = Trade(
|
||||||
|
entry_ts=position_entry_ts,
|
||||||
|
exit_ts=last_ts,
|
||||||
|
side=position.side,
|
||||||
|
size=position.size,
|
||||||
|
entry_price=position.entry_price,
|
||||||
|
exit_price=last_close,
|
||||||
|
fees_bp=fees_bp,
|
||||||
|
)
|
||||||
|
trades.append(trade)
|
||||||
|
equity += trade.net_pnl
|
||||||
|
equity_history[-1] = equity
|
||||||
|
if len(returns_history) >= 2:
|
||||||
|
returns_history[-1] = equity - equity_history[-2]
|
||||||
|
|
||||||
|
return BacktestResult(
|
||||||
|
equity_curve=pd.Series(equity_history, index=ohlcv.index, name="equity"),
|
||||||
|
returns=pd.Series(returns_history, index=ohlcv.index, name="returns"),
|
||||||
|
trades=trades,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _random_ohlcv(n: int, seed: int) -> pd.DataFrame:
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
rets = rng.normal(0.0, 0.01, size=n)
|
||||||
|
close = 100.0 * np.exp(np.cumsum(rets))
|
||||||
|
idx = pd.date_range("2024-01-01", periods=n, freq="1h", tz="UTC")
|
||||||
|
return pd.DataFrame(
|
||||||
|
{
|
||||||
|
"open": close * (1 + rng.normal(0, 0.001, n)),
|
||||||
|
"high": close * 1.005,
|
||||||
|
"low": close * 0.995,
|
||||||
|
"close": close,
|
||||||
|
"volume": rng.uniform(1.0, 100.0, n),
|
||||||
|
},
|
||||||
|
index=idx,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _random_signals(n: int, seed: int, p_change: float = 0.1) -> pd.Series:
|
||||||
|
"""Segnali con persistenza: ad ogni bar con prob p_change cambia stato."""
|
||||||
|
rng = np.random.default_rng(seed + 999)
|
||||||
|
states = [Side.LONG, Side.SHORT, Side.FLAT]
|
||||||
|
out: list[Side] = [rng.choice(states)]
|
||||||
|
for _ in range(1, n):
|
||||||
|
out.append(rng.choice(states) if rng.random() < p_change else out[-1])
|
||||||
|
idx = pd.date_range("2024-01-01", periods=n, freq="1h", tz="UTC")
|
||||||
|
return pd.Series(out, index=idx, dtype=object)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("seed", [0, 1, 42, 123, 999])
|
||||||
|
def test_vectorized_equals_legacy(seed: int) -> None:
|
||||||
|
df = _random_ohlcv(500, seed)
|
||||||
|
signals = _random_signals(500, seed)
|
||||||
|
engine = BacktestEngine(fees_bp=5.0)
|
||||||
|
new = engine.run(df, signals)
|
||||||
|
ref = _legacy_run(df, signals, fees_bp=5.0)
|
||||||
|
|
||||||
|
pd.testing.assert_series_equal(
|
||||||
|
new.equity_curve, ref.equity_curve, rtol=1e-9, atol=1e-9
|
||||||
|
)
|
||||||
|
pd.testing.assert_series_equal(
|
||||||
|
new.returns, ref.returns, rtol=1e-9, atol=1e-9
|
||||||
|
)
|
||||||
|
assert len(new.trades) == len(ref.trades)
|
||||||
|
for nt, rt in zip(new.trades, ref.trades, strict=True):
|
||||||
|
assert nt.entry_ts == rt.entry_ts
|
||||||
|
assert nt.exit_ts == rt.exit_ts
|
||||||
|
assert nt.side == rt.side
|
||||||
|
assert nt.entry_price == pytest.approx(rt.entry_price, abs=1e-12)
|
||||||
|
assert nt.exit_price == pytest.approx(rt.exit_price, abs=1e-12)
|
||||||
|
assert nt.net_pnl == pytest.approx(rt.net_pnl, abs=1e-12)
|
||||||
|
|
||||||
|
|
||||||
|
def test_vectorized_handles_position_still_open_at_end() -> None:
|
||||||
|
"""Edge case: signal LONG fino all'ultimo bar (exit a close[-1] forced)."""
|
||||||
|
df = _random_ohlcv(100, seed=7)
|
||||||
|
signals = pd.Series([Side.LONG] * 100, index=df.index)
|
||||||
|
new = BacktestEngine(fees_bp=10.0).run(df, signals)
|
||||||
|
ref = _legacy_run(df, signals, fees_bp=10.0)
|
||||||
|
pd.testing.assert_series_equal(new.equity_curve, ref.equity_curve, atol=1e-9)
|
||||||
|
assert len(new.trades) == 1
|
||||||
|
assert new.trades[0].side == Side.LONG
|
||||||
|
|
||||||
|
|
||||||
|
def test_vectorized_zero_signals_no_trades() -> None:
|
||||||
|
df = _random_ohlcv(50, seed=3)
|
||||||
|
signals = pd.Series([Side.FLAT] * 50, index=df.index)
|
||||||
|
new = BacktestEngine().run(df, signals)
|
||||||
|
assert len(new.trades) == 0
|
||||||
|
assert (new.equity_curve == 0).all()
|
||||||
+1
-1
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from multi_swarm.backtest.orders import Order, Position, Side, Trade
|
from multi_swarm_core.backtest.orders import Order, Position, Side, Trade
|
||||||
|
|
||||||
|
|
||||||
def test_order_validates_side() -> None:
|
def test_order_validates_side() -> None:
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import pytest
|
import pytest
|
||||||
import responses
|
import responses
|
||||||
|
|
||||||
from multi_swarm.cerbero.client import CerberoClient
|
from multi_swarm_core.cerbero.client import CerberoClient
|
||||||
|
|
||||||
|
|
||||||
@responses.activate
|
@responses.activate
|
||||||
+1
-1
@@ -6,7 +6,7 @@ from pathlib import Path
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from multi_swarm.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
from multi_swarm_core.data.cerbero_ohlcv import CerberoOHLCVLoader, OHLCVRequest
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from multi_swarm.cerbero.tools import CerberoTools
|
from multi_swarm_core.cerbero.tools import CerberoTools
|
||||||
|
|
||||||
|
|
||||||
def test_tools_dispatch_sma(mocker):
|
def test_tools_dispatch_sma(mocker):
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Tests for multi_swarm.config.Settings.
|
"""Tests for multi_swarm_core.config.Settings.
|
||||||
|
|
||||||
Note on .env isolation:
|
Note on .env isolation:
|
||||||
The happy-path test relies on monkeypatch.setenv to provide values.
|
The happy-path test relies on monkeypatch.setenv to provide values.
|
||||||
@@ -10,7 +10,7 @@ absence of required env vars. This keeps the test deterministic both in CI
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from multi_swarm.config import Settings
|
from multi_swarm_core.config import Settings
|
||||||
|
|
||||||
|
|
||||||
def test_settings_loads_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_settings_loads_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
from multi_swarm.genome.hypothesis import ModelTier
|
from multi_swarm_core.genome.hypothesis import ModelTier
|
||||||
from multi_swarm.llm.cost_tracker import CostTracker, estimate_cost
|
from multi_swarm_core.llm.cost_tracker import CostTracker, estimate_cost
|
||||||
|
|
||||||
|
|
||||||
def test_estimate_cost_tier_c():
|
def test_estimate_cost_tier_c():
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from multi_swarm.metrics.diversity import population_prompt_diversity
|
from multi_swarm_core.metrics.diversity import population_prompt_diversity
|
||||||
|
|
||||||
|
|
||||||
def test_empty_or_single_prompt_zero_diversity() -> None:
|
def test_empty_or_single_prompt_zero_diversity() -> None:
|
||||||
+2
-2
@@ -4,8 +4,8 @@ import numpy as np
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from multi_swarm.agents.falsification import FalsificationAgent, FalsificationReport
|
from multi_swarm_core.agents.falsification import FalsificationAgent, FalsificationReport
|
||||||
from multi_swarm.protocol.parser import parse_strategy
|
from multi_swarm_core.protocol.parser import parse_strategy
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user