Files
PythagorasGoal/README.md
T
Adriano Dal Pastro 8fd2c16cac fix(live): MT01 usa trend 1h live da Cerbero, non dal parquet statico
Il paper trader restava a zero trade: il feed Cerbero era fermo a
mezzanotte (bug end_date lato cerbero-mcp, poi risolto) e MT01 leggeva
il trend 1h da un parquet statico, di fatto congelandolo (gap ~15h sul
bar corrente). Ora il runner fa fetch 1h live per le strategie MTF e lo
passa a generate_signals via il parametro df_1h (fallback al parquet se
assente). Aggiornati CLAUDE.md, README e diario 2026-05-28.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 15:30:26 +00:00

201 lines
8.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# PythagorasGoal
Sistema di riconoscimento pattern frattali e predizione per il trading di criptovalute (BTC, ETH), ispirato al framework teorico di Serleto & Malanga (*Pythagoras Trading Prediction*).
## Obiettivo
Partendo da un capitale iniziale di €1.000, raggiungere un profitto medio di €50 al giorno entro 68 mesi, tramite strategie algoritmiche che combinano analisi frattale, squeeze di volatilità e machine learning.
## Risultati
Oltre 35 strategie testate su dati storici 20182026 (BTC e ETH, timeframe 15m / 1h, fee 0.2% round-trip, leva 3x, posizione 15%). Le migliori:
| Codice | Strategia | Mercato | Accuracy | Trades | Max DD | Robustezza |
|--------|-----------|---------|----------|--------|--------|------------|
| MT01 | Squeeze + MTF Momentum | BTC 15m | **82.7%** | 503 | 5.9% | ✅ 9/9 anni |
| MT01 | Squeeze + MTF Momentum | ETH 15m | 81.2% | 404 | 2.9% | ✅ 9/9 anni |
| PD01 | Price-Volume Divergence | ETH 15m | 80.9% | 465 | **2.3%** | ✅ 9/9 anni |
| PD01 | Price-Volume Divergence | BTC 15m | 80.6% | 578 | 2.7% | ✅ 9/9 anni |
| CM01 | Cross-Market Momentum | ETH 15m | 80.6% | 433 | **2.2%** | ✅ 9/9 anni |
| AD01 | Adaptive Squeeze | BTC 15m | 79.9% | 1364 | 9.9% | ✅ 9/9 anni |
| SQ02 | Antifake + Volume | BTC 15m | 79.7% | 1250 | 6.5% | ✅ 9/9 anni |
La famiglia squeeze (compressione → espansione di volatilità) è il nucleo comune. Le migliori varianti aggiungono un filtro indipendente: conferma del trend su timeframe superiore (MT01), trend del volume al breakout (PD01), momentum dell'asset correlato (CM01), o soglia di squeeze adattiva al regime di volatilità (AD01). Tutte mantengono accuracy ≥67% in ogni singolo anno dal 2018, con i drawdown più contenuti (2-3%) su ETH.
## Come funziona
### Volatility Squeeze Breakout
Il meccanismo centrale sfrutta i cicli naturali di compressione ed espansione della volatilità:
1. **Compressione** — le Bollinger Bands entrano dentro i Keltner Channel (il prezzo si muove sempre meno, accumulando "energia").
2. **Breakout** — le bande escono dal canale. Un impulso direzionale parte.
3. **Filtri** — anti-fakeout (scarta breakout con retrace >60%) + volume confirmation (breakout >1.3× media).
4. **ML opzionale** — un modello GradientBoosting (GBM), addestrato walk-forward su feature strutturali, conferma la direzione e filtra i segnali deboli.
### Filtri di conferma indipendenti
Le varianti più recenti aggiungono un singolo filtro di conferma al breakout, ciascuno motivato da una dinamica di mercato reale (non da ottimizzazione dei parametri):
- **MT01 — Multi-timeframe momentum.** Entra solo se la EMA su timeframe orario conferma il trend nella direzione del breakout. Filtra i breakout controtendenza.
- **PD01 — Price-volume divergence.** Richiede che il volume sia in *crescita* al momento del breakout, non solo elevato: un breakout su volume calante è debole e viene scartato.
- **CM01 — Cross-market momentum.** Entra solo se l'asset correlato (BTC ↔ ETH) mostra momentum nella stessa direzione nelle ultime barre.
- **AD01 — Adaptive squeeze.** La soglia di squeeze si adatta al regime di volatilità: più selettiva nei mercati agitati, più permissiva in quelli calmi.
### Feature ML (44 dimensioni)
- Rapporti body/shadow normalizzati su finestre multiple (12, 24, 48 candele)
- Momentum, volatilità, skewness, kurtosis dei rendimenti logaritmici
- Autocorrelazione lag-1 e profilo volumetrico
- Durata della fase di squeeze e rapporto di espansione Keltner
- Posizione del prezzo rispetto al range recente e ATR normalizzato
## Struttura progetto
```
PythagorasGoal/
├── src/
│ ├── data/ # Download e gestione dati (Cerbero MCP + Binance)
│ ├── fractal/ # Indicatori frattali: Hurst, Higuchi FD, self-similarity
│ ├── backtest/ # Motore di backtesting con fee e metriche
│ ├── strategies/ # Classe base Strategy ABC + indicatori condivisi
│ │ ├── base.py # Strategy, Signal, BacktestResult, YearlyStats
│ │ └── indicators.py # keltner_ratio, detect_squeezes, ema, atr, rv, corr
│ └── live/ # Paper trading live su Deribit testnet
│ ├── multi_runner.py # Orchestratore multi-strategia
│ ├── strategy_worker.py # Worker indipendente con stato persistente
│ ├── strategy_loader.py # Import dinamico classi Strategy
│ ├── cerbero_client.py # Client HTTP per Cerbero MCP
│ ├── signal_engine.py # Squeeze + ML real-time (per ML01)
│ └── telegram_notifier.py
├── scripts/
│ ├── strategies/ # Strategie attive (SQ01-SQ04, ML01, MT01, PD01, CM01, AD01)
│ ├── waste/ # Strategie scartate (W01-W28)
│ └── analysis/ # Script di confronto e report
├── strategies.yml # Config multi-strategy paper trader
├── data/
│ └── raw/ # Parquet OHLCV (gitignored, ~70 MB)
├── docs/
│ ├── diary/ # Diario di ricerca giornaliero
│ └── specs/ # Specifiche di design
├── Dockerfile
├── docker-compose.yml
└── pyproject.toml
```
## Strategie attive
Tutte le strategie estendono `src.strategies.base.Strategy` con interfaccia comune: `generate_signals() → backtest() → report()`.
| Codice | Script | Tipo | Descrizione |
|--------|--------|------|-------------|
| SQ01 | `SQ01_squeeze_base.py` | Regole | Squeeze breakout puro |
| SQ02 | `SQ02_squeeze_antifake_vol.py` | Regole | Squeeze + antifakeout + volume confirm |
| SQ03 | `SQ03_squeeze_all_filters.py` | Regole | Squeeze + filtri selezionabili (9 preset) |
| SQ04 | `SQ04_squeeze_ultimate.py` | Regole | Combo incrementali con correlazione/trend |
| ML01 | `ML01_squeeze_gbm.py` | ML | Squeeze + GBM walk-forward |
| MT01 | `MT01_squeeze_mtf_momentum.py` | Regole | Squeeze 15m + conferma trend EMA 1h (max accuracy) |
| PD01 | `PD01_price_volume_divergence.py` | Regole | Squeeze + trend del volume al breakout (DD minimo) |
| CM01 | `CM01_cross_market_momentum.py` | Regole | Squeeze + momentum dell'asset correlato (BTC ↔ ETH) |
| AD01 | `AD01_adaptive_squeeze.py` | Regole | Squeeze con soglia adattiva al regime di volatilità |
Per eseguire il backtest di una strategia:
```bash
uv run python scripts/strategies/MT01_squeeze_mtf_momentum.py
```
Per il confronto completo per anno e mercato:
```bash
uv run python scripts/analysis/yearly_market_report.py
```
## Paper Trading Live
Il multi-strategy runner esegue N strategie in parallelo su dati live da Cerbero MCP, ognuna con €1000 USDC virtuali indipendenti. Le strategie multi-timeframe (MT01) ricevono anche l'1h **live** da Cerbero ad ogni poll, così la conferma del trend non resta indietro rispetto al feed 15m.
### Avvio
```bash
# Locale
uv run python -m src.live.multi_runner
# Docker
docker compose up -d
```
### Configurazione
Le strategie attive sono definite in `strategies.yml`:
```yaml
defaults:
capital: 1000
position_size: 0.15
leverage: 3
strategies:
- name: SQ02_antifake_vol
asset: BTC
tf: 15m
enabled: true
```
Per aggiungere una strategia: nuova riga in `strategies.yml`, poi `docker compose restart`. Lo storico delle strategie esistenti rimane intatto.
### Persistenza
Ogni strategia ha la sua directory in `data/paper_trades/`:
```
data/paper_trades/
SQ02_antifake_vol__BTC__15m/
trades.jsonl # Storico trade append-only
status.json # Stato corrente (resume al restart)
```
Notifiche Telegram per ogni trade (richiede `TELEGRAM_BOT_TOKEN` e `TELEGRAM_CHAT_ID` in `.env`).
## Setup
```bash
# Clona e installa
git clone <repo-url> && cd PythagorasGoal
uv sync
# Scarica dati storici (~70 MB)
uv run python -m src.data.downloader
# Backtest strategia migliore
uv run python scripts/strategies/MT01_squeeze_mtf_momentum.py
# Paper trading live
uv run python -m src.live.multi_runner
```
### Requisiti
- Python ≥ 3.11
- [uv](https://docs.astral.sh/uv/) come package manager
- Accesso a Cerbero MCP (`cerbero-mcp.tielogic.xyz`) per dati Deribit live
- Docker (opzionale, per deploy su VPS)
## Dati
| Asset | Timeframe | Candele | Copertura |
|-------|-----------|---------|-----------|
| BTC | 5m / 15m / 1h | 883K / 294K / 74K | 2018-01 → oggi |
| ETH | 5m / 15m / 1h | 882K / 294K / 74K | 2018-01 → oggi |
Fonte primaria: Deribit perpetual via Cerbero MCP. Fallback: Binance spot via ccxt. Formato: Apache Parquet.
## Riferimenti
- Serleto, L. & Malanga, C. — *Pythagoras Trading Prediction* (2024)
- Serleto, L. & Malanga, C. — *Libro dei Frattali* (2024)
## Licenza
Uso privato. Non destinato alla distribuzione.