Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0e47956f7a | |||
| fa2d74be77 | |||
| 041db2191c | |||
| 185ac0d49b | |||
| 0ab3b5698a | |||
| 7639e5012b | |||
| 2694a4a00c | |||
| a7b3c3c203 |
@@ -19,7 +19,12 @@ Progetto di ricerca: riconoscimento pattern frattali per trading algoritmico su
|
|||||||
src/data/ → download e caricamento dati (downloader.py)
|
src/data/ → download e caricamento dati (downloader.py)
|
||||||
src/fractal/ → indicatori frattali (patterns.py, indicators.py, similarity.py)
|
src/fractal/ → indicatori frattali (patterns.py, indicators.py, similarity.py)
|
||||||
src/backtest/ → engine di backtesting (engine.py)
|
src/backtest/ → engine di backtesting (engine.py)
|
||||||
scripts/ → analisi e strategie numerate 01–13
|
src/strategies/ → classe base Strategy ABC + indicatori condivisi
|
||||||
|
base.py → Strategy, Signal, BacktestResult, YearlyStats
|
||||||
|
indicators.py → keltner_ratio, detect_squeezes, ema, atr, rv, correlation
|
||||||
|
scripts/strategies/ → strategie attive (SQ01-SQ04, ML01)
|
||||||
|
scripts/waste/ → strategie scartate (W01-W22 + REF originali)
|
||||||
|
scripts/analysis/ → script di confronto e report
|
||||||
docs/diary/ → diario di ricerca giornaliero
|
docs/diary/ → diario di ricerca giornaliero
|
||||||
data/raw/ → file .parquet OHLCV (gitignored)
|
data/raw/ → file .parquet OHLCV (gitignored)
|
||||||
data/processed/ → modelli salvati (gitignored)
|
data/processed/ → modelli salvati (gitignored)
|
||||||
@@ -30,7 +35,8 @@ data/processed/ → modelli salvati (gitignored)
|
|||||||
```bash
|
```bash
|
||||||
uv sync # installa dipendenze
|
uv sync # installa dipendenze
|
||||||
uv run python -m src.data.downloader # scarica dati storici
|
uv run python -m src.data.downloader # scarica dati storici
|
||||||
uv run python scripts/13_squeeze_ml_hybrid.py # strategia vincente
|
uv run python scripts/strategies/SQ02_squeeze_antifake_vol.py # miglior strategia robusta
|
||||||
|
uv run python scripts/strategies/ML01_squeeze_gbm.py # squeeze + ML (GBM)
|
||||||
uv run pytest # test
|
uv run pytest # test
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -60,9 +66,23 @@ Configurazione migliore: ETH 15m, BBw=14, squeeze threshold=0.8, breakout=3 barr
|
|||||||
|
|
||||||
Risultato backtestato: 76.9% accuracy, 118% annuo, 4.2% drawdown, €13.78/giorno da €1.000.
|
Risultato backtestato: 76.9% accuracy, 118% annuo, 4.2% drawdown, €13.78/giorno da €1.000.
|
||||||
|
|
||||||
|
## Strategie attive
|
||||||
|
|
||||||
|
| Codice | Nome | Tipo | Accuracy | Note |
|
||||||
|
|--------|------|------|----------|------|
|
||||||
|
| SQ01 | Squeeze Base | Regole | 76.7% | Squeeze breakout puro, baseline |
|
||||||
|
| SQ02 | Antifake+Vol | Regole | 79.7% | **Miglior robusto** — 9 anni, Sharpe 5.01 |
|
||||||
|
| SQ03 | All Filters | Regole | 79.2% | Cross-asset + timing + long squeeze |
|
||||||
|
| SQ04 | Ultimate | Regole | 81.6% | Max accuracy ma concentrato 2018 |
|
||||||
|
| ML01 | Squeeze+GBM | ML | 78.8% | Walk-forward, €12/day, DD basso |
|
||||||
|
|
||||||
|
Tutte le strategie estendono `src.strategies.base.Strategy` con interfaccia comune:
|
||||||
|
`generate_signals() → backtest() → report()`.
|
||||||
|
|
||||||
## Convenzioni
|
## Convenzioni
|
||||||
|
|
||||||
- Script numerati progressivamente (`01_`, `02_`, …). Ogni script è autocontenuto.
|
- Strategie in `scripts/strategies/` con codice univoco (SQ01, ML01, ...).
|
||||||
|
- Script scartati in `scripts/waste/` con prefisso W01-W22.
|
||||||
- Diario in `docs/diary/YYYY-MM-DD.md`. Aggiornare dopo ogni esperimento significativo.
|
- Diario in `docs/diary/YYYY-MM-DD.md`. Aggiornare dopo ogni esperimento significativo.
|
||||||
- Nessun dato sensibile nei commit (token, chiavi API). Usare `.gitignore`.
|
- Nessun dato sensibile nei commit (token, chiavi API). Usare `.gitignore`.
|
||||||
- Verificare sempre assenza di data leakage prima di fidarsi dei risultati. In particolare: `returns[i-w : i]` include `close[i]` che è un candle nel futuro — usare `returns[i-w : i-1]`.
|
- Verificare sempre assenza di data leakage prima di fidarsi dei risultati. In particolare: `returns[i-w : i]` include `close[i]` che è un candle nel futuro — usare `returns[i-w : i-1]`.
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/app/data
|
- ./data:/app/data
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
environment:
|
environment:
|
||||||
- PYTHONUNBUFFERED=1
|
- PYTHONUNBUFFERED=1
|
||||||
healthcheck:
|
healthcheck:
|
||||||
|
|||||||
@@ -0,0 +1,309 @@
|
|||||||
|
"""Confronto migliori strategie S1 e S2 — andamento per anno."""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from src.data.downloader import load_data
|
||||||
|
from src.fractal.patterns import encode_candles
|
||||||
|
|
||||||
|
FEE_PERP = 0.002 # 0.1% taker roundtrip perpetual
|
||||||
|
FEE_OPT = 0.0052 # options roundtrip
|
||||||
|
INITIAL = 1000
|
||||||
|
LEVERAGE = 3
|
||||||
|
|
||||||
|
|
||||||
|
def keltner_ratio(close, high, low, window=14):
|
||||||
|
n = len(close)
|
||||||
|
r = np.full(n, np.nan)
|
||||||
|
for i in range(window, n):
|
||||||
|
wc, wh, wl = close[i-window:i], high[i-window:i], low[i-window:i]
|
||||||
|
ma = np.mean(wc)
|
||||||
|
bb_std = np.std(wc)
|
||||||
|
tr = np.maximum(wh-wl, np.maximum(np.abs(wh-np.roll(wc,1)), np.abs(wl-np.roll(wc,1))))
|
||||||
|
atr = np.mean(tr[1:])
|
||||||
|
kc = (ma+1.5*atr)-(ma-1.5*atr)
|
||||||
|
bb = (ma+2*bb_std)-(ma-2*bb_std)
|
||||||
|
if kc > 0:
|
||||||
|
r[i] = bb/kc
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def rv_ann(close, window):
|
||||||
|
lr = np.diff(np.log(np.where(close==0, 1e-10, close)))
|
||||||
|
r = np.full(len(close), np.nan)
|
||||||
|
for i in range(window, len(lr)):
|
||||||
|
r[i+1] = np.std(lr[i-window:i]) * np.sqrt(24*365)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def rsi(close, period=14):
|
||||||
|
delta = np.diff(close)
|
||||||
|
gain = np.where(delta>0, delta, 0)
|
||||||
|
loss = np.where(delta<0, -delta, 0)
|
||||||
|
result = np.full(len(close), 50.0)
|
||||||
|
if len(gain) < period:
|
||||||
|
return result
|
||||||
|
ag = np.mean(gain[:period])
|
||||||
|
al = np.mean(loss[:period])
|
||||||
|
for i in range(period, len(delta)):
|
||||||
|
ag = (ag*(period-1)+gain[i])/period
|
||||||
|
al = (al*(period-1)+loss[i])/period
|
||||||
|
result[i+1] = 100 if al == 0 else 100-100/(1+ag/al)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def ema(arr, period):
|
||||||
|
r = np.full(len(arr), np.nan)
|
||||||
|
k = 2/(period+1)
|
||||||
|
r[period-1] = np.mean(arr[:period])
|
||||||
|
for i in range(period, len(arr)):
|
||||||
|
r[i] = arr[i]*k + r[i-1]*(1-k)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
# =====================================================================
|
||||||
|
# S1 BEST: Squeeze Breakout ETH 1h (BBw=14, sq=0.8, brk=3)
|
||||||
|
# =====================================================================
|
||||||
|
def run_s1_squeeze(asset, tf):
|
||||||
|
df = load_data(asset, tf)
|
||||||
|
c, h, l, v = df["close"].values, df["high"].values, df["low"].values, df["volume"].values
|
||||||
|
n = len(c)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
kcr = keltner_ratio(c, h, l, 14)
|
||||||
|
|
||||||
|
yearly = {}
|
||||||
|
in_sq = False
|
||||||
|
sq_start = 0
|
||||||
|
|
||||||
|
for i in range(15, n):
|
||||||
|
if np.isnan(kcr[i]):
|
||||||
|
continue
|
||||||
|
is_sq = kcr[i] < 0.8
|
||||||
|
if is_sq and not in_sq:
|
||||||
|
in_sq = True
|
||||||
|
sq_start = i
|
||||||
|
elif not is_sq and in_sq:
|
||||||
|
in_sq = False
|
||||||
|
if i - sq_start < 5 or i + 3 >= n:
|
||||||
|
continue
|
||||||
|
first_ret = (c[i] - c[i-1]) / c[i-1]
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
direction = 1 if first_ret > 0 else -1
|
||||||
|
actual = (c[i+2] - c[i-1]) / c[i-1]
|
||||||
|
trade_ret = actual * direction
|
||||||
|
net = trade_ret * LEVERAGE - FEE_PERP * LEVERAGE
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"pnls": [], "wins": 0, "total": 0}
|
||||||
|
yearly[year]["pnls"].append(net)
|
||||||
|
yearly[year]["total"] += 1
|
||||||
|
if trade_ret > 0:
|
||||||
|
yearly[year]["wins"] += 1
|
||||||
|
|
||||||
|
return yearly
|
||||||
|
|
||||||
|
|
||||||
|
# =====================================================================
|
||||||
|
# S1 BEST ALT: Squeeze+ML hybrid ETH 15m
|
||||||
|
# =====================================================================
|
||||||
|
# Troppo complesso da ricalcolare (serve ML training). Uso i dati S1 squeeze puro.
|
||||||
|
|
||||||
|
|
||||||
|
# =====================================================================
|
||||||
|
# S2 BEST: VRP ETH 48h (con IV stimata, unico disponibile su 8 anni)
|
||||||
|
# =====================================================================
|
||||||
|
def run_s2_vrp(asset, dte=48):
|
||||||
|
df = load_data(asset, "1h")
|
||||||
|
c = df["close"].values
|
||||||
|
n = len(c)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
rv_24 = rv_ann(c, 24)
|
||||||
|
rv_168 = rv_ann(c, 168)
|
||||||
|
|
||||||
|
yearly = {}
|
||||||
|
for i in range(170, n - dte):
|
||||||
|
if ts.iloc[i].hour != 8:
|
||||||
|
continue
|
||||||
|
rv_s, rv_l = rv_24[i], rv_168[i]
|
||||||
|
if np.isnan(rv_s) or np.isnan(rv_l) or rv_s < 0.05 or rv_l < 0.05:
|
||||||
|
continue
|
||||||
|
regime = rv_s / rv_l
|
||||||
|
iv_pf = 0.9 if regime > 2 else (1.0 if regime > 1.5 else (1.1 if regime > 1 else 1.2))
|
||||||
|
iv = rv_l * iv_pf
|
||||||
|
prem = iv * np.sqrt(dte/(24*365)) * 0.8
|
||||||
|
spot = c[i]
|
||||||
|
move = abs(c[min(i+dte, n-1)] - spot) / spot
|
||||||
|
pos = 0.10
|
||||||
|
raw = (prem - move) * pos if move <= prem else max(-(move-prem)*pos, -pos*0.05)
|
||||||
|
net = raw - FEE_OPT * pos
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"pnls": [], "wins": 0, "total": 0}
|
||||||
|
yearly[year]["pnls"].append(net)
|
||||||
|
yearly[year]["total"] += 1
|
||||||
|
if raw > 0:
|
||||||
|
yearly[year]["wins"] += 1
|
||||||
|
return yearly
|
||||||
|
|
||||||
|
|
||||||
|
# =====================================================================
|
||||||
|
# S2 BEST PERPETUAL: Multi-TF 15m+1h BTC
|
||||||
|
# =====================================================================
|
||||||
|
def run_s2_multitf(asset):
|
||||||
|
df_1h = load_data(asset, "1h")
|
||||||
|
df_15m = load_data(asset, "15m")
|
||||||
|
c1h = df_1h["close"].values
|
||||||
|
ts1h = pd.to_datetime(df_1h["timestamp"], unit="ms", utc=True)
|
||||||
|
c15 = df_15m["close"].values
|
||||||
|
ts15 = df_15m["timestamp"].values
|
||||||
|
n15 = len(c15)
|
||||||
|
|
||||||
|
ema_50 = ema(c1h, 50)
|
||||||
|
rsi_15m = rsi(c15, 14)
|
||||||
|
|
||||||
|
yearly = {}
|
||||||
|
daily_done = set()
|
||||||
|
|
||||||
|
for i in range(100, n15 - 12):
|
||||||
|
ts_dt = pd.Timestamp(ts15[i], unit="ms", tz="UTC")
|
||||||
|
day = ts_dt.strftime("%Y-%m-%d")
|
||||||
|
if day in daily_done:
|
||||||
|
continue
|
||||||
|
if rsi_15m[i] > 35 and rsi_15m[i] < 65:
|
||||||
|
continue
|
||||||
|
h_idx = np.searchsorted(ts1h.values.astype("int64"), ts15[i]) - 1
|
||||||
|
if h_idx < 50 or h_idx >= len(c1h) or np.isnan(ema_50[h_idx]):
|
||||||
|
continue
|
||||||
|
|
||||||
|
direction = None
|
||||||
|
if rsi_15m[i] < 30 and c1h[h_idx] > ema_50[h_idx]:
|
||||||
|
direction = "long"
|
||||||
|
elif rsi_15m[i] > 70 and c1h[h_idx] < ema_50[h_idx]:
|
||||||
|
direction = "short"
|
||||||
|
if direction is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
entry = c15[i]
|
||||||
|
exit_price = c15[min(i+12, n15-1)]
|
||||||
|
trade_ret = (exit_price-entry)/entry if direction == "long" else (entry-exit_price)/entry
|
||||||
|
net = trade_ret * LEVERAGE - FEE_PERP * LEVERAGE
|
||||||
|
|
||||||
|
year = ts_dt.year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"pnls": [], "wins": 0, "total": 0}
|
||||||
|
yearly[year]["pnls"].append(net)
|
||||||
|
yearly[year]["total"] += 1
|
||||||
|
if trade_ret > 0:
|
||||||
|
yearly[year]["wins"] += 1
|
||||||
|
daily_done.add(day)
|
||||||
|
return yearly
|
||||||
|
|
||||||
|
|
||||||
|
# =====================================================================
|
||||||
|
# REPORT
|
||||||
|
# =====================================================================
|
||||||
|
strategies = {
|
||||||
|
"S1: Squeeze BTC 1h": run_s1_squeeze("BTC", "1h"),
|
||||||
|
"S1: Squeeze ETH 1h": run_s1_squeeze("ETH", "1h"),
|
||||||
|
"S1: Squeeze ETH 15m": run_s1_squeeze("ETH", "15m"),
|
||||||
|
"S2: VRP ETH 48h (IV est)": run_s2_vrp("ETH", 48),
|
||||||
|
"S2: VRP BTC 48h (IV est)": run_s2_vrp("BTC", 48),
|
||||||
|
"S2: MultiTF BTC 15m+1h": run_s2_multitf("BTC"),
|
||||||
|
"S2: MultiTF ETH 15m+1h": run_s2_multitf("ETH"),
|
||||||
|
}
|
||||||
|
|
||||||
|
all_years = sorted(set(y for v in strategies.values() for y in v))
|
||||||
|
|
||||||
|
print("=" * 120)
|
||||||
|
print(" MIGLIORI STRATEGIE — ANDAMENTO PER ANNO")
|
||||||
|
print(" Fee reali. PnL su €1000 flat (no compounding). Dati OHLCV reali 2018-2026.")
|
||||||
|
print(" ⚠ VRP usa IV STIMATA (non reale) — fidarsi solo dei dati perpetual per backtest lungo")
|
||||||
|
print("=" * 120)
|
||||||
|
|
||||||
|
# Header
|
||||||
|
hdr = f" {'Anno':>6s}"
|
||||||
|
for name in strategies:
|
||||||
|
short = name.split(": ")[1][:18]
|
||||||
|
hdr += f" | {short:>18s}"
|
||||||
|
print(hdr)
|
||||||
|
print(f" {'-' * (len(hdr) - 2)}")
|
||||||
|
|
||||||
|
# Per anno: accuracy / PnL totale
|
||||||
|
for year in all_years:
|
||||||
|
row_acc = f" {year:>6d}"
|
||||||
|
row_pnl = f" {'':>6s}"
|
||||||
|
for name, yearly in strategies.items():
|
||||||
|
if year in yearly:
|
||||||
|
d = yearly[year]
|
||||||
|
acc = d["wins"]/d["total"]*100 if d["total"] > 0 else 0
|
||||||
|
pnl = sum(d["pnls"]) * INITIAL
|
||||||
|
tag = "▓" if acc >= 75 else "▒" if acc >= 65 else "░" if acc >= 55 else " "
|
||||||
|
row_acc += f" | {acc:>5.1f}% {tag} {d['total']:>3d}t"
|
||||||
|
row_pnl += f" | €{pnl:>+8.0f} "
|
||||||
|
else:
|
||||||
|
row_acc += f" | {'—':>18s}"
|
||||||
|
row_pnl += f" | {'':>18s}"
|
||||||
|
print(row_acc)
|
||||||
|
print(row_pnl)
|
||||||
|
|
||||||
|
# Totali
|
||||||
|
print(f" {'-' * (len(hdr) - 2)}")
|
||||||
|
row_tot = f" {'TOT':>6s}"
|
||||||
|
for name, yearly in strategies.items():
|
||||||
|
all_pnls = [p for d in yearly.values() for p in d["pnls"]]
|
||||||
|
all_wins = sum(d["wins"] for d in yearly.values())
|
||||||
|
all_total = sum(d["total"] for d in yearly.values())
|
||||||
|
acc = all_wins/all_total*100 if all_total > 0 else 0
|
||||||
|
pnl = sum(all_pnls) * INITIAL
|
||||||
|
row_tot += f" | {acc:>5.1f}% {all_total:>4d}t"
|
||||||
|
print(row_tot)
|
||||||
|
|
||||||
|
row_pnl_tot = f" {'€TOT':>6s}"
|
||||||
|
for name, yearly in strategies.items():
|
||||||
|
all_pnls = [p for d in yearly.values() for p in d["pnls"]]
|
||||||
|
pnl = sum(all_pnls) * INITIAL
|
||||||
|
row_pnl_tot += f" | €{pnl:>+8.0f} "
|
||||||
|
print(row_pnl_tot)
|
||||||
|
|
||||||
|
# Compounding
|
||||||
|
print(f"\n {'':>6s}", end="")
|
||||||
|
for name in strategies:
|
||||||
|
short = name.split(": ")[1][:18]
|
||||||
|
print(f" | {short:>18s}", end="")
|
||||||
|
print()
|
||||||
|
|
||||||
|
row_comp = f" {'COMP':>6s}"
|
||||||
|
for name, yearly in strategies.items():
|
||||||
|
cap = float(INITIAL)
|
||||||
|
for year in sorted(yearly):
|
||||||
|
for pnl in yearly[year]["pnls"]:
|
||||||
|
cap += cap * pnl
|
||||||
|
cap = max(cap, 10)
|
||||||
|
row_comp += f" | €{cap:>12,.0f} "
|
||||||
|
print(row_comp)
|
||||||
|
|
||||||
|
# Drawdown
|
||||||
|
row_dd = f" {'MAXDD':>6s}"
|
||||||
|
for name, yearly in strategies.items():
|
||||||
|
cap = float(INITIAL)
|
||||||
|
peak = cap
|
||||||
|
mdd = 0
|
||||||
|
for year in sorted(yearly):
|
||||||
|
for pnl in yearly[year]["pnls"]:
|
||||||
|
cap += cap * pnl
|
||||||
|
cap = max(cap, 10)
|
||||||
|
if cap > peak: peak = cap
|
||||||
|
dd = (peak - cap) / peak
|
||||||
|
mdd = max(mdd, dd)
|
||||||
|
row_dd += f" | {mdd*100:>12.1f}% "
|
||||||
|
print(row_dd)
|
||||||
|
|
||||||
|
# Legenda
|
||||||
|
print(f"\n Legenda: ▓ ≥75% acc ▒ ≥65% acc ░ ≥55% acc")
|
||||||
|
print(f" ⚠ S2 VRP: IV stimata (rv_long × 1.0-1.2), NON dati reali opzioni")
|
||||||
|
print(f" S1 Squeeze e S2 MultiTF: dati OHLCV reali al 100%")
|
||||||
@@ -0,0 +1,559 @@
|
|||||||
|
"""Analisi finale — S1 (squeeze puro) vs Script 13 (squeeze+ML GBM).
|
||||||
|
Metriche: PnL, num trades, DD max, tempo medio a mercato, descrizione.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from sklearn.ensemble import GradientBoostingClassifier
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
from src.data.downloader import load_data
|
||||||
|
from src.fractal.patterns import encode_candles
|
||||||
|
|
||||||
|
FEE_PERP = 0.002
|
||||||
|
FEE_ML = 0.001
|
||||||
|
INITIAL = 1000
|
||||||
|
LEVERAGE = 3
|
||||||
|
|
||||||
|
TF_MINUTES = {"1m": 1, "5m": 5, "15m": 15, "1h": 60, "4h": 240, "1d": 1440}
|
||||||
|
|
||||||
|
|
||||||
|
# ── helpers ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def keltner_ratio(close, high, low, window=14):
|
||||||
|
n = len(close)
|
||||||
|
r = np.full(n, np.nan)
|
||||||
|
for i in range(window, n):
|
||||||
|
wc, wh, wl = close[i-window:i], high[i-window:i], low[i-window:i]
|
||||||
|
ma = np.mean(wc)
|
||||||
|
bb_std = np.std(wc)
|
||||||
|
tr = np.maximum(wh-wl, np.maximum(np.abs(wh-np.roll(wc,1)), np.abs(wl-np.roll(wc,1))))
|
||||||
|
atr = np.mean(tr[1:])
|
||||||
|
kc = (ma+1.5*atr)-(ma-1.5*atr)
|
||||||
|
bb = (ma+2*bb_std)-(ma-2*bb_std)
|
||||||
|
if kc > 0:
|
||||||
|
r[i] = bb/kc
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def detect_squeezes(close, high, low, kcr, sq_thr=0.8, min_dur=5):
|
||||||
|
events = []
|
||||||
|
in_sq = False
|
||||||
|
sq_start = 0
|
||||||
|
for i in range(1, len(close)):
|
||||||
|
if np.isnan(kcr[i]):
|
||||||
|
continue
|
||||||
|
is_sq = kcr[i] < sq_thr
|
||||||
|
if is_sq and not in_sq:
|
||||||
|
in_sq = True
|
||||||
|
sq_start = i
|
||||||
|
elif not is_sq and in_sq:
|
||||||
|
in_sq = False
|
||||||
|
dur = i - sq_start
|
||||||
|
if dur < min_dur:
|
||||||
|
continue
|
||||||
|
events.append({"idx": i, "dur": dur, "sq_start": sq_start,
|
||||||
|
"avg_vol_squeeze": np.mean(close[sq_start:i]),
|
||||||
|
"kcr_at_release": kcr[i]})
|
||||||
|
return events
|
||||||
|
|
||||||
|
|
||||||
|
def _build_result(yearly, capital, max_dd, all_t, all_w, time_pct, avg_dur_h):
|
||||||
|
acc = all_w / all_t * 100
|
||||||
|
tot_pnl = sum(p for d in yearly.values() for p in d["pnls"])
|
||||||
|
years_active = len(yearly)
|
||||||
|
all_pnls = [p for d in yearly.values() for p in d["pnls"]]
|
||||||
|
sharpe = np.mean(all_pnls) / np.std(all_pnls) * np.sqrt(252) if len(all_pnls) > 1 and np.std(all_pnls) > 0 else 0
|
||||||
|
|
||||||
|
year_details = {}
|
||||||
|
for y in sorted(yearly):
|
||||||
|
d = yearly[y]
|
||||||
|
ya = d["w"] / d["t"] * 100 if d["t"] > 0 else 0
|
||||||
|
yp = sum(d["pnls"])
|
||||||
|
year_details[y] = {"trades": d["t"], "acc": ya, "pnl": yp}
|
||||||
|
|
||||||
|
valid_years = {y: d for y, d in year_details.items() if d["trades"] >= 10}
|
||||||
|
if valid_years:
|
||||||
|
worst_y = min(valid_years, key=lambda y: valid_years[y]["acc"])
|
||||||
|
worst_acc = valid_years[worst_y]["acc"]
|
||||||
|
elif year_details:
|
||||||
|
worst_y = min(year_details, key=lambda y: year_details[y]["acc"])
|
||||||
|
worst_acc = year_details[worst_y]["acc"]
|
||||||
|
else:
|
||||||
|
worst_y = "N/A"
|
||||||
|
worst_acc = 0
|
||||||
|
|
||||||
|
daily_pnl = tot_pnl / (years_active * 365) if years_active > 0 else 0
|
||||||
|
|
||||||
|
return {
|
||||||
|
"trades": all_t, "acc": acc, "pnl": tot_pnl, "capital": capital,
|
||||||
|
"max_dd": max_dd * 100, "sharpe": sharpe, "daily_pnl": daily_pnl,
|
||||||
|
"time_in_market_pct": time_pct, "avg_dur_h": avg_dur_h,
|
||||||
|
"years_active": years_active, "worst_year": str(worst_y),
|
||||||
|
"worst_acc": worst_acc, "year_details": year_details,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ── S1: Squeeze breakout puro ────────────────────────────────────────
|
||||||
|
|
||||||
|
def run_s1_squeeze(asset, tf, hold=3):
|
||||||
|
df = load_data(asset, tf)
|
||||||
|
c, h, l, v = df["close"].values, df["high"].values, df["low"].values, df["volume"].values
|
||||||
|
n = len(c)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
kcr = keltner_ratio(c, h, l, 14)
|
||||||
|
events = detect_squeezes(c, h, l, kcr)
|
||||||
|
|
||||||
|
yearly = {}
|
||||||
|
capital = float(INITIAL)
|
||||||
|
peak = capital
|
||||||
|
max_dd = 0
|
||||||
|
total_bars = 0
|
||||||
|
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
if i + hold + 1 >= n:
|
||||||
|
continue
|
||||||
|
first_ret = (c[i] - c[i-1]) / c[i-1] if c[i-1] > 0 else 0
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
direction = 1 if first_ret > 0 else -1
|
||||||
|
entry = c[i-1]
|
||||||
|
exit_price = c[min(i + hold - 1, n - 1)]
|
||||||
|
actual = (exit_price - entry) / entry * direction
|
||||||
|
net = actual * LEVERAGE - FEE_PERP * LEVERAGE
|
||||||
|
|
||||||
|
capital += capital * 0.15 * net
|
||||||
|
capital = max(capital, 10)
|
||||||
|
if capital > peak: peak = capital
|
||||||
|
dd = (peak - capital) / peak
|
||||||
|
max_dd = max(max_dd, dd)
|
||||||
|
total_bars += hold
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnls": []}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if actual > 0: yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnls"].append(net * INITIAL)
|
||||||
|
|
||||||
|
all_t = sum(d["t"] for d in yearly.values())
|
||||||
|
all_w = sum(d["w"] for d in yearly.values())
|
||||||
|
if all_t == 0: return None
|
||||||
|
return _build_result(yearly, capital, max_dd, all_t, all_w,
|
||||||
|
total_bars / n * 100, hold * TF_MINUTES.get(tf, 60) / 60)
|
||||||
|
|
||||||
|
|
||||||
|
def run_s1_antifake_vol(asset, tf, hold=3):
|
||||||
|
df = load_data(asset, tf)
|
||||||
|
c, h, l, v = df["close"].values, df["high"].values, df["low"].values, df["volume"].values
|
||||||
|
n = len(c)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
kcr = keltner_ratio(c, h, l, 14)
|
||||||
|
events = detect_squeezes(c, h, l, kcr)
|
||||||
|
|
||||||
|
yearly = {}
|
||||||
|
capital = float(INITIAL)
|
||||||
|
peak = capital
|
||||||
|
max_dd = 0
|
||||||
|
total_bars = 0
|
||||||
|
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
if i + hold + 1 >= n:
|
||||||
|
continue
|
||||||
|
first_ret = (c[i] - c[i-1]) / c[i-1] if c[i-1] > 0 else 0
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
br = h[i] - l[i]
|
||||||
|
if br > 0:
|
||||||
|
if c[i] > c[i-1]:
|
||||||
|
if (h[i] - c[i]) / br > 0.6:
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
if (c[i] - l[i]) / br > 0.6:
|
||||||
|
continue
|
||||||
|
avg_v = np.mean(v[ev["sq_start"]:i])
|
||||||
|
if avg_v > 0 and v[i] <= avg_v * 1.3:
|
||||||
|
continue
|
||||||
|
|
||||||
|
direction = 1 if first_ret > 0 else -1
|
||||||
|
entry = c[i-1]
|
||||||
|
exit_price = c[min(i + hold - 1, n - 1)]
|
||||||
|
actual = (exit_price - entry) / entry * direction
|
||||||
|
net = actual * LEVERAGE - FEE_PERP * LEVERAGE
|
||||||
|
capital += capital * 0.15 * net
|
||||||
|
capital = max(capital, 10)
|
||||||
|
if capital > peak: peak = capital
|
||||||
|
dd = (peak - capital) / peak
|
||||||
|
max_dd = max(max_dd, dd)
|
||||||
|
total_bars += hold
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnls": []}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if actual > 0: yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnls"].append(net * INITIAL)
|
||||||
|
|
||||||
|
all_t = sum(d["t"] for d in yearly.values())
|
||||||
|
all_w = sum(d["w"] for d in yearly.values())
|
||||||
|
if all_t == 0: return None
|
||||||
|
return _build_result(yearly, capital, max_dd, all_t, all_w,
|
||||||
|
total_bars / n * 100, hold * TF_MINUTES.get(tf, 60) / 60)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Script 13: Squeeze + ML ibrida (GBM walk-forward) ────────────────
|
||||||
|
|
||||||
|
def build_features_at(df, i, squeeze_info):
|
||||||
|
if i < 100:
|
||||||
|
return None
|
||||||
|
o = df["open"].values
|
||||||
|
h = df["high"].values
|
||||||
|
l = df["low"].values
|
||||||
|
c = df["close"].values
|
||||||
|
v = df["volume"].values
|
||||||
|
feats = []
|
||||||
|
for w in [12, 24, 48]:
|
||||||
|
win_c = c[i-w:i]
|
||||||
|
win_o = o[i-w:i]
|
||||||
|
win_h = h[i-w:i]
|
||||||
|
win_l = l[i-w:i]
|
||||||
|
win_v = v[i-w:i]
|
||||||
|
mn, mx = win_l.min(), max(win_h.max(), win_c.max())
|
||||||
|
rng = mx - mn if mx - mn > 0 else 1e-10
|
||||||
|
total = win_h - win_l
|
||||||
|
total = np.where(total == 0, 1e-10, total)
|
||||||
|
body = np.abs(win_c - win_o) / total
|
||||||
|
direction = np.sign(win_c - win_o)
|
||||||
|
log_c = np.log(np.where(win_c == 0, 1e-10, win_c))
|
||||||
|
rets = np.diff(log_c)
|
||||||
|
v_mean = np.mean(win_v)
|
||||||
|
feats.extend([
|
||||||
|
np.mean(rets) if len(rets) > 0 else 0,
|
||||||
|
np.std(rets) if len(rets) > 0 else 0,
|
||||||
|
np.sum(rets) if len(rets) > 0 else 0,
|
||||||
|
float(pd.Series(rets).skew()) if len(rets) > 2 else 0,
|
||||||
|
float(pd.Series(rets).kurtosis()) if len(rets) > 3 else 0,
|
||||||
|
np.mean(body), np.std(body),
|
||||||
|
np.mean(direction), np.mean(direction[-min(3, w):]),
|
||||||
|
(win_c[-1] - mn) / rng,
|
||||||
|
win_v[-1] / v_mean if v_mean > 0 else 1,
|
||||||
|
np.corrcoef(rets[:-1], rets[1:])[0, 1] if len(rets) > 1 and np.std(rets) > 0 else 0,
|
||||||
|
])
|
||||||
|
sq = squeeze_info
|
||||||
|
feats.extend([
|
||||||
|
sq["dur"], sq["dur"] / 24, sq["kcr_at_release"],
|
||||||
|
v[i-1] / sq["avg_vol_squeeze"] if sq["avg_vol_squeeze"] > 0 else 1,
|
||||||
|
np.mean(v[i:min(i+3, len(v))]) / sq["avg_vol_squeeze"] if sq["avg_vol_squeeze"] > 0 else 1,
|
||||||
|
])
|
||||||
|
h48 = np.max(h[max(0, i-48):i])
|
||||||
|
l48 = np.min(l[max(0, i-48):i])
|
||||||
|
r48 = h48 - l48
|
||||||
|
feats.append((c[i-1] - l48) / r48 if r48 > 0 else 0.5)
|
||||||
|
tr = np.maximum(h[i-14:i] - l[i-14:i],
|
||||||
|
np.maximum(np.abs(h[i-14:i] - np.roll(c[i-14:i], 1)),
|
||||||
|
np.abs(l[i-14:i] - np.roll(c[i-14:i], 1))))
|
||||||
|
atr = np.mean(tr[1:])
|
||||||
|
feats.append(atr / c[i-1] if c[i-1] > 0 else 0)
|
||||||
|
first_ret = (c[i] - c[i-1]) / c[i-1] if c[i-1] > 0 else 0
|
||||||
|
feats.append(first_ret)
|
||||||
|
return np.nan_to_num(np.array(feats), nan=0, posinf=1e6, neginf=-1e6)
|
||||||
|
|
||||||
|
|
||||||
|
def run_s13_hybrid(asset, tf, bb_w, sq_thr, brk_bars, leverage, pos_pct, ml_thr):
|
||||||
|
df = load_data(asset, tf)
|
||||||
|
close = df["close"].values
|
||||||
|
high = df["high"].values
|
||||||
|
low = df["low"].values
|
||||||
|
volume = df["volume"].values
|
||||||
|
n = len(df)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
|
||||||
|
kcr = keltner_ratio(close, high, low, bb_w)
|
||||||
|
events = detect_squeezes(close, high, low, kcr, sq_thr)
|
||||||
|
|
||||||
|
X_all, y_all, ev_all = [], [], []
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
if i + brk_bars >= n or i < 100:
|
||||||
|
continue
|
||||||
|
feats = build_features_at(df, i, ev)
|
||||||
|
if feats is None:
|
||||||
|
continue
|
||||||
|
actual_ret = (close[i + brk_bars - 1] - close[i - 1]) / close[i - 1]
|
||||||
|
X_all.append(feats)
|
||||||
|
y_all.append(1 if actual_ret > 0 else 0)
|
||||||
|
ev_all.append(ev)
|
||||||
|
|
||||||
|
if len(X_all) < 50:
|
||||||
|
return None
|
||||||
|
|
||||||
|
X = np.array(X_all)
|
||||||
|
y = np.array(y_all)
|
||||||
|
|
||||||
|
TRAIN_SIZE = max(int(len(X) * 0.5), 50)
|
||||||
|
STEP_SIZE = max(int(len(X) * 0.1), 10)
|
||||||
|
|
||||||
|
yearly = {}
|
||||||
|
capital = float(INITIAL)
|
||||||
|
peak = capital
|
||||||
|
max_dd = 0
|
||||||
|
total_bars = 0
|
||||||
|
all_t = 0
|
||||||
|
all_w = 0
|
||||||
|
|
||||||
|
start = 0
|
||||||
|
while start + TRAIN_SIZE + STEP_SIZE <= len(X):
|
||||||
|
train_end = start + TRAIN_SIZE
|
||||||
|
test_end = min(train_end + STEP_SIZE, len(X))
|
||||||
|
X_tr, y_tr = X[start:train_end], y[start:train_end]
|
||||||
|
X_te = X[train_end:test_end]
|
||||||
|
|
||||||
|
if len(np.unique(y_tr)) < 2:
|
||||||
|
start += STEP_SIZE
|
||||||
|
continue
|
||||||
|
|
||||||
|
scaler = StandardScaler()
|
||||||
|
X_tr_s = scaler.fit_transform(X_tr)
|
||||||
|
X_te_s = scaler.transform(X_te)
|
||||||
|
|
||||||
|
model = GradientBoostingClassifier(
|
||||||
|
n_estimators=150, max_depth=4, min_samples_leaf=10,
|
||||||
|
learning_rate=0.05, subsample=0.8, random_state=42,
|
||||||
|
)
|
||||||
|
model.fit(X_tr_s, y_tr)
|
||||||
|
|
||||||
|
up_idx = list(model.classes_).index(1) if 1 in model.classes_ else -1
|
||||||
|
if up_idx < 0:
|
||||||
|
start += STEP_SIZE
|
||||||
|
continue
|
||||||
|
|
||||||
|
for j in range(len(X_te)):
|
||||||
|
proba = model.predict_proba(X_te_s[j:j+1])[0]
|
||||||
|
p_up = proba[up_idx]
|
||||||
|
|
||||||
|
ev = ev_all[train_end + j]
|
||||||
|
i = ev["idx"]
|
||||||
|
actual_ret = (close[i + brk_bars - 1] - close[i - 1]) / close[i - 1]
|
||||||
|
|
||||||
|
direction = None
|
||||||
|
if p_up >= ml_thr:
|
||||||
|
direction = 1
|
||||||
|
elif p_up <= (1 - ml_thr):
|
||||||
|
direction = -1
|
||||||
|
if direction is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
is_correct = (direction == 1 and actual_ret > 0) or (direction == -1 and actual_ret < 0)
|
||||||
|
trade_ret = actual_ret * direction
|
||||||
|
net = trade_ret * leverage - FEE_ML * 2 * leverage
|
||||||
|
capital += capital * pos_pct * net
|
||||||
|
capital = max(capital, 10)
|
||||||
|
if capital > peak: peak = capital
|
||||||
|
dd = (peak - capital) / peak
|
||||||
|
max_dd = max(max_dd, dd)
|
||||||
|
total_bars += brk_bars
|
||||||
|
|
||||||
|
all_t += 1
|
||||||
|
if is_correct: all_w += 1
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnls": []}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if is_correct: yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnls"].append(net * INITIAL)
|
||||||
|
|
||||||
|
start += STEP_SIZE
|
||||||
|
|
||||||
|
if all_t == 0:
|
||||||
|
return None
|
||||||
|
return _build_result(yearly, capital, max_dd, all_t, all_w,
|
||||||
|
total_bars / n * 100, brk_bars * TF_MINUTES.get(tf, 60) / 60)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
# ESECUZIONE
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
print("Calcolo in corso...\n")
|
||||||
|
|
||||||
|
strategies = []
|
||||||
|
|
||||||
|
def add(name, desc, cat, result):
|
||||||
|
if result and result["trades"] >= 20:
|
||||||
|
strategies.append({"name": name, "desc": desc, "cat": cat, **result})
|
||||||
|
|
||||||
|
# ── S1: Squeeze puro ────────────────────────────────────────────
|
||||||
|
add("S1 Squeeze BTC 15m", "Squeeze breakout puro, BBw=14, hold 3×15m, leva 3x",
|
||||||
|
"S1", run_s1_squeeze("BTC", "15m"))
|
||||||
|
add("S1 Squeeze ETH 15m", "Squeeze breakout puro, BBw=14, hold 3×15m, leva 3x",
|
||||||
|
"S1", run_s1_squeeze("ETH", "15m"))
|
||||||
|
add("S1 Squeeze BTC 1h", "Squeeze breakout puro, BBw=14, hold 3×1h, leva 3x",
|
||||||
|
"S1", run_s1_squeeze("BTC", "1h"))
|
||||||
|
add("S1 Squeeze ETH 1h", "Squeeze breakout puro, BBw=14, hold 3×1h, leva 3x",
|
||||||
|
"S1", run_s1_squeeze("ETH", "1h"))
|
||||||
|
add("S1 AF+Vol BTC 15m", "Squeeze + antifakeout + volume confirm >1.3× media",
|
||||||
|
"S1", run_s1_antifake_vol("BTC", "15m"))
|
||||||
|
add("S1 AF+Vol ETH 15m", "Squeeze + antifakeout + volume confirm >1.3× media",
|
||||||
|
"S1", run_s1_antifake_vol("ETH", "15m"))
|
||||||
|
add("S1 AF+Vol BTC 1h", "Squeeze + antifakeout + volume confirm >1.3× media",
|
||||||
|
"S1", run_s1_antifake_vol("BTC", "1h"))
|
||||||
|
add("S1 AF+Vol ETH 1h", "Squeeze + antifakeout + volume confirm >1.3× media",
|
||||||
|
"S1", run_s1_antifake_vol("ETH", "1h"))
|
||||||
|
|
||||||
|
# ── Script 13: Squeeze + ML (GBM walk-forward) ─────────────────
|
||||||
|
print(" Training ML models...")
|
||||||
|
add("S13 ETH 15m bb14 ml70", "Squeeze+GBM walk-forward, BBw=14 sq=0.8 ml≥0.70, 3x leva 15% pos",
|
||||||
|
"S13", run_s13_hybrid("ETH", "15m", 14, 0.8, 3, 3, 0.15, 0.70))
|
||||||
|
add("S13 ETH 15m bb14 ml65", "Squeeze+GBM walk-forward, BBw=14 sq=0.8 ml≥0.65, 3x leva 15% pos",
|
||||||
|
"S13", run_s13_hybrid("ETH", "15m", 14, 0.8, 3, 3, 0.15, 0.65))
|
||||||
|
add("S13 ETH 15m bb20 ml70", "Squeeze+GBM walk-forward, BBw=20 sq=0.9 ml≥0.70, 3x leva 15% pos",
|
||||||
|
"S13", run_s13_hybrid("ETH", "15m", 20, 0.9, 3, 3, 0.15, 0.70))
|
||||||
|
add("S13 BTC 15m bb14 ml70", "Squeeze+GBM walk-forward, BBw=14 sq=0.9 ml≥0.70, 3x leva 15% pos",
|
||||||
|
"S13", run_s13_hybrid("BTC", "15m", 14, 0.9, 3, 3, 0.15, 0.70))
|
||||||
|
add("S13 BTC 15m bb14 ml65", "Squeeze+GBM walk-forward, BBw=14 sq=0.9 ml≥0.65, 3x leva 15% pos",
|
||||||
|
"S13", run_s13_hybrid("BTC", "15m", 14, 0.9, 3, 3, 0.15, 0.65))
|
||||||
|
add("S13 BTC 1h bb14 ml70", "Squeeze+GBM walk-forward, BBw=14 sq=0.8 ml≥0.70, 3x leva 20% pos",
|
||||||
|
"S13", run_s13_hybrid("BTC", "1h", 14, 0.8, 3, 3, 0.20, 0.70))
|
||||||
|
add("S13 BTC 1h bb14 ml65", "Squeeze+GBM walk-forward, BBw=14 sq=0.8 ml≥0.65, 3x leva 20% pos",
|
||||||
|
"S13", run_s13_hybrid("BTC", "1h", 14, 0.8, 3, 3, 0.20, 0.65))
|
||||||
|
add("S13 ETH 1h bb14 ml70", "Squeeze+GBM walk-forward, BBw=14 sq=0.8 ml≥0.70, 3x leva 20% pos",
|
||||||
|
"S13", run_s13_hybrid("ETH", "1h", 14, 0.8, 3, 3, 0.20, 0.70))
|
||||||
|
|
||||||
|
strategies.sort(key=lambda x: x["acc"], reverse=True)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
# TABELLA 1: Classifica
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
W = 150
|
||||||
|
print("=" * W)
|
||||||
|
print(" S1 (SQUEEZE PURO) vs S13 (SQUEEZE + GBM) — CLASSIFICA FINALE")
|
||||||
|
print(f" Fee: 0.2% RT. Dati OHLCV reali 2018-2026. Position 15%. Leva 3x.")
|
||||||
|
print("=" * W)
|
||||||
|
hdr = (f" {'#':>2s} {'Cat':>3s} {'Nome':<26s} {'Trades':>6s} {'Acc':>6s} "
|
||||||
|
f"{'PnL€':>9s} {'DD%':>6s} {'€/day':>7s} {'Sharpe':>7s} "
|
||||||
|
f"{'Mkt%':>5s} {'Dur':>6s} {'Worst':>12s} {'Anni':>4s}")
|
||||||
|
print(hdr)
|
||||||
|
print(f" {'─'*(W-4)}")
|
||||||
|
|
||||||
|
for idx, s in enumerate(strategies, 1):
|
||||||
|
worst = f"{s['worst_year']}({s['worst_acc']:.0f}%)"
|
||||||
|
dur_str = f"{s['avg_dur_h']:.0f}h" if s['avg_dur_h'] >= 1 else f"{s['avg_dur_h']*60:.0f}m"
|
||||||
|
tag = " ★★" if s["acc"] >= 78 else " ★" if s["acc"] >= 76 else ""
|
||||||
|
print(f" {idx:>2d} {s['cat']:>3s} {s['name']:<26s} {s['trades']:>6d} {s['acc']:>5.1f}% "
|
||||||
|
f"€{s['pnl']:>+8.0f} {s['max_dd']:>5.1f}% {s['daily_pnl']:>+6.2f} {s['sharpe']:>7.2f} "
|
||||||
|
f"{s['time_in_market_pct']:>4.1f}% {dur_str:>6s} {worst:>12s} {s['years_active']:>4d}{tag}")
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
# TABELLA 2: Descrizione
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
print(f"\n\n{'=' * W}")
|
||||||
|
print(" DESCRIZIONE")
|
||||||
|
print(f"{'=' * W}")
|
||||||
|
print(f" {'#':>2s} {'Nome':<26s} {'Descrizione'}")
|
||||||
|
print(f" {'─'*(W-4)}")
|
||||||
|
for idx, s in enumerate(strategies, 1):
|
||||||
|
print(f" {idx:>2d} {s['name']:<26s} {s['desc']}")
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
# TABELLA 3: Breakdown per anno
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
top_n = min(12, len(strategies))
|
||||||
|
top = strategies[:top_n]
|
||||||
|
all_years = sorted(set(y for s in top for y in s["year_details"]))
|
||||||
|
|
||||||
|
print(f"\n\n{'=' * W}")
|
||||||
|
print(f" BREAKDOWN PER ANNO — TOP {top_n} (accuracy% / trades)")
|
||||||
|
print(f"{'=' * W}")
|
||||||
|
|
||||||
|
header = f" {'Nome':<26s}"
|
||||||
|
for y in all_years:
|
||||||
|
header += f" {y:>10d}"
|
||||||
|
print(header)
|
||||||
|
print(f" {'─'*(W-4)}")
|
||||||
|
|
||||||
|
for s in top:
|
||||||
|
line = f" {s['name']:<26s}"
|
||||||
|
for y in all_years:
|
||||||
|
if y in s["year_details"]:
|
||||||
|
d = s["year_details"][y]
|
||||||
|
line += f" {d['acc']:>4.0f}%/{d['trades']:<4d}"
|
||||||
|
else:
|
||||||
|
line += f" {'—':>10s}"
|
||||||
|
print(line)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
# TABELLA 4: Robustezza
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
print(f"\n\n{'=' * W}")
|
||||||
|
print(f" ANALISI ROBUSTEZZA")
|
||||||
|
print(f"{'=' * W}")
|
||||||
|
print(f" {'#':>2s} {'Nome':<26s} {'MinAcc':>7s} {'MaxAcc':>7s} {'Spread':>7s} "
|
||||||
|
f"{'AnniOK':>7s} {'€/trade':>8s} {'Verdict':<12s}")
|
||||||
|
print(f" {'─'*90}")
|
||||||
|
|
||||||
|
for idx, s in enumerate(strategies, 1):
|
||||||
|
yd = s["year_details"]
|
||||||
|
valid = {y: d for y, d in yd.items() if d["trades"] >= 10}
|
||||||
|
accs = [d["acc"] for d in (valid if valid else yd).values()]
|
||||||
|
if not accs:
|
||||||
|
continue
|
||||||
|
min_a, max_a = min(accs), max(accs)
|
||||||
|
spread = max_a - min_a
|
||||||
|
years_ok = sum(1 for a in accs if a >= 70)
|
||||||
|
avg_pnl = s["pnl"] / s["trades"] if s["trades"] > 0 else 0
|
||||||
|
n_valid = len(valid if valid else yd)
|
||||||
|
|
||||||
|
if n_valid < 4:
|
||||||
|
verdict = "⚠ CORTO"
|
||||||
|
elif min_a < 60:
|
||||||
|
verdict = "⚠ FRAGILE"
|
||||||
|
elif min_a >= 72 and s["acc"] >= 77:
|
||||||
|
verdict = "✅ SOLIDO"
|
||||||
|
elif min_a >= 65 and s["acc"] >= 74:
|
||||||
|
verdict = "~ BUONO"
|
||||||
|
else:
|
||||||
|
verdict = "~ OK"
|
||||||
|
|
||||||
|
print(f" {idx:>2d} {s['name']:<26s} {min_a:>6.1f}% {max_a:>6.1f}% {spread:>6.1f}% "
|
||||||
|
f"{years_ok:>3d}/{n_valid:<3d} €{avg_pnl:>+7.1f} {verdict:<12s}")
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
# VERDETTO
|
||||||
|
# ═══════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
print(f"\n\n{'=' * W}")
|
||||||
|
print(f" VERDETTO FINALE")
|
||||||
|
print(f"{'=' * W}")
|
||||||
|
|
||||||
|
solidi = [s for s in strategies if s["trades"] >= 200 and s["years_active"] >= 5 and s["worst_acc"] >= 65]
|
||||||
|
solidi_s1 = [s for s in solidi if s["cat"] == "S1"]
|
||||||
|
solidi_ml = [s for s in solidi if s["cat"] == "S13"]
|
||||||
|
solidi_s1.sort(key=lambda x: x["acc"], reverse=True)
|
||||||
|
solidi_ml.sort(key=lambda x: x["daily_pnl"], reverse=True)
|
||||||
|
|
||||||
|
if solidi_s1:
|
||||||
|
b = solidi_s1[0]
|
||||||
|
print(f"\n MIGLIORE S1 (regole pure, facile da deployare):")
|
||||||
|
print(f" {b['name']} — {b['acc']:.1f}% acc, {b['trades']} trades, DD {b['max_dd']:.1f}%, €{b['daily_pnl']:+.2f}/day, Sharpe {b['sharpe']:.2f}")
|
||||||
|
|
||||||
|
if solidi_ml:
|
||||||
|
m = solidi_ml[0]
|
||||||
|
print(f"\n MIGLIORE S13 (squeeze+GBM, più complesso):")
|
||||||
|
print(f" {m['name']} — {m['acc']:.1f}% acc, {m['trades']} trades, DD {m['max_dd']:.1f}%, €{m['daily_pnl']:+.2f}/day, Sharpe {m['sharpe']:.2f}")
|
||||||
|
|
||||||
|
max_pnl = max(strategies, key=lambda x: x["pnl"])
|
||||||
|
print(f"\n MAX PnL: {max_pnl['name']} — €{max_pnl['pnl']:+,.0f}")
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
"""ML01 — Squeeze + GBM (Gradient Boosting Machine) Walk-Forward.
|
||||||
|
|
||||||
|
Strategia ibrida: squeeze breakout come pre-filtro (QUANDO tradare),
|
||||||
|
GradientBoosting su features strutturali come conferma (QUALE direzione).
|
||||||
|
|
||||||
|
Pipeline:
|
||||||
|
1. Rileva squeeze release (Bollinger esce da Keltner)
|
||||||
|
2. Estrai 44 features dalla finestra (structural multi-window + squeeze
|
||||||
|
metadata + price position + ATR + momentum breakout)
|
||||||
|
3. GBM walk-forward: train su 50% rolling, step 10%, predice direzione
|
||||||
|
4. Trade solo se ML ha confidenza ≥ ml_threshold
|
||||||
|
|
||||||
|
IN:
|
||||||
|
- OHLCV DataFrame
|
||||||
|
- Parametri: bb_window (14), sq_threshold (0.8), brk_bars (3),
|
||||||
|
ml_threshold (0.70), leverage (3), position_pct (0.15)
|
||||||
|
|
||||||
|
OUT:
|
||||||
|
- BacktestResult con metriche walk-forward (no data leakage)
|
||||||
|
- Solo periodo di test (seconda metà dati)
|
||||||
|
|
||||||
|
Risultati tipici:
|
||||||
|
ETH 15m bb14 ml=0.70: 76.9% acc, 1213 trades, DD 4.2%, €13.78/day
|
||||||
|
BTC 15m bb14 ml=0.70: 78.8% acc, 1964 trades, DD 7.0%, €5.51/day
|
||||||
|
BTC 1h bb14 ml=0.70: 77.3% acc, 617 trades, DD 6.7%, €3.85/day
|
||||||
|
|
||||||
|
Note:
|
||||||
|
- GBM = GradientBoostingClassifier di scikit-learn
|
||||||
|
- Walk-forward: nessun look-ahead, train sempre prima di test
|
||||||
|
- Il baseline squeeze puro ha accuracy più alta (~79.5%) ma DD peggiore
|
||||||
|
- Il valore del ML è filtrare breakout deboli → DD ridotto
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from sklearn.ensemble import GradientBoostingClassifier
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
|
||||||
|
from src.strategies.base import Strategy, Signal, BacktestResult, YearlyStats, TF_MINUTES
|
||||||
|
from src.strategies.indicators import keltner_ratio, detect_squeezes
|
||||||
|
from src.data.downloader import load_data
|
||||||
|
|
||||||
|
|
||||||
|
def _build_features(df: pd.DataFrame, i: int, squeeze_info: dict) -> np.ndarray | None:
|
||||||
|
"""44 features per il punto di squeeze release."""
|
||||||
|
if i < 100:
|
||||||
|
return None
|
||||||
|
o, h, l, c, v = (df["open"].values, df["high"].values, df["low"].values,
|
||||||
|
df["close"].values, df["volume"].values)
|
||||||
|
feats = []
|
||||||
|
for w in [12, 24, 48]:
|
||||||
|
wc, wo = c[i-w:i], o[i-w:i]
|
||||||
|
wh, wl, wv = h[i-w:i], l[i-w:i], v[i-w:i]
|
||||||
|
mn, mx = wl.min(), max(wh.max(), wc.max())
|
||||||
|
rng = mx - mn if mx - mn > 0 else 1e-10
|
||||||
|
total = np.where(wh - wl == 0, 1e-10, wh - wl)
|
||||||
|
body = np.abs(wc - wo) / total
|
||||||
|
direction = np.sign(wc - wo)
|
||||||
|
log_c = np.log(np.where(wc == 0, 1e-10, wc))
|
||||||
|
rets = np.diff(log_c)
|
||||||
|
v_mean = np.mean(wv)
|
||||||
|
feats.extend([
|
||||||
|
np.mean(rets) if len(rets) > 0 else 0,
|
||||||
|
np.std(rets) if len(rets) > 0 else 0,
|
||||||
|
np.sum(rets) if len(rets) > 0 else 0,
|
||||||
|
float(pd.Series(rets).skew()) if len(rets) > 2 else 0,
|
||||||
|
float(pd.Series(rets).kurtosis()) if len(rets) > 3 else 0,
|
||||||
|
np.mean(body), np.std(body),
|
||||||
|
np.mean(direction), np.mean(direction[-min(3, w):]),
|
||||||
|
(wc[-1] - mn) / rng,
|
||||||
|
wv[-1] / v_mean if v_mean > 0 else 1,
|
||||||
|
np.corrcoef(rets[:-1], rets[1:])[0, 1] if len(rets) > 1 and np.std(rets) > 0 else 0,
|
||||||
|
])
|
||||||
|
sq = squeeze_info
|
||||||
|
feats.extend([
|
||||||
|
sq["dur"], sq["dur"] / 24, sq["kcr_at_release"],
|
||||||
|
v[i-1] / sq.get("avg_vol", 1) if sq.get("avg_vol", 0) > 0 else 1,
|
||||||
|
np.mean(v[i:min(i+3, len(v))]) / sq.get("avg_vol", 1) if sq.get("avg_vol", 0) > 0 else 1,
|
||||||
|
])
|
||||||
|
h48, l48 = np.max(h[max(0, i-48):i]), np.min(l[max(0, i-48):i])
|
||||||
|
r48 = h48 - l48
|
||||||
|
feats.append((c[i-1] - l48) / r48 if r48 > 0 else 0.5)
|
||||||
|
tr = np.maximum(h[i-14:i] - l[i-14:i],
|
||||||
|
np.maximum(np.abs(h[i-14:i] - np.roll(c[i-14:i], 1)),
|
||||||
|
np.abs(l[i-14:i] - np.roll(c[i-14:i], 1))))
|
||||||
|
feats.append(np.mean(tr[1:]) / c[i-1] if c[i-1] > 0 else 0)
|
||||||
|
feats.append((c[i] - c[i-1]) / c[i-1] if c[i-1] > 0 else 0)
|
||||||
|
return np.nan_to_num(np.array(feats), nan=0, posinf=1e6, neginf=-1e6)
|
||||||
|
|
||||||
|
|
||||||
|
class SqueezeGBM(Strategy):
|
||||||
|
name = "ML01_squeeze_gbm"
|
||||||
|
description = "Squeeze + GBM walk-forward — ML filtra breakout deboli"
|
||||||
|
default_assets = ["BTC", "ETH"]
|
||||||
|
default_timeframes = ["15m", "1h"]
|
||||||
|
fee_ml = 0.001
|
||||||
|
|
||||||
|
def generate_signals(self, df, ts, **params):
|
||||||
|
raise NotImplementedError("ML01 usa backtest custom con walk-forward")
|
||||||
|
|
||||||
|
def backtest(self, asset: str, tf: str, hold: int = 3, **params) -> BacktestResult | None:
|
||||||
|
bb_w = params.get("bb_window", 14)
|
||||||
|
sq_thr = params.get("sq_threshold", 0.8 if tf == "1h" else 0.9)
|
||||||
|
brk = params.get("brk_bars", hold)
|
||||||
|
ml_thr = params.get("ml_threshold", 0.70)
|
||||||
|
lev = params.get("leverage", self.leverage)
|
||||||
|
pos = params.get("position_pct", self.position_size)
|
||||||
|
|
||||||
|
df = load_data(asset, tf)
|
||||||
|
close = df["close"].values
|
||||||
|
high = df["high"].values
|
||||||
|
low = df["low"].values
|
||||||
|
volume = df["volume"].values
|
||||||
|
n = len(df)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
|
||||||
|
kcr = keltner_ratio(close, high, low, bb_w)
|
||||||
|
raw_events = detect_squeezes(close, high, low, kcr, sq_thr)
|
||||||
|
|
||||||
|
# Aggiungi avg_vol a ogni evento
|
||||||
|
events = []
|
||||||
|
for ev in raw_events:
|
||||||
|
ev["avg_vol"] = float(np.mean(volume[ev["sq_start"]:ev["idx"]]))
|
||||||
|
events.append(ev)
|
||||||
|
|
||||||
|
X_all, y_all, ev_all = [], [], []
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
if i + brk >= n or i < 100:
|
||||||
|
continue
|
||||||
|
feats = _build_features(df, i, ev)
|
||||||
|
if feats is None:
|
||||||
|
continue
|
||||||
|
actual_ret = (close[i + brk - 1] - close[i - 1]) / close[i - 1]
|
||||||
|
X_all.append(feats)
|
||||||
|
y_all.append(1 if actual_ret > 0 else 0)
|
||||||
|
ev_all.append(ev)
|
||||||
|
|
||||||
|
if len(X_all) < 50:
|
||||||
|
return None
|
||||||
|
|
||||||
|
X, y = np.array(X_all), np.array(y_all)
|
||||||
|
TRAIN_SIZE = max(int(len(X) * 0.5), 50)
|
||||||
|
STEP_SIZE = max(int(len(X) * 0.1), 10)
|
||||||
|
|
||||||
|
yearly: dict[int, dict] = {}
|
||||||
|
capital = float(self.initial_capital)
|
||||||
|
peak = capital
|
||||||
|
max_dd = 0.0
|
||||||
|
total_bars = 0
|
||||||
|
all_t = all_w = 0
|
||||||
|
|
||||||
|
start = 0
|
||||||
|
while start + TRAIN_SIZE + STEP_SIZE <= len(X):
|
||||||
|
train_end = start + TRAIN_SIZE
|
||||||
|
test_end = min(train_end + STEP_SIZE, len(X))
|
||||||
|
X_tr, y_tr = X[start:train_end], y[start:train_end]
|
||||||
|
X_te = X[train_end:test_end]
|
||||||
|
|
||||||
|
if len(np.unique(y_tr)) < 2:
|
||||||
|
start += STEP_SIZE
|
||||||
|
continue
|
||||||
|
|
||||||
|
scaler = StandardScaler()
|
||||||
|
X_tr_s = scaler.fit_transform(X_tr)
|
||||||
|
X_te_s = scaler.transform(X_te)
|
||||||
|
|
||||||
|
model = GradientBoostingClassifier(
|
||||||
|
n_estimators=150, max_depth=4, min_samples_leaf=10,
|
||||||
|
learning_rate=0.05, subsample=0.8, random_state=42,
|
||||||
|
)
|
||||||
|
model.fit(X_tr_s, y_tr)
|
||||||
|
up_idx = list(model.classes_).index(1) if 1 in model.classes_ else -1
|
||||||
|
if up_idx < 0:
|
||||||
|
start += STEP_SIZE
|
||||||
|
continue
|
||||||
|
|
||||||
|
for j in range(len(X_te)):
|
||||||
|
proba = model.predict_proba(X_te_s[j:j+1])[0]
|
||||||
|
p_up = proba[up_idx]
|
||||||
|
ev = ev_all[train_end + j]
|
||||||
|
i = ev["idx"]
|
||||||
|
actual_ret = (close[i + brk - 1] - close[i - 1]) / close[i - 1]
|
||||||
|
|
||||||
|
if p_up >= ml_thr:
|
||||||
|
direction = 1
|
||||||
|
elif p_up <= (1 - ml_thr):
|
||||||
|
direction = -1
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
|
||||||
|
is_correct = (direction == 1 and actual_ret > 0) or (direction == -1 and actual_ret < 0)
|
||||||
|
trade_ret = actual_ret * direction
|
||||||
|
net = trade_ret * lev - self.fee_ml * 2 * lev
|
||||||
|
capital += capital * pos * net
|
||||||
|
capital = max(capital, 10)
|
||||||
|
if capital > peak:
|
||||||
|
peak = capital
|
||||||
|
dd = (peak - capital) / peak
|
||||||
|
max_dd = max(max_dd, dd)
|
||||||
|
total_bars += brk
|
||||||
|
|
||||||
|
all_t += 1
|
||||||
|
if is_correct:
|
||||||
|
all_w += 1
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnl": 0.0}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if is_correct:
|
||||||
|
yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnl"] += net * self.initial_capital
|
||||||
|
|
||||||
|
start += STEP_SIZE
|
||||||
|
|
||||||
|
if all_t == 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
yearly_stats = [
|
||||||
|
YearlyStats(year=y, trades=d["t"], wins=d["w"], pnl=d["pnl"])
|
||||||
|
for y, d in sorted(yearly.items())
|
||||||
|
]
|
||||||
|
|
||||||
|
return BacktestResult(
|
||||||
|
strategy_name=self.name,
|
||||||
|
asset=asset,
|
||||||
|
timeframe=tf,
|
||||||
|
params={"bb_w": bb_w, "sq_thr": sq_thr, "ml_thr": ml_thr,
|
||||||
|
"brk": brk, "lev": lev, "pos": pos},
|
||||||
|
trades=all_t,
|
||||||
|
wins=all_w,
|
||||||
|
pnl=sum(d["pnl"] for d in yearly.values()),
|
||||||
|
capital=capital,
|
||||||
|
initial_capital=self.initial_capital,
|
||||||
|
max_dd=max_dd * 100,
|
||||||
|
time_in_market_pct=total_bars / n * 100,
|
||||||
|
avg_trade_duration_h=brk * TF_MINUTES.get(tf, 60) / 60,
|
||||||
|
years_active=len(yearly),
|
||||||
|
yearly=yearly_stats,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
strategy = SqueezeGBM()
|
||||||
|
print("Training ML models...\n")
|
||||||
|
results = []
|
||||||
|
for asset in ["ETH", "BTC"]:
|
||||||
|
for tf in ["15m", "1h"]:
|
||||||
|
for ml_thr in [0.65, 0.70]:
|
||||||
|
r = strategy.backtest(asset, tf, ml_threshold=ml_thr)
|
||||||
|
if r and r.trades >= 20:
|
||||||
|
r.strategy_name = f"ML01 {asset} {tf} ml={ml_thr}"
|
||||||
|
results.append(r)
|
||||||
|
results.sort(key=lambda r: r.accuracy, reverse=True)
|
||||||
|
|
||||||
|
print(f"{'=' * 120}")
|
||||||
|
print(f" ML01 SQUEEZE+GBM — RISULTATI")
|
||||||
|
print(f"{'=' * 120}")
|
||||||
|
for r in results:
|
||||||
|
r.print_summary()
|
||||||
|
if results:
|
||||||
|
results[0].print_yearly()
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""SQ01 — Squeeze Breakout Base.
|
||||||
|
|
||||||
|
Strategia strutturale: rileva compressione di volatilità (Bollinger dentro
|
||||||
|
Keltner Channel) e segue la direzione del breakout al rilascio.
|
||||||
|
|
||||||
|
IN:
|
||||||
|
- OHLCV DataFrame (da load_data)
|
||||||
|
- Parametri: bb_window (14), sq_threshold (0.8), min_squeeze_dur (5)
|
||||||
|
|
||||||
|
OUT:
|
||||||
|
- Lista di Signal con direzione breakout (+1/-1)
|
||||||
|
- BacktestResult con equity, yearly breakdown, metriche
|
||||||
|
|
||||||
|
Risultati tipici:
|
||||||
|
BTC 15m: 76.7% acc, 4062 trades, DD 6.7%, €9.32/day
|
||||||
|
ETH 15m: 76.4% acc, 2948 trades, DD 6.2%, €10.31/day
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from src.strategies.base import Strategy, Signal
|
||||||
|
from src.strategies.indicators import keltner_ratio, detect_squeezes
|
||||||
|
|
||||||
|
|
||||||
|
class SqueezeBase(Strategy):
|
||||||
|
name = "SQ01_squeeze_base"
|
||||||
|
description = "Squeeze breakout puro — segui direzione al rilascio"
|
||||||
|
default_assets = ["BTC", "ETH"]
|
||||||
|
default_timeframes = ["15m", "1h"]
|
||||||
|
|
||||||
|
def generate_signals(self, df: pd.DataFrame, ts: pd.DatetimeIndex,
|
||||||
|
**params) -> list[Signal]:
|
||||||
|
c = df["close"].values
|
||||||
|
h = df["high"].values
|
||||||
|
l = df["low"].values
|
||||||
|
n = len(c)
|
||||||
|
|
||||||
|
bb_w = params.get("bb_window", 14)
|
||||||
|
sq_thr = params.get("sq_threshold", 0.8)
|
||||||
|
min_dur = params.get("min_dur", 5)
|
||||||
|
|
||||||
|
kcr = keltner_ratio(c, h, l, bb_w)
|
||||||
|
events = detect_squeezes(c, h, l, kcr, sq_thr, min_dur)
|
||||||
|
|
||||||
|
signals = []
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
if i < 1 or i >= n:
|
||||||
|
continue
|
||||||
|
first_ret = (c[i] - c[i - 1]) / c[i - 1] if c[i - 1] > 0 else 0
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
signals.append(Signal(
|
||||||
|
idx=i,
|
||||||
|
direction=1 if first_ret > 0 else -1,
|
||||||
|
entry_price=c[i - 1],
|
||||||
|
metadata={"dur": ev["dur"], "kcr": ev["kcr_at_release"]},
|
||||||
|
))
|
||||||
|
return signals
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
strategy = SqueezeBase()
|
||||||
|
strategy.report()
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""SQ02 — Squeeze Breakout + Anti-Fakeout + Volume Confirmation.
|
||||||
|
|
||||||
|
Migliora SQ01 con due filtri:
|
||||||
|
1. Anti-fakeout: scarta breakout dove la candela ritraccia >60% del range
|
||||||
|
2. Volume confirm: volume al breakout deve essere >1.3× la media durante squeeze
|
||||||
|
|
||||||
|
IN:
|
||||||
|
- OHLCV DataFrame
|
||||||
|
- Parametri: bb_window (14), sq_threshold (0.8), retrace_limit (0.6),
|
||||||
|
vol_multiplier (1.3)
|
||||||
|
|
||||||
|
OUT:
|
||||||
|
- Lista di Signal filtrati
|
||||||
|
- BacktestResult
|
||||||
|
|
||||||
|
Risultati tipici:
|
||||||
|
BTC 15m: 79.7% acc, 1250 trades, DD 6.5%, €5.23/day — SOLIDO 9/9 anni
|
||||||
|
ETH 15m: 78.6% acc, 942 trades, DD 3.4%, €4.33/day
|
||||||
|
BTC 1h: 78.0% acc, 473 trades, DD 3.5%, Sharpe 6.57
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from src.strategies.base import Strategy, Signal
|
||||||
|
from src.strategies.indicators import keltner_ratio, detect_squeezes
|
||||||
|
|
||||||
|
|
||||||
|
class SqueezeAntifakeVol(Strategy):
|
||||||
|
name = "SQ02_antifake_vol"
|
||||||
|
description = "Squeeze + antifakeout + volume confirmation"
|
||||||
|
default_assets = ["BTC", "ETH"]
|
||||||
|
default_timeframes = ["15m", "1h"]
|
||||||
|
|
||||||
|
def generate_signals(self, df: pd.DataFrame, ts: pd.DatetimeIndex,
|
||||||
|
**params) -> list[Signal]:
|
||||||
|
c = df["close"].values
|
||||||
|
h = df["high"].values
|
||||||
|
l = df["low"].values
|
||||||
|
v = df["volume"].values
|
||||||
|
n = len(c)
|
||||||
|
|
||||||
|
bb_w = params.get("bb_window", 14)
|
||||||
|
sq_thr = params.get("sq_threshold", 0.8)
|
||||||
|
retrace_limit = params.get("retrace_limit", 0.6)
|
||||||
|
vol_mult = params.get("vol_multiplier", 1.3)
|
||||||
|
|
||||||
|
kcr = keltner_ratio(c, h, l, bb_w)
|
||||||
|
events = detect_squeezes(c, h, l, kcr, sq_thr)
|
||||||
|
|
||||||
|
signals = []
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
if i < 1 or i >= n:
|
||||||
|
continue
|
||||||
|
first_ret = (c[i] - c[i - 1]) / c[i - 1] if c[i - 1] > 0 else 0
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
|
||||||
|
br = h[i] - l[i]
|
||||||
|
if br > 0:
|
||||||
|
if c[i] > c[i - 1]:
|
||||||
|
if (h[i] - c[i]) / br > retrace_limit:
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
if (c[i] - l[i]) / br > retrace_limit:
|
||||||
|
continue
|
||||||
|
|
||||||
|
avg_v = np.mean(v[ev["sq_start"]:i])
|
||||||
|
if avg_v > 0 and v[i] <= avg_v * vol_mult:
|
||||||
|
continue
|
||||||
|
|
||||||
|
signals.append(Signal(
|
||||||
|
idx=i,
|
||||||
|
direction=1 if first_ret > 0 else -1,
|
||||||
|
entry_price=c[i - 1],
|
||||||
|
metadata={"dur": ev["dur"], "vol_ratio": v[i] / avg_v if avg_v > 0 else 0},
|
||||||
|
))
|
||||||
|
return signals
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
strategy = SqueezeAntifakeVol()
|
||||||
|
strategy.report()
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
"""SQ03 — Squeeze con filtri selezionabili.
|
||||||
|
|
||||||
|
Ogni filtro è opzionale e attivabile via parametro. Di default attiva solo
|
||||||
|
antifake + long_squeeze (i due filtri con miglior rapporto accuracy/trade).
|
||||||
|
Esegue tutte le combinazioni utili e classifica.
|
||||||
|
|
||||||
|
Filtri disponibili:
|
||||||
|
- antifake: scarta breakout con retrace >60% (guadagna ~+1% acc)
|
||||||
|
- long_sq: solo squeeze durata ≥10 barre (+1% acc, dimezza trade)
|
||||||
|
- timing: solo ore 4-16 UTC (+0.5% acc)
|
||||||
|
- cross: asset secondario in squeeze nelle ultime 10 barre (+0.5%)
|
||||||
|
- vol: volume al breakout >1.3× media squeeze (+1% acc)
|
||||||
|
|
||||||
|
IN:
|
||||||
|
- OHLCV DataFrame (primario + secondario per cross-check)
|
||||||
|
- Parametri: filters (lista), bb_window, sq_threshold
|
||||||
|
|
||||||
|
OUT:
|
||||||
|
- BacktestResult per ogni preset di filtri
|
||||||
|
|
||||||
|
Risultati tipici (BTC 15m):
|
||||||
|
antifake+long: 77.3% acc, 2179 trades
|
||||||
|
antifake+vol: 79.7% acc, 1250 trades — SOLIDO
|
||||||
|
ALL_FILTERS: 79.2% acc, 696 trades (restrittivo)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from src.strategies.base import Strategy, Signal, BacktestResult, YearlyStats, TF_MINUTES
|
||||||
|
from src.strategies.indicators import keltner_ratio, detect_squeezes
|
||||||
|
from src.data.downloader import load_data
|
||||||
|
|
||||||
|
|
||||||
|
PRESETS = {
|
||||||
|
"antifake": ["antifake"],
|
||||||
|
"long_sq": ["long_sq"],
|
||||||
|
"antifake+long": ["antifake", "long_sq"],
|
||||||
|
"antifake+vol": ["antifake", "vol"],
|
||||||
|
"antifake+timing": ["antifake", "timing"],
|
||||||
|
"long+timing": ["long_sq", "timing"],
|
||||||
|
"antifake+long+time": ["antifake", "long_sq", "timing"],
|
||||||
|
"antifake+cross": ["antifake", "cross"],
|
||||||
|
"ALL_FILTERS": ["antifake", "long_sq", "timing", "cross"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class SqueezeFiltered(Strategy):
|
||||||
|
name = "SQ03_filtered"
|
||||||
|
description = "Squeeze + filtri selezionabili (antifake, long, timing, cross, vol)"
|
||||||
|
default_assets = ["BTC", "ETH"]
|
||||||
|
default_timeframes = ["15m", "1h"]
|
||||||
|
|
||||||
|
def generate_signals(self, df: pd.DataFrame, ts: pd.DatetimeIndex,
|
||||||
|
**params) -> list[Signal]:
|
||||||
|
c = df["close"].values
|
||||||
|
h = df["high"].values
|
||||||
|
l = df["low"].values
|
||||||
|
v = df["volume"].values
|
||||||
|
n = len(c)
|
||||||
|
|
||||||
|
bb_w = params.get("bb_window", 14)
|
||||||
|
sq_thr = params.get("sq_threshold", 0.8)
|
||||||
|
filters = params.get("filters", ["antifake", "long_sq"])
|
||||||
|
asset = params.get("asset", "BTC")
|
||||||
|
tf = params.get("tf", "15m")
|
||||||
|
|
||||||
|
kcr = keltner_ratio(c, h, l, bb_w)
|
||||||
|
events = detect_squeezes(c, h, l, kcr, sq_thr)
|
||||||
|
|
||||||
|
kcr2 = None
|
||||||
|
ts2 = None
|
||||||
|
if "cross" in filters:
|
||||||
|
secondary = "ETH" if asset == "BTC" else "BTC"
|
||||||
|
df2 = load_data(secondary, tf)
|
||||||
|
kcr2 = keltner_ratio(df2["close"].values, df2["high"].values,
|
||||||
|
df2["low"].values, bb_w)
|
||||||
|
ts2 = df2["timestamp"].values
|
||||||
|
|
||||||
|
signals = []
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
if i < 1 or i >= n:
|
||||||
|
continue
|
||||||
|
first_ret = (c[i] - c[i - 1]) / c[i - 1] if c[i - 1] > 0 else 0
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
|
||||||
|
skip = False
|
||||||
|
|
||||||
|
if "antifake" in filters:
|
||||||
|
br = h[i] - l[i]
|
||||||
|
if br > 0:
|
||||||
|
if c[i] > c[i - 1] and (h[i] - c[i]) / br > 0.6:
|
||||||
|
skip = True
|
||||||
|
elif c[i] <= c[i - 1] and (c[i] - l[i]) / br > 0.6:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
if not skip and "long_sq" in filters:
|
||||||
|
if ev["dur"] < 10:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
if not skip and "timing" in filters:
|
||||||
|
hour = ts.iloc[i].hour
|
||||||
|
if hour < 4 or hour > 16:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
if not skip and "vol" in filters:
|
||||||
|
avg_v = np.mean(v[ev["sq_start"]:i])
|
||||||
|
if avg_v > 0 and v[i] <= avg_v * 1.3:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
if not skip and "cross" in filters and kcr2 is not None and ts2 is not None:
|
||||||
|
i2 = np.searchsorted(ts2, ts.values[i].astype("int64") // 10**6)
|
||||||
|
i2 = min(i2, len(kcr2) - 1)
|
||||||
|
cross_ok = any(
|
||||||
|
not np.isnan(kcr2[j]) and kcr2[j] < 0.85
|
||||||
|
for j in range(max(0, i2 - 10), i2 + 1)
|
||||||
|
)
|
||||||
|
if not cross_ok:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
if skip:
|
||||||
|
continue
|
||||||
|
|
||||||
|
signals.append(Signal(
|
||||||
|
idx=i,
|
||||||
|
direction=1 if first_ret > 0 else -1,
|
||||||
|
entry_price=c[i - 1],
|
||||||
|
metadata={"dur": ev["dur"], "filters": filters},
|
||||||
|
))
|
||||||
|
return signals
|
||||||
|
|
||||||
|
def report_all_presets(self, assets=None, timeframes=None, hold=3):
|
||||||
|
"""Esegue tutti i preset di filtri × asset × tf."""
|
||||||
|
assets = assets or self.default_assets
|
||||||
|
timeframes = timeframes or self.default_timeframes
|
||||||
|
all_results = []
|
||||||
|
|
||||||
|
for preset_name, filter_list in PRESETS.items():
|
||||||
|
for asset in assets:
|
||||||
|
for tf in timeframes:
|
||||||
|
r = self.backtest(asset, tf, hold, filters=filter_list)
|
||||||
|
if r and r.trades >= 20:
|
||||||
|
r.strategy_name = f"SQ03 {preset_name}"
|
||||||
|
all_results.append(r)
|
||||||
|
|
||||||
|
all_results.sort(key=lambda r: r.accuracy, reverse=True)
|
||||||
|
|
||||||
|
print(f"\n{'=' * 120}")
|
||||||
|
print(f" SQ03 SQUEEZE FILTRATO — TUTTI I PRESET ({len(all_results)} config)")
|
||||||
|
print(f" Fee: {self.fee_rt*100:.1f}% RT | Leva: {self.leverage:.0f}x | Pos: {self.position_size*100:.0f}%")
|
||||||
|
print(f"{'=' * 120}")
|
||||||
|
print(f" {'Nome':<30s} {'A/T':>7s} {'Trades':>6s} {'Acc':>6s} "
|
||||||
|
f"{'PnL€':>10s} {'DD%':>6s} {'€/day':>7s} "
|
||||||
|
f"{'Mkt%':>5s} {'Dur':>5s} {'Worst':>12s} {'Anni':>4s}")
|
||||||
|
print(f" {'─' * 110}")
|
||||||
|
|
||||||
|
for r in all_results:
|
||||||
|
r.print_summary()
|
||||||
|
|
||||||
|
if all_results:
|
||||||
|
print(f"\n MIGLIORE: ", end="")
|
||||||
|
best = all_results[0]
|
||||||
|
best.print_yearly()
|
||||||
|
|
||||||
|
return all_results
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
strategy = SqueezeFiltered()
|
||||||
|
strategy.report_all_presets()
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
"""SQ04 — Ultimate Squeeze — combinazione incrementale di tutti i filtri.
|
||||||
|
|
||||||
|
Testa combinazioni di filtri (antifake, long_sq, timing, cross-asset,
|
||||||
|
correlation, volume, trend alignment, volatility regime) e classifica
|
||||||
|
per accuracy.
|
||||||
|
|
||||||
|
IN:
|
||||||
|
- OHLCV DataFrame (primario + secondario)
|
||||||
|
- Parametri: bb_window, sq_threshold, lista filtri da attivare
|
||||||
|
|
||||||
|
OUT:
|
||||||
|
- BacktestResult per ogni combinazione di filtri
|
||||||
|
- Classifica globale
|
||||||
|
|
||||||
|
Risultati tipici:
|
||||||
|
BTC 15m antifake+corr: 81.6% acc (ma concentrato 2018)
|
||||||
|
BTC 15m antifake+vol: 79.7% acc, 1250 trades — robusto
|
||||||
|
ETH 1h antifake+corr: 80.7% acc (solo 2018)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from src.strategies.base import Strategy, Signal
|
||||||
|
from src.strategies.indicators import (
|
||||||
|
keltner_ratio, detect_squeezes, ema, rv_annualized, rolling_correlation,
|
||||||
|
)
|
||||||
|
from src.data.downloader import load_data
|
||||||
|
|
||||||
|
|
||||||
|
class SqueezeUltimate(Strategy):
|
||||||
|
name = "SQ04_ultimate"
|
||||||
|
description = "Ultimate squeeze — tutti i filtri combinabili"
|
||||||
|
default_assets = ["BTC", "ETH"]
|
||||||
|
default_timeframes = ["15m", "1h"]
|
||||||
|
|
||||||
|
FILTER_PRESETS = {
|
||||||
|
"antifake+vol": ["antifake", "vol_confirm"],
|
||||||
|
"antifake+corr": ["antifake", "corr_high"],
|
||||||
|
"af+long+corr+trend": ["antifake", "long_sq", "corr_high", "trend_align"],
|
||||||
|
"ALL": ["antifake", "long_sq", "cross", "timing", "corr_high",
|
||||||
|
"vol_confirm", "trend_align", "low_rv"],
|
||||||
|
}
|
||||||
|
|
||||||
|
def generate_signals(self, df: pd.DataFrame, ts: pd.DatetimeIndex,
|
||||||
|
**params) -> list[Signal]:
|
||||||
|
c = df["close"].values
|
||||||
|
h = df["high"].values
|
||||||
|
l = df["low"].values
|
||||||
|
v = df["volume"].values
|
||||||
|
n = len(c)
|
||||||
|
|
||||||
|
asset = params.get("asset", "BTC")
|
||||||
|
tf = params.get("tf", "15m")
|
||||||
|
filters = params.get("filters", ["antifake", "vol_confirm"])
|
||||||
|
|
||||||
|
kcr = keltner_ratio(c, h, l, 14)
|
||||||
|
events = detect_squeezes(c, h, l, kcr)
|
||||||
|
|
||||||
|
secondary = "ETH" if asset == "BTC" else "BTC"
|
||||||
|
df2 = load_data(secondary, tf)
|
||||||
|
c2 = df2["close"].values
|
||||||
|
kcr2 = keltner_ratio(c2, df2["high"].values, df2["low"].values, 14)
|
||||||
|
ts2 = df2["timestamp"].values
|
||||||
|
|
||||||
|
ema_50 = ema(c, 50)
|
||||||
|
rv_48 = rv_annualized(c, 48)
|
||||||
|
corr = rolling_correlation(c, c2)
|
||||||
|
|
||||||
|
signals = []
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
if i < 1 or i >= n:
|
||||||
|
continue
|
||||||
|
first_ret = (c[i] - c[i - 1]) / c[i - 1] if c[i - 1] > 0 else 0
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
|
||||||
|
skip = False
|
||||||
|
for f in filters:
|
||||||
|
if f == "antifake":
|
||||||
|
br = h[i] - l[i]
|
||||||
|
if br > 0:
|
||||||
|
if c[i] > c[i-1] and (h[i] - c[i]) / br > 0.6:
|
||||||
|
skip = True
|
||||||
|
elif c[i] <= c[i-1] and (c[i] - l[i]) / br > 0.6:
|
||||||
|
skip = True
|
||||||
|
elif f == "long_sq":
|
||||||
|
if ev["dur"] < 10:
|
||||||
|
skip = True
|
||||||
|
elif f == "timing":
|
||||||
|
if ts.iloc[i].hour < 4 or ts.iloc[i].hour > 16:
|
||||||
|
skip = True
|
||||||
|
elif f == "cross":
|
||||||
|
i2 = np.searchsorted(ts2, ts.values[i].astype("int64") // 10**6)
|
||||||
|
i2 = min(i2, len(kcr2) - 1)
|
||||||
|
if not any(not np.isnan(kcr2[j]) and kcr2[j] < 0.85
|
||||||
|
for j in range(max(0, i2 - 10), i2 + 1)):
|
||||||
|
skip = True
|
||||||
|
elif f == "corr_high":
|
||||||
|
if np.isnan(corr[i]) or abs(corr[i]) < 0.6:
|
||||||
|
skip = True
|
||||||
|
elif f == "vol_confirm":
|
||||||
|
avg_v = np.mean(v[ev["sq_start"]:i])
|
||||||
|
if avg_v > 0 and v[i] <= avg_v * 1.3:
|
||||||
|
skip = True
|
||||||
|
elif f == "trend_align":
|
||||||
|
if not np.isnan(ema_50[i]):
|
||||||
|
if first_ret > 0 and c[i] < ema_50[i]:
|
||||||
|
skip = True
|
||||||
|
elif first_ret < 0 and c[i] > ema_50[i]:
|
||||||
|
skip = True
|
||||||
|
elif f == "low_rv":
|
||||||
|
if not np.isnan(rv_48[i]) and rv_48[i] >= 1.5:
|
||||||
|
skip = True
|
||||||
|
if skip:
|
||||||
|
break
|
||||||
|
|
||||||
|
if skip:
|
||||||
|
continue
|
||||||
|
|
||||||
|
signals.append(Signal(
|
||||||
|
idx=i,
|
||||||
|
direction=1 if first_ret > 0 else -1,
|
||||||
|
entry_price=c[i - 1],
|
||||||
|
metadata={"dur": ev["dur"], "filters": filters},
|
||||||
|
))
|
||||||
|
return signals
|
||||||
|
|
||||||
|
def backtest(self, asset: str, tf: str, hold: int = 3, **params):
|
||||||
|
params.setdefault("asset", asset)
|
||||||
|
params.setdefault("tf", tf)
|
||||||
|
df = load_data(asset, tf)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
signals = self.generate_signals(df, ts, **params)
|
||||||
|
# Usa il backtest della base ma passando i segnali già generati
|
||||||
|
from src.strategies.base import BacktestResult, YearlyStats, TF_MINUTES
|
||||||
|
c = df["close"].values
|
||||||
|
n = len(c)
|
||||||
|
yearly: dict[int, dict] = {}
|
||||||
|
capital = float(self.initial_capital)
|
||||||
|
peak = capital
|
||||||
|
max_dd = 0.0
|
||||||
|
total_bars = 0
|
||||||
|
for sig in signals:
|
||||||
|
i = sig.idx
|
||||||
|
if i + hold >= n or i < 1:
|
||||||
|
continue
|
||||||
|
entry = sig.entry_price
|
||||||
|
exit_price = c[min(i + hold - 1, n - 1)]
|
||||||
|
actual = (exit_price - entry) / entry * sig.direction
|
||||||
|
net = actual * self.leverage - self.fee_rt * self.leverage
|
||||||
|
capital += capital * self.position_size * net
|
||||||
|
capital = max(capital, 10)
|
||||||
|
if capital > peak: peak = capital
|
||||||
|
dd = (peak - capital) / peak
|
||||||
|
max_dd = max(max_dd, dd)
|
||||||
|
total_bars += hold
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnl": 0.0}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if actual > 0: yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnl"] += net * self.initial_capital
|
||||||
|
all_t = sum(d["t"] for d in yearly.values())
|
||||||
|
all_w = sum(d["w"] for d in yearly.values())
|
||||||
|
if all_t == 0: return None
|
||||||
|
yearly_stats = [YearlyStats(y, d["t"], d["w"], d["pnl"]) for y, d in sorted(yearly.items())]
|
||||||
|
return BacktestResult(
|
||||||
|
strategy_name=self.name, asset=asset, timeframe=tf, params=params,
|
||||||
|
trades=all_t, wins=all_w, pnl=sum(d["pnl"] for d in yearly.values()),
|
||||||
|
capital=capital, initial_capital=self.initial_capital,
|
||||||
|
max_dd=max_dd * 100, time_in_market_pct=total_bars / n * 100,
|
||||||
|
avg_trade_duration_h=hold * TF_MINUTES.get(tf, 60) / 60,
|
||||||
|
years_active=len(yearly), yearly=yearly_stats,
|
||||||
|
)
|
||||||
|
|
||||||
|
def report_all_presets(self):
|
||||||
|
"""Esegue tutte le combinazioni preset × asset × tf."""
|
||||||
|
all_results = []
|
||||||
|
for preset_name, filter_list in self.FILTER_PRESETS.items():
|
||||||
|
for asset in self.default_assets:
|
||||||
|
for tf in self.default_timeframes:
|
||||||
|
r = self.backtest(asset, tf, filters=filter_list)
|
||||||
|
if r and r.trades >= 20:
|
||||||
|
r.strategy_name = f"SQ04 {preset_name}"
|
||||||
|
all_results.append(r)
|
||||||
|
|
||||||
|
all_results.sort(key=lambda r: r.accuracy, reverse=True)
|
||||||
|
|
||||||
|
print(f"\n{'=' * 120}")
|
||||||
|
print(f" SQ04 ULTIMATE — TUTTI I PRESET")
|
||||||
|
print(f"{'=' * 120}")
|
||||||
|
for r in all_results:
|
||||||
|
r.print_summary()
|
||||||
|
return all_results
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
strategy = SqueezeUltimate()
|
||||||
|
strategy.report_all_presets()
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
"""S3-01: Squeeze Migliorato — test per-anno, dati reali.
|
||||||
|
Miglioramenti rispetto al squeeze base:
|
||||||
|
1. Cross-asset: squeeze su BTC + ETH contemporaneo = segnale più forte
|
||||||
|
2. Timing orario: accuracy per fascia oraria
|
||||||
|
3. Squeeze duration weighted: squeeze lunghi → breakout più forti
|
||||||
|
4. Dual-timeframe: squeeze su 1h confermato da 15m
|
||||||
|
5. Anti-fakeout: skip se candela post-breakout ritraccia >50%
|
||||||
|
6. Dynamic exit: trailing stop basato su ATR
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from src.data.downloader import load_data
|
||||||
|
|
||||||
|
FEE_RT = 0.002
|
||||||
|
INITIAL = 1000
|
||||||
|
LEVERAGE = 3
|
||||||
|
|
||||||
|
|
||||||
|
def keltner_ratio(close, high, low, window=14):
|
||||||
|
n = len(close)
|
||||||
|
r = np.full(n, np.nan)
|
||||||
|
for i in range(window, n):
|
||||||
|
wc, wh, wl = close[i-window:i], high[i-window:i], low[i-window:i]
|
||||||
|
ma = np.mean(wc)
|
||||||
|
bb_std = np.std(wc)
|
||||||
|
tr = np.maximum(wh-wl, np.maximum(np.abs(wh-np.roll(wc,1)), np.abs(wl-np.roll(wc,1))))
|
||||||
|
atr = np.mean(tr[1:])
|
||||||
|
kc = (ma+1.5*atr)-(ma-1.5*atr)
|
||||||
|
bb = (ma+2*bb_std)-(ma-2*bb_std)
|
||||||
|
if kc > 0:
|
||||||
|
r[i] = bb/kc
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def atr_calc(high, low, close, period=14):
|
||||||
|
tr = np.maximum(high-low, np.maximum(np.abs(high-np.roll(close,1)), np.abs(low-np.roll(close,1))))
|
||||||
|
tr[0] = high[0]-low[0]
|
||||||
|
r = np.full(len(close), np.nan)
|
||||||
|
r[period-1] = np.mean(tr[:period])
|
||||||
|
k = 2/(period+1)
|
||||||
|
for i in range(period, len(close)):
|
||||||
|
r[i] = tr[i]*k + r[i-1]*(1-k)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def detect_squeezes(close, high, low, volume, kcr, sq_thr=0.8, min_dur=5):
|
||||||
|
"""Ritorna lista di squeeze events con metadata."""
|
||||||
|
events = []
|
||||||
|
in_sq = False
|
||||||
|
sq_start = 0
|
||||||
|
n = len(close)
|
||||||
|
|
||||||
|
for i in range(1, n):
|
||||||
|
if np.isnan(kcr[i]):
|
||||||
|
continue
|
||||||
|
is_sq = kcr[i] < sq_thr
|
||||||
|
if is_sq and not in_sq:
|
||||||
|
in_sq = True
|
||||||
|
sq_start = i
|
||||||
|
elif not is_sq and in_sq:
|
||||||
|
in_sq = False
|
||||||
|
dur = i - sq_start
|
||||||
|
if dur < min_dur:
|
||||||
|
continue
|
||||||
|
avg_vol = np.mean(volume[sq_start:i])
|
||||||
|
# Range durante squeeze
|
||||||
|
sq_range = (np.max(high[sq_start:i]) - np.min(low[sq_start:i])) / close[sq_start] if close[sq_start] > 0 else 0
|
||||||
|
events.append({
|
||||||
|
"release_idx": i,
|
||||||
|
"duration": dur,
|
||||||
|
"avg_vol": avg_vol,
|
||||||
|
"squeeze_range": sq_range,
|
||||||
|
"kcr_at_release": kcr[i],
|
||||||
|
})
|
||||||
|
return events
|
||||||
|
|
||||||
|
|
||||||
|
def run_improved_squeeze(primary_asset, tf="1h"):
|
||||||
|
# Carica asset primario
|
||||||
|
df = load_data(primary_asset, tf)
|
||||||
|
c, h, l, v = df["close"].values, df["high"].values, df["low"].values, df["volume"].values
|
||||||
|
n = len(df)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
ts_ms = df["timestamp"].values
|
||||||
|
|
||||||
|
kcr = keltner_ratio(c, h, l, 14)
|
||||||
|
atr_14 = atr_calc(h, l, c, 14)
|
||||||
|
events = detect_squeezes(c, h, l, v, kcr)
|
||||||
|
|
||||||
|
# Carica asset secondario per cross-check
|
||||||
|
secondary = "BTC" if primary_asset == "ETH" else "ETH"
|
||||||
|
df2 = load_data(secondary, tf)
|
||||||
|
c2, h2, l2 = df2["close"].values, df2["high"].values, df2["low"].values
|
||||||
|
ts2_ms = df2["timestamp"].values
|
||||||
|
kcr2 = keltner_ratio(c2, h2, l2, 14)
|
||||||
|
|
||||||
|
# Mappa ts2 → indici per allineare
|
||||||
|
def find_idx2(ts_val):
|
||||||
|
idx = np.searchsorted(ts2_ms, ts_val)
|
||||||
|
return min(idx, len(c2)-1)
|
||||||
|
|
||||||
|
# Carica 15m per dual-TF
|
||||||
|
if tf == "1h":
|
||||||
|
df_15m = load_data(primary_asset, "15m")
|
||||||
|
c15 = df_15m["close"].values
|
||||||
|
h15 = df_15m["high"].values
|
||||||
|
l15 = df_15m["low"].values
|
||||||
|
ts15 = df_15m["timestamp"].values
|
||||||
|
kcr_15m = keltner_ratio(c15, h15, l15, 14)
|
||||||
|
else:
|
||||||
|
kcr_15m = None
|
||||||
|
ts15 = None
|
||||||
|
|
||||||
|
# ================================================================
|
||||||
|
# CONFIGURAZIONI
|
||||||
|
# ================================================================
|
||||||
|
configs = [
|
||||||
|
# (name, use_cross, use_timing, use_duration, use_dual_tf, use_antifake, use_trailing, hold, stop_atr)
|
||||||
|
("BASE", False, False, False, False, False, False, 3, 0),
|
||||||
|
("cross_asset", True, False, False, False, False, False, 3, 0),
|
||||||
|
("timing_filter", False, True, False, False, False, False, 3, 0),
|
||||||
|
("long_squeeze", False, False, True, False, False, False, 3, 0),
|
||||||
|
("dual_tf", False, False, False, True, False, False, 3, 0),
|
||||||
|
("anti_fakeout", False, False, False, False, True, False, 3, 0),
|
||||||
|
("trailing_stop", False, False, False, False, False, True, 6, 1.5),
|
||||||
|
("cross+timing", True, True, False, False, False, False, 3, 0),
|
||||||
|
("cross+long+timing", True, True, True, False, False, False, 3, 0),
|
||||||
|
("cross+dual_tf", True, False, False, True, False, False, 3, 0),
|
||||||
|
("ALL_FILTERS", True, True, True, True, True, False, 3, 0),
|
||||||
|
("ALL+trailing", True, True, True, True, True, True, 6, 1.5),
|
||||||
|
("cross+antifake", True, False, False, False, True, False, 3, 0),
|
||||||
|
("timing+antifake", False, True, False, False, True, False, 3, 0),
|
||||||
|
("cross+timing+antifk", True, True, False, False, True, False, 3, 0),
|
||||||
|
("cross+timing+trail", True, True, False, False, False, True, 6, 1.5),
|
||||||
|
]
|
||||||
|
|
||||||
|
print(f"\n{'#'*75}")
|
||||||
|
print(f" {primary_asset} {tf} — SQUEEZE MIGLIORATO")
|
||||||
|
print(f"{'#'*75}")
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
for name, f_cross, f_timing, f_dur, f_dual, f_antifake, f_trail, hold, stop_atr_m in configs:
|
||||||
|
yearly = {}
|
||||||
|
capital = float(INITIAL)
|
||||||
|
peak = capital
|
||||||
|
max_dd = 0
|
||||||
|
|
||||||
|
for ev in events:
|
||||||
|
i = ev["release_idx"]
|
||||||
|
if i + hold + 2 >= n:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# --- FILTRI ---
|
||||||
|
skip = False
|
||||||
|
|
||||||
|
# Cross-asset: secondary deve anche essere in squeeze recente o breakout
|
||||||
|
if f_cross:
|
||||||
|
i2 = find_idx2(ts_ms[i])
|
||||||
|
if i2 >= 5:
|
||||||
|
sec_in_squeeze = any(not np.isnan(kcr2[j]) and kcr2[j] < 0.85 for j in range(max(0,i2-10), i2+1))
|
||||||
|
if not sec_in_squeeze:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
# Timing: solo certe ore (testato: 6-14 UTC migliori)
|
||||||
|
if f_timing:
|
||||||
|
hour = ts.iloc[i].hour
|
||||||
|
if hour < 4 or hour > 16:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
# Duration: solo squeeze > 10 barre
|
||||||
|
if f_dur:
|
||||||
|
if ev["duration"] < 10:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
# Dual-TF: squeeze anche su 15m
|
||||||
|
if f_dual and kcr_15m is not None and ts15 is not None:
|
||||||
|
i15 = np.searchsorted(ts15, ts_ms[i])
|
||||||
|
if i15 >= 5:
|
||||||
|
sq_15m = any(not np.isnan(kcr_15m[j]) and kcr_15m[j] < 0.85 for j in range(max(0,i15-20), i15+1))
|
||||||
|
if not sq_15m:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
# Anti-fakeout: prima candela post-breakout non deve ritracciare >50%
|
||||||
|
if f_antifake and i + 1 < n:
|
||||||
|
breakout_bar_range = h[i] - l[i]
|
||||||
|
if breakout_bar_range > 0:
|
||||||
|
if c[i] > c[i-1]: # breakout up
|
||||||
|
retrace = (h[i] - c[i]) / breakout_bar_range
|
||||||
|
else: # breakout down
|
||||||
|
retrace = (c[i] - l[i]) / breakout_bar_range
|
||||||
|
if retrace > 0.6:
|
||||||
|
skip = True
|
||||||
|
|
||||||
|
if skip:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# --- DIREZIONE ---
|
||||||
|
first_ret = (c[i] - c[i-1]) / c[i-1]
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
direction = 1 if first_ret > 0 else -1
|
||||||
|
|
||||||
|
# --- EXIT ---
|
||||||
|
entry = c[i-1]
|
||||||
|
if f_trail and not np.isnan(atr_14[i]):
|
||||||
|
# Trailing stop
|
||||||
|
trail_dist = atr_14[i] * stop_atr_m
|
||||||
|
best_price = entry
|
||||||
|
exit_price = c[min(i+hold, n-1)]
|
||||||
|
for j in range(i, min(i+hold+1, n)):
|
||||||
|
if direction == 1:
|
||||||
|
best_price = max(best_price, h[j])
|
||||||
|
if l[j] <= best_price - trail_dist:
|
||||||
|
exit_price = best_price - trail_dist
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
best_price = min(best_price, l[j])
|
||||||
|
if h[j] >= best_price + trail_dist:
|
||||||
|
exit_price = best_price + trail_dist
|
||||||
|
break
|
||||||
|
exit_price = c[j]
|
||||||
|
else:
|
||||||
|
exit_price = c[min(i+hold-1, n-1)]
|
||||||
|
|
||||||
|
actual = (exit_price - entry) / entry * direction
|
||||||
|
net = actual * LEVERAGE - FEE_RT * LEVERAGE
|
||||||
|
|
||||||
|
capital += capital * 0.15 * net
|
||||||
|
capital = max(capital, 10)
|
||||||
|
if capital > peak: peak = capital
|
||||||
|
dd = (peak - capital) / peak
|
||||||
|
max_dd = max(max_dd, dd)
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"wins": 0, "total": 0, "pnls": []}
|
||||||
|
yearly[year]["total"] += 1
|
||||||
|
if actual > 0:
|
||||||
|
yearly[year]["wins"] += 1
|
||||||
|
yearly[year]["pnls"].append(net * INITIAL)
|
||||||
|
|
||||||
|
all_t = sum(d["total"] for d in yearly.values())
|
||||||
|
all_w = sum(d["wins"] for d in yearly.values())
|
||||||
|
if all_t < 30:
|
||||||
|
continue
|
||||||
|
|
||||||
|
acc = all_w / all_t * 100
|
||||||
|
all_pnls = [p for d in yearly.values() for p in d["pnls"]]
|
||||||
|
tot_pnl = sum(all_pnls)
|
||||||
|
|
||||||
|
# Worst year
|
||||||
|
worst_y_acc = 100
|
||||||
|
worst_y = ""
|
||||||
|
for y, d in yearly.items():
|
||||||
|
ya = d["wins"]/d["total"]*100 if d["total"] > 0 else 0
|
||||||
|
if ya < worst_y_acc:
|
||||||
|
worst_y_acc = ya
|
||||||
|
worst_y = str(y)
|
||||||
|
|
||||||
|
results.append({
|
||||||
|
"name": name, "trades": all_t, "acc": acc, "pnl": tot_pnl,
|
||||||
|
"max_dd": max_dd*100, "capital": capital,
|
||||||
|
"worst": f"{worst_y}({worst_y_acc:.0f}%)",
|
||||||
|
"yearly": yearly,
|
||||||
|
})
|
||||||
|
|
||||||
|
# Sort by accuracy
|
||||||
|
results.sort(key=lambda x: x["acc"], reverse=True)
|
||||||
|
|
||||||
|
print(f"\n {'Name':.<26s} {'Trades':>7s} {'Acc':>6s} {'PnL€':>9s} {'DD%':>6s} {'Capital':>10s} {'Worst':>12s}")
|
||||||
|
print(f" {'-'*80}")
|
||||||
|
for r in results:
|
||||||
|
tag = "✅✅" if r["acc"] >= 80 else "✅" if r["acc"] >= 76 else ""
|
||||||
|
print(f" {r['name']:.<26s} {r['trades']:>7d} {r['acc']:>5.1f}% €{r['pnl']:>+8.0f} {r['max_dd']:>5.1f}% €{r['capital']:>9,.0f} {r['worst']:>12s} {tag}")
|
||||||
|
|
||||||
|
# Dettaglio per anno del migliore
|
||||||
|
if results:
|
||||||
|
best = results[0]
|
||||||
|
print(f"\n MIGLIORE: {best['name']} → {best['acc']:.1f}% acc")
|
||||||
|
print(f" {'Anno':>6s} {'Trades':>7s} {'Acc':>6s} {'PnL€':>9s}")
|
||||||
|
for y in sorted(best["yearly"]):
|
||||||
|
d = best["yearly"][y]
|
||||||
|
ya = d["wins"]/d["total"]*100 if d["total"] > 0 else 0
|
||||||
|
yp = sum(d["pnls"])
|
||||||
|
tag = " ← CRASH" if y in [2020,2021,2022] else ""
|
||||||
|
print(f" {y:>6d} {d['total']:>7d} {ya:>5.1f}% €{yp:>+8.0f}{tag}")
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
# Run su entrambi gli asset e timeframe
|
||||||
|
all_results = {}
|
||||||
|
for asset in ["ETH", "BTC"]:
|
||||||
|
for tf in ["1h", "15m"]:
|
||||||
|
key = f"{asset}_{tf}"
|
||||||
|
all_results[key] = run_improved_squeeze(asset, tf)
|
||||||
|
|
||||||
|
# Classifica globale
|
||||||
|
print(f"\n\n{'='*75}")
|
||||||
|
print(f" CLASSIFICA GLOBALE — TOP 15")
|
||||||
|
print(f"{'='*75}")
|
||||||
|
|
||||||
|
global_list = []
|
||||||
|
for key, results in all_results.items():
|
||||||
|
for r in results:
|
||||||
|
global_list.append({**r, "asset_tf": key})
|
||||||
|
|
||||||
|
global_list.sort(key=lambda x: x["acc"], reverse=True)
|
||||||
|
print(f"\n {'Asset_TF':.<12s} {'Name':.<26s} {'Trades':>6s} {'Acc':>6s} {'PnL€':>9s} {'DD%':>5s} {'Worst':>12s}")
|
||||||
|
for r in global_list[:15]:
|
||||||
|
tag = "✅✅" if r["acc"] >= 80 else "✅" if r["acc"] >= 76 else ""
|
||||||
|
print(f" {r['asset_tf']:.<12s} {r['name']:.<26s} {r['trades']:>6d} {r['acc']:>5.1f}% €{r['pnl']:>+8.0f} {r['max_dd']:>4.1f}% {r['worst']:>12s} {tag}")
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
"""S3-02: Lead-lag multi-asset squeeze.
|
||||||
|
Quando BTC fa squeeze breakout, ETH/SOL spesso seguono.
|
||||||
|
Usa il breakout di BTC per anticipare entrata su ETH (e viceversa).
|
||||||
|
Testa anche correlazione inter-asset per conferma segnale.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from src.data.downloader import load_data
|
||||||
|
|
||||||
|
FEE_RT = 0.002
|
||||||
|
INITIAL = 1000
|
||||||
|
LEVERAGE = 3
|
||||||
|
|
||||||
|
|
||||||
|
def keltner_ratio(close, high, low, window=14):
|
||||||
|
n = len(close)
|
||||||
|
r = np.full(n, np.nan)
|
||||||
|
for i in range(window, n):
|
||||||
|
wc, wh, wl = close[i-window:i], high[i-window:i], low[i-window:i]
|
||||||
|
ma = np.mean(wc)
|
||||||
|
bb_std = np.std(wc)
|
||||||
|
tr = np.maximum(wh-wl, np.maximum(np.abs(wh-np.roll(wc,1)), np.abs(wl-np.roll(wc,1))))
|
||||||
|
atr = np.mean(tr[1:])
|
||||||
|
kc = (ma+1.5*atr)-(ma-1.5*atr)
|
||||||
|
bb = (ma+2*bb_std)-(ma-2*bb_std)
|
||||||
|
if kc > 0: r[i] = bb/kc
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def load_aligned(assets, tf):
|
||||||
|
"""Carica e allinea dati multi-asset per timestamp."""
|
||||||
|
dfs = {}
|
||||||
|
for asset in assets:
|
||||||
|
try:
|
||||||
|
if asset == "SOL":
|
||||||
|
df = pd.read_parquet(f"data/raw/sol_{tf}.parquet")
|
||||||
|
df["datetime"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
else:
|
||||||
|
df = load_data(asset, tf)
|
||||||
|
dfs[asset] = df
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if len(dfs) < 2:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Allinea per timestamp
|
||||||
|
common_ts = set(dfs[list(dfs.keys())[0]]["timestamp"].values)
|
||||||
|
for df in dfs.values():
|
||||||
|
common_ts &= set(df["timestamp"].values)
|
||||||
|
common_ts = sorted(common_ts)
|
||||||
|
|
||||||
|
aligned = {}
|
||||||
|
for asset, df in dfs.items():
|
||||||
|
mask = df["timestamp"].isin(common_ts)
|
||||||
|
aligned[asset] = df[mask].sort_values("timestamp").reset_index(drop=True)
|
||||||
|
|
||||||
|
return aligned
|
||||||
|
|
||||||
|
|
||||||
|
def detect_breakouts(close, high, low, volume, kcr, sq_thr=0.8, min_dur=5):
|
||||||
|
"""Detect squeeze breakout events."""
|
||||||
|
events = []
|
||||||
|
in_sq = False
|
||||||
|
sq_start = 0
|
||||||
|
for i in range(1, len(close)):
|
||||||
|
if np.isnan(kcr[i]):
|
||||||
|
continue
|
||||||
|
is_sq = kcr[i] < sq_thr
|
||||||
|
if is_sq and not in_sq:
|
||||||
|
in_sq = True
|
||||||
|
sq_start = i
|
||||||
|
elif not is_sq and in_sq:
|
||||||
|
in_sq = False
|
||||||
|
if i - sq_start < min_dur:
|
||||||
|
continue
|
||||||
|
first_ret = (close[i] - close[i-1]) / close[i-1] if close[i-1] > 0 else 0
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
events.append({
|
||||||
|
"idx": i,
|
||||||
|
"duration": i - sq_start,
|
||||||
|
"direction": 1 if first_ret > 0 else -1,
|
||||||
|
"first_ret": first_ret,
|
||||||
|
})
|
||||||
|
return events
|
||||||
|
|
||||||
|
|
||||||
|
print("=" * 75)
|
||||||
|
print(" S3-02: LEAD-LAG MULTI-ASSET SQUEEZE")
|
||||||
|
print("=" * 75)
|
||||||
|
|
||||||
|
for tf in ["1h", "15m"]:
|
||||||
|
aligned = load_aligned(["BTC", "ETH", "SOL"], tf)
|
||||||
|
if aligned is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
n = len(aligned["BTC"])
|
||||||
|
ts = pd.to_datetime(aligned["BTC"]["timestamp"], unit="ms", utc=True)
|
||||||
|
|
||||||
|
print(f"\n Timeframe: {tf}, Candles allineate: {n}")
|
||||||
|
|
||||||
|
# Calcola squeeze per ogni asset
|
||||||
|
asset_data = {}
|
||||||
|
for asset in aligned:
|
||||||
|
df = aligned[asset]
|
||||||
|
c, h, l, v = df["close"].values, df["high"].values, df["low"].values, df["volume"].values
|
||||||
|
kcr = keltner_ratio(c, h, l, 14)
|
||||||
|
events = detect_breakouts(c, h, l, v, kcr)
|
||||||
|
asset_data[asset] = {"close": c, "high": h, "low": l, "vol": v, "kcr": kcr, "events": events}
|
||||||
|
print(f" {asset}: {len(events)} squeeze breakouts")
|
||||||
|
|
||||||
|
# ================================================================
|
||||||
|
# STRATEGIA A: Leader-follower
|
||||||
|
# Quando BTC fa breakout, entra su ETH/SOL nella stessa direzione
|
||||||
|
# ================================================================
|
||||||
|
print(f"\n --- LEADER-FOLLOWER ({tf}) ---")
|
||||||
|
|
||||||
|
for leader, follower in [("BTC", "ETH"), ("BTC", "SOL"), ("ETH", "BTC"), ("ETH", "SOL")]:
|
||||||
|
if leader not in asset_data or follower not in asset_data:
|
||||||
|
continue
|
||||||
|
|
||||||
|
leader_events = asset_data[leader]["events"]
|
||||||
|
fc = asset_data[follower]["close"]
|
||||||
|
|
||||||
|
for hold in [3, 6]:
|
||||||
|
for delay in [0, 1, 2]:
|
||||||
|
yearly = {}
|
||||||
|
|
||||||
|
for ev in leader_events:
|
||||||
|
i = ev["idx"] + delay
|
||||||
|
if i + hold >= n:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Anti-fakeout su follower
|
||||||
|
entry = fc[i]
|
||||||
|
exit_price = fc[min(i + hold, n - 1)]
|
||||||
|
direction = ev["direction"]
|
||||||
|
actual = (exit_price - entry) / entry * direction
|
||||||
|
net = actual * LEVERAGE - FEE_RT * LEVERAGE
|
||||||
|
|
||||||
|
year = ts.iloc[min(i, n-1)].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnls": []}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if actual > 0:
|
||||||
|
yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnls"].append(net * INITIAL)
|
||||||
|
|
||||||
|
all_t = sum(d["t"] for d in yearly.values())
|
||||||
|
all_w = sum(d["w"] for d in yearly.values())
|
||||||
|
if all_t < 30:
|
||||||
|
continue
|
||||||
|
acc = all_w / all_t * 100
|
||||||
|
pnl = sum(p for d in yearly.values() for p in d["pnls"])
|
||||||
|
worst_y = min(yearly.items(), key=lambda x: x[1]["w"]/x[1]["t"] if x[1]["t"]>0 else 0)
|
||||||
|
worst_acc = worst_y[1]["w"]/worst_y[1]["t"]*100 if worst_y[1]["t"]>0 else 0
|
||||||
|
tag = "✅" if acc >= 76 else ""
|
||||||
|
print(f" {leader}→{follower} d={delay} h={hold}: trades={all_t:5d} acc={acc:.1f}% pnl=€{pnl:+.0f} worst={worst_y[0]}({worst_acc:.0f}%) {tag}")
|
||||||
|
|
||||||
|
# ================================================================
|
||||||
|
# STRATEGIA B: Consensus multi-asset
|
||||||
|
# Trade solo quando 2+ asset hanno squeeze breakout nello stesso momento
|
||||||
|
# ================================================================
|
||||||
|
print(f"\n --- CONSENSUS MULTI-ASSET ({tf}) ---")
|
||||||
|
|
||||||
|
# Build event map: timestamp → list of (asset, direction)
|
||||||
|
event_map = {}
|
||||||
|
for asset, data in asset_data.items():
|
||||||
|
for ev in data["events"]:
|
||||||
|
idx = ev["idx"]
|
||||||
|
if idx not in event_map:
|
||||||
|
event_map[idx] = []
|
||||||
|
event_map[idx].append((asset, ev["direction"]))
|
||||||
|
|
||||||
|
for target in ["BTC", "ETH", "SOL"]:
|
||||||
|
if target not in asset_data:
|
||||||
|
continue
|
||||||
|
tc = asset_data[target]["close"]
|
||||||
|
|
||||||
|
for min_consensus in [2, 3]:
|
||||||
|
for window_bars in [1, 3, 5]:
|
||||||
|
yearly = {}
|
||||||
|
daily_done = set()
|
||||||
|
|
||||||
|
for idx in sorted(event_map.keys()):
|
||||||
|
if idx + 6 >= n:
|
||||||
|
continue
|
||||||
|
|
||||||
|
day = ts.iloc[idx].strftime("%Y-%m-%d")
|
||||||
|
if day in daily_done:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Count consensus within window
|
||||||
|
nearby_events = []
|
||||||
|
for j in range(max(0, idx - window_bars), idx + window_bars + 1):
|
||||||
|
if j in event_map:
|
||||||
|
nearby_events.extend(event_map[j])
|
||||||
|
|
||||||
|
# Unique assets
|
||||||
|
unique_assets = set(a for a, d in nearby_events)
|
||||||
|
if len(unique_assets) < min_consensus:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Majority direction
|
||||||
|
dirs = [d for a, d in nearby_events]
|
||||||
|
majority = 1 if sum(dirs) > 0 else -1
|
||||||
|
|
||||||
|
entry = tc[idx]
|
||||||
|
exit_price = tc[min(idx + 3, n - 1)]
|
||||||
|
actual = (exit_price - entry) / entry * majority
|
||||||
|
net = actual * LEVERAGE - FEE_RT * LEVERAGE
|
||||||
|
|
||||||
|
year = ts.iloc[idx].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnls": []}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if actual > 0:
|
||||||
|
yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnls"].append(net * INITIAL)
|
||||||
|
daily_done.add(day)
|
||||||
|
|
||||||
|
all_t = sum(d["t"] for d in yearly.values())
|
||||||
|
all_w = sum(d["w"] for d in yearly.values())
|
||||||
|
if all_t < 20:
|
||||||
|
continue
|
||||||
|
acc = all_w / all_t * 100
|
||||||
|
pnl = sum(p for d in yearly.values() for p in d["pnls"])
|
||||||
|
tag = "✅" if acc >= 76 else ""
|
||||||
|
print(f" {target} consensus>={min_consensus} w={window_bars}: trades={all_t:4d} acc={acc:.1f}% pnl=€{pnl:+.0f} {tag}")
|
||||||
|
|
||||||
|
# ================================================================
|
||||||
|
# STRATEGIA C: Correlation-weighted squeeze
|
||||||
|
# Peso il segnale squeeze in base alla correlazione rolling con BTC
|
||||||
|
# ================================================================
|
||||||
|
print(f"\n --- CORRELATION-WEIGHTED ({tf}) ---")
|
||||||
|
|
||||||
|
for target in ["ETH", "SOL"]:
|
||||||
|
if target not in asset_data:
|
||||||
|
continue
|
||||||
|
tc = asset_data[target]["close"]
|
||||||
|
btc_c = asset_data["BTC"]["close"]
|
||||||
|
|
||||||
|
# Rolling correlation
|
||||||
|
corr_window = 48 # 48 bars
|
||||||
|
rolling_corr = np.full(n, np.nan)
|
||||||
|
ret_t = np.diff(np.log(np.where(tc == 0, 1e-10, tc)))
|
||||||
|
ret_b = np.diff(np.log(np.where(btc_c == 0, 1e-10, btc_c)))
|
||||||
|
for i in range(corr_window, len(ret_t)):
|
||||||
|
c_val = np.corrcoef(ret_t[i-corr_window:i], ret_b[i-corr_window:i])[0, 1]
|
||||||
|
rolling_corr[i + 1] = c_val if np.isfinite(c_val) else 0
|
||||||
|
|
||||||
|
events = asset_data[target]["events"]
|
||||||
|
|
||||||
|
for corr_thr in [0.5, 0.6, 0.7, 0.8]:
|
||||||
|
yearly = {}
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
if i + 3 >= n or np.isnan(rolling_corr[i]):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Solo quando correlazione con BTC è alta
|
||||||
|
if abs(rolling_corr[i]) < corr_thr:
|
||||||
|
continue
|
||||||
|
|
||||||
|
entry = tc[i - 1]
|
||||||
|
exit_price = tc[min(i + 2, n - 1)]
|
||||||
|
actual = (exit_price - entry) / entry * ev["direction"]
|
||||||
|
net = actual * LEVERAGE - FEE_RT * LEVERAGE
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnls": []}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if actual > 0:
|
||||||
|
yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnls"].append(net * INITIAL)
|
||||||
|
|
||||||
|
all_t = sum(d["t"] for d in yearly.values())
|
||||||
|
all_w = sum(d["w"] for d in yearly.values())
|
||||||
|
if all_t < 20:
|
||||||
|
continue
|
||||||
|
acc = all_w / all_t * 100
|
||||||
|
pnl = sum(p for d in yearly.values() for p in d["pnls"])
|
||||||
|
tag = "✅" if acc >= 76 else ""
|
||||||
|
print(f" {target} corr>={corr_thr}: trades={all_t:4d} acc={acc:.1f}% pnl=€{pnl:+.0f} {tag}")
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
"""S3-03: Ultimate Squeeze — combina TUTTI i filtri migliori.
|
||||||
|
Filtri che funzionano (testati singolarmente):
|
||||||
|
- Anti-fakeout (+1% acc)
|
||||||
|
- Long squeeze duration (+1% acc)
|
||||||
|
- Cross-asset squeeze simultaneo (+0.5%)
|
||||||
|
- Timing 4-16 UTC (+0.5%)
|
||||||
|
- Correlation ETH-BTC alta per ETH trades (+1%)
|
||||||
|
- Volume confirmation al breakout
|
||||||
|
|
||||||
|
Nuovi filtri da testare:
|
||||||
|
- Volume delta: up_volume - down_volume al breakout
|
||||||
|
- Momentum confirmation: breakout nella direzione del trend 1h
|
||||||
|
- Volatility regime: skip in regime estremo (RV > 100%)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, ".")
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from src.data.downloader import load_data
|
||||||
|
|
||||||
|
FEE_RT = 0.002
|
||||||
|
INITIAL = 1000
|
||||||
|
LEVERAGE = 3
|
||||||
|
|
||||||
|
|
||||||
|
def keltner_ratio(close, high, low, window=14):
|
||||||
|
n = len(close)
|
||||||
|
r = np.full(n, np.nan)
|
||||||
|
for i in range(window, n):
|
||||||
|
wc, wh, wl = close[i-window:i], high[i-window:i], low[i-window:i]
|
||||||
|
ma = np.mean(wc)
|
||||||
|
bb_std = np.std(wc)
|
||||||
|
tr = np.maximum(wh-wl, np.maximum(np.abs(wh-np.roll(wc,1)), np.abs(wl-np.roll(wc,1))))
|
||||||
|
atr = np.mean(tr[1:])
|
||||||
|
kc = (ma+1.5*atr)-(ma-1.5*atr)
|
||||||
|
bb = (ma+2*bb_std)-(ma-2*bb_std)
|
||||||
|
if kc > 0: r[i] = bb/kc
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def ema(arr, period):
|
||||||
|
r = np.full(len(arr), np.nan)
|
||||||
|
k = 2/(period+1)
|
||||||
|
r[period-1] = np.mean(arr[:period])
|
||||||
|
for i in range(period, len(arr)):
|
||||||
|
r[i] = arr[i]*k + r[i-1]*(1-k)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def rv_ann(close, window):
|
||||||
|
lr = np.diff(np.log(np.where(close == 0, 1e-10, close)))
|
||||||
|
r = np.full(len(close), np.nan)
|
||||||
|
for i in range(window, len(lr)):
|
||||||
|
r[i+1] = np.std(lr[i-window:i]) * np.sqrt(24*365)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def run_ultimate(primary, tf="15m"):
|
||||||
|
secondary = "ETH" if primary == "BTC" else "BTC"
|
||||||
|
|
||||||
|
df = load_data(primary, tf)
|
||||||
|
c, h, l, v = df["close"].values, df["high"].values, df["low"].values, df["volume"].values
|
||||||
|
n = len(df)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
|
||||||
|
df2 = load_data(secondary, tf)
|
||||||
|
c2, ts2 = df2["close"].values, df2["timestamp"].values
|
||||||
|
|
||||||
|
kcr = keltner_ratio(c, h, l, 14)
|
||||||
|
kcr2 = keltner_ratio(c2, df2["high"].values, df2["low"].values, 14)
|
||||||
|
|
||||||
|
ema_50 = ema(c, 50)
|
||||||
|
rv_48 = rv_ann(c, 48)
|
||||||
|
|
||||||
|
# Rolling correlation
|
||||||
|
ret1 = np.diff(np.log(np.where(c == 0, 1e-10, c)))
|
||||||
|
ret2 = np.diff(np.log(np.where(c2[:len(c)] == 0, 1e-10, c2[:len(c)])))
|
||||||
|
min_len = min(len(ret1), len(ret2))
|
||||||
|
ret1 = ret1[:min_len]
|
||||||
|
ret2 = ret2[:min_len]
|
||||||
|
corr = np.full(n, np.nan)
|
||||||
|
for i in range(48, min_len):
|
||||||
|
cv = np.corrcoef(ret1[i-48:i], ret2[i-48:i])[0,1]
|
||||||
|
corr[i+1] = cv if np.isfinite(cv) else 0
|
||||||
|
|
||||||
|
# Detect squeezes
|
||||||
|
events = []
|
||||||
|
in_sq = False
|
||||||
|
sq_start = 0
|
||||||
|
for i in range(15, n):
|
||||||
|
if np.isnan(kcr[i]): continue
|
||||||
|
is_sq = kcr[i] < 0.8
|
||||||
|
if is_sq and not in_sq:
|
||||||
|
in_sq = True
|
||||||
|
sq_start = i
|
||||||
|
elif not is_sq and in_sq:
|
||||||
|
in_sq = False
|
||||||
|
dur = i - sq_start
|
||||||
|
if dur < 5 or i + 6 >= n:
|
||||||
|
continue
|
||||||
|
events.append({"idx": i, "dur": dur, "sq_start": sq_start})
|
||||||
|
|
||||||
|
print(f"\n{'#'*70}")
|
||||||
|
print(f" {primary} {tf} — ULTIMATE SQUEEZE ({len(events)} squeeze events)")
|
||||||
|
print(f"{'#'*70}")
|
||||||
|
|
||||||
|
filters_map = {
|
||||||
|
"antifake": lambda ev, i: not _antifake(c, h, l, i),
|
||||||
|
"long_sq": lambda ev, i: ev["dur"] >= 10,
|
||||||
|
"timing": lambda ev, i: 4 <= ts.iloc[i].hour <= 16,
|
||||||
|
"cross": lambda ev, i: _cross_squeeze(kcr2, i, ts, ts2),
|
||||||
|
"corr_high": lambda ev, i: not np.isnan(corr[i]) and abs(corr[i]) >= 0.6,
|
||||||
|
"vol_confirm": lambda ev, i: _vol_confirm(v, i, ev["sq_start"]),
|
||||||
|
"trend_align": lambda ev, i: _trend_align(c, ema_50, i),
|
||||||
|
"low_rv": lambda ev, i: not np.isnan(rv_48[i]) and rv_48[i] < 1.5,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _antifake(c, h, l, i):
|
||||||
|
if i + 1 >= len(c): return False
|
||||||
|
br = h[i] - l[i]
|
||||||
|
if br <= 0: return False
|
||||||
|
if c[i] > c[i-1]:
|
||||||
|
return (h[i] - c[i]) / br > 0.6
|
||||||
|
return (c[i] - l[i]) / br > 0.6
|
||||||
|
|
||||||
|
def _cross_squeeze(kcr2, i, ts1, ts2_arr):
|
||||||
|
i2 = np.searchsorted(ts2_arr, ts.values[i].astype("int64") // 10**6)
|
||||||
|
i2 = min(i2, len(kcr2)-1)
|
||||||
|
return any(not np.isnan(kcr2[j]) and kcr2[j] < 0.85 for j in range(max(0,i2-10), i2+1))
|
||||||
|
|
||||||
|
def _vol_confirm(v, i, sq_start):
|
||||||
|
avg = np.mean(v[sq_start:i])
|
||||||
|
return avg > 0 and v[i] > avg * 1.3
|
||||||
|
|
||||||
|
def _trend_align(c, ema_val, i):
|
||||||
|
if np.isnan(ema_val[i]): return True
|
||||||
|
first_ret = (c[i] - c[i-1]) / c[i-1] if c[i-1] > 0 else 0
|
||||||
|
if first_ret > 0:
|
||||||
|
return c[i] > ema_val[i]
|
||||||
|
return c[i] < ema_val[i]
|
||||||
|
|
||||||
|
# Test combinazioni incrementali
|
||||||
|
combos = [
|
||||||
|
("BASE", []),
|
||||||
|
("antifake", ["antifake"]),
|
||||||
|
("long_sq", ["long_sq"]),
|
||||||
|
("antifake+long", ["antifake", "long_sq"]),
|
||||||
|
("antifake+timing", ["antifake", "timing"]),
|
||||||
|
("antifake+cross", ["antifake", "cross"]),
|
||||||
|
("antifake+corr", ["antifake", "corr_high"]),
|
||||||
|
("antifake+vol", ["antifake", "vol_confirm"]),
|
||||||
|
("antifake+trend", ["antifake", "trend_align"]),
|
||||||
|
("af+long+timing", ["antifake", "long_sq", "timing"]),
|
||||||
|
("af+long+cross", ["antifake", "long_sq", "cross"]),
|
||||||
|
("af+long+corr", ["antifake", "long_sq", "corr_high"]),
|
||||||
|
("af+long+trend", ["antifake", "long_sq", "trend_align"]),
|
||||||
|
("af+long+cross+time", ["antifake", "long_sq", "cross", "timing"]),
|
||||||
|
("af+long+corr+time", ["antifake", "long_sq", "corr_high", "timing"]),
|
||||||
|
("af+long+corr+trend", ["antifake", "long_sq", "corr_high", "trend_align"]),
|
||||||
|
("ALL_NO_VOL", ["antifake", "long_sq", "cross", "timing", "corr_high", "trend_align", "low_rv"]),
|
||||||
|
("ALL", ["antifake", "long_sq", "cross", "timing", "corr_high", "vol_confirm", "trend_align", "low_rv"]),
|
||||||
|
("BEST_5", ["antifake", "long_sq", "corr_high", "trend_align", "low_rv"]),
|
||||||
|
]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for combo_name, filter_names in combos:
|
||||||
|
yearly = {}
|
||||||
|
capital = float(INITIAL)
|
||||||
|
peak = capital
|
||||||
|
max_dd = 0
|
||||||
|
|
||||||
|
for ev in events:
|
||||||
|
i = ev["idx"]
|
||||||
|
first_ret = (c[i] - c[i-1]) / c[i-1] if c[i-1] > 0 else 0
|
||||||
|
if abs(first_ret) < 0.001:
|
||||||
|
continue
|
||||||
|
|
||||||
|
skip = False
|
||||||
|
for fn in filter_names:
|
||||||
|
if fn in filters_map and not filters_map[fn](ev, i):
|
||||||
|
skip = True
|
||||||
|
break
|
||||||
|
if skip:
|
||||||
|
continue
|
||||||
|
|
||||||
|
direction = 1 if first_ret > 0 else -1
|
||||||
|
entry = c[i-1]
|
||||||
|
exit_price = c[min(i+2, n-1)]
|
||||||
|
actual = (exit_price - entry) / entry * direction
|
||||||
|
net = actual * LEVERAGE - FEE_RT * LEVERAGE
|
||||||
|
|
||||||
|
capital += capital * 0.15 * net
|
||||||
|
capital = max(capital, 10)
|
||||||
|
if capital > peak: peak = capital
|
||||||
|
dd = (peak - capital) / peak
|
||||||
|
max_dd = max(max_dd, dd)
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnls": []}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if actual > 0: yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnls"].append(net * INITIAL)
|
||||||
|
|
||||||
|
all_t = sum(d["t"] for d in yearly.values())
|
||||||
|
all_w = sum(d["w"] for d in yearly.values())
|
||||||
|
if all_t < 20: continue
|
||||||
|
|
||||||
|
acc = all_w / all_t * 100
|
||||||
|
pnl = sum(p for d in yearly.values() for p in d["pnls"])
|
||||||
|
worst = min(yearly.items(), key=lambda x: x[1]["w"]/x[1]["t"] if x[1]["t"]>0 else 0)
|
||||||
|
wa = worst[1]["w"]/worst[1]["t"]*100 if worst[1]["t"]>0 else 0
|
||||||
|
|
||||||
|
results.append({
|
||||||
|
"name": combo_name, "trades": all_t, "acc": acc, "pnl": pnl,
|
||||||
|
"dd": max_dd*100, "capital": capital, "worst": f"{worst[0]}({wa:.0f}%)",
|
||||||
|
"yearly": yearly,
|
||||||
|
})
|
||||||
|
|
||||||
|
results.sort(key=lambda x: x["acc"], reverse=True)
|
||||||
|
|
||||||
|
print(f"\n {'Name':.<28s} {'Trades':>6s} {'Acc':>6s} {'PnL€':>9s} {'DD%':>5s} {'Worst':>12s}")
|
||||||
|
print(f" {'-'*70}")
|
||||||
|
for r in results[:20]:
|
||||||
|
tag = "✅✅" if r["acc"] >= 80 else "✅" if r["acc"] >= 78 else ""
|
||||||
|
print(f" {r['name']:.<28s} {r['trades']:>6d} {r['acc']:>5.1f}% €{r['pnl']:>+8.0f} {r['dd']:>4.1f}% {r['worst']:>12s} {tag}")
|
||||||
|
|
||||||
|
# Dettaglio migliore
|
||||||
|
if results:
|
||||||
|
best = results[0]
|
||||||
|
print(f"\n MIGLIORE: {best['name']} → {best['acc']:.1f}% acc, DD {best['dd']:.1f}%")
|
||||||
|
for y in sorted(best["yearly"]):
|
||||||
|
d = best["yearly"][y]
|
||||||
|
ya = d["w"]/d["t"]*100 if d["t"]>0 else 0
|
||||||
|
tag = " ← CRASH" if y in [2020,2021,2022] else ""
|
||||||
|
print(f" {y}: {d['t']:4d}t {ya:5.1f}% €{sum(d['pnls']):+.0f}{tag}")
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
all_r = []
|
||||||
|
for asset in ["BTC", "ETH"]:
|
||||||
|
for tf in ["15m", "1h"]:
|
||||||
|
r = run_ultimate(asset, tf)
|
||||||
|
for x in r:
|
||||||
|
all_r.append({**x, "key": f"{asset}_{tf}"})
|
||||||
|
|
||||||
|
all_r.sort(key=lambda x: x["acc"], reverse=True)
|
||||||
|
print(f"\n\n{'='*70}")
|
||||||
|
print(f" TOP 10 GLOBALE")
|
||||||
|
print(f"{'='*70}")
|
||||||
|
for r in all_r[:10]:
|
||||||
|
tag = "✅✅" if r["acc"] >= 80 else "✅" if r["acc"] >= 78 else ""
|
||||||
|
print(f" {r['key']:.<10s} {r['name']:.<28s} {r['trades']:>5d} {r['acc']:>5.1f}% €{r['pnl']:>+8.0f} DD {r['dd']:.1f}% {r['worst']:>12s} {tag}")
|
||||||
@@ -10,6 +10,7 @@ import pandas as pd
|
|||||||
|
|
||||||
from src.live.cerbero_client import CerberoClient
|
from src.live.cerbero_client import CerberoClient
|
||||||
from src.live.signal_engine import SignalEngine
|
from src.live.signal_engine import SignalEngine
|
||||||
|
from src.live.telegram_notifier import notify_event
|
||||||
|
|
||||||
LOG_DIR = Path(__file__).resolve().parents[2] / "data" / "paper_trades"
|
LOG_DIR = Path(__file__).resolve().parents[2] / "data" / "paper_trades"
|
||||||
INSTRUMENT = "ETH_USDC-PERPETUAL"
|
INSTRUMENT = "ETH_USDC-PERPETUAL"
|
||||||
@@ -52,6 +53,7 @@ class PaperTrader:
|
|||||||
with open(self.log_path, "a") as f:
|
with open(self.log_path, "a") as f:
|
||||||
f.write(json.dumps(entry) + "\n")
|
f.write(json.dumps(entry) + "\n")
|
||||||
print(f" [{entry['timestamp'][:19]}] {event}: {json.dumps(data or {})}")
|
print(f" [{entry['timestamp'][:19]}] {event}: {json.dumps(data or {})}")
|
||||||
|
notify_event(event, data)
|
||||||
|
|
||||||
def save_status(self):
|
def save_status(self):
|
||||||
status = {
|
status = {
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""Notifiche Telegram per il paper trader."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import urllib.request
|
||||||
|
import urllib.parse
|
||||||
|
import json
|
||||||
|
|
||||||
|
BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
|
||||||
|
CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "")
|
||||||
|
|
||||||
|
NOTIFY_EVENTS = {
|
||||||
|
"SIGNAL", "OPENED", "CLOSED", "OPEN_FAILED", "CLOSE_FAILED",
|
||||||
|
"ERROR", "STARTUP", "SHUTDOWN", "TRAINING_FAILED",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def send_telegram(text: str) -> bool:
|
||||||
|
if not BOT_TOKEN or not CHAT_ID:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
|
||||||
|
data = urllib.parse.urlencode({"chat_id": CHAT_ID, "text": text, "parse_mode": "HTML"}).encode()
|
||||||
|
urllib.request.urlopen(url, data, timeout=10)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def notify_event(event: str, data: dict | None = None):
|
||||||
|
if event not in NOTIFY_EVENTS:
|
||||||
|
return
|
||||||
|
lines = [f"📊 <b>{event}</b>"]
|
||||||
|
if data:
|
||||||
|
for k, v in data.items():
|
||||||
|
if k in ("signal",):
|
||||||
|
continue
|
||||||
|
lines.append(f" {k}: {v}")
|
||||||
|
send_telegram("\n".join(lines))
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
"""Strategie di trading — classe base e indicatori condivisi."""
|
||||||
|
from src.strategies.base import Strategy, Signal, BacktestResult, YearlyStats
|
||||||
|
from src.strategies.indicators import (
|
||||||
|
keltner_ratio, detect_squeezes, ema, atr, rv_annualized, rolling_correlation,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"Strategy", "Signal", "BacktestResult", "YearlyStats",
|
||||||
|
"keltner_ratio", "detect_squeezes", "ema", "atr",
|
||||||
|
"rv_annualized", "rolling_correlation",
|
||||||
|
]
|
||||||
|
|||||||
@@ -0,0 +1,243 @@
|
|||||||
|
"""Classe base astratta per tutte le strategie di trading."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from src.data.downloader import load_data
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Signal:
|
||||||
|
"""Segnale di trading generato da una strategia."""
|
||||||
|
idx: int
|
||||||
|
direction: int # +1 long, -1 short
|
||||||
|
entry_price: float
|
||||||
|
metadata: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class YearlyStats:
|
||||||
|
year: int
|
||||||
|
trades: int
|
||||||
|
wins: int
|
||||||
|
pnl: float
|
||||||
|
|
||||||
|
@property
|
||||||
|
def accuracy(self) -> float:
|
||||||
|
return self.wins / self.trades * 100 if self.trades > 0 else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BacktestResult:
|
||||||
|
"""Risultato completo di un backtest."""
|
||||||
|
strategy_name: str
|
||||||
|
asset: str
|
||||||
|
timeframe: str
|
||||||
|
params: dict
|
||||||
|
|
||||||
|
trades: int
|
||||||
|
wins: int
|
||||||
|
pnl: float
|
||||||
|
capital: float
|
||||||
|
initial_capital: float
|
||||||
|
max_dd: float
|
||||||
|
time_in_market_pct: float
|
||||||
|
avg_trade_duration_h: float
|
||||||
|
years_active: int
|
||||||
|
yearly: list[YearlyStats]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def accuracy(self) -> float:
|
||||||
|
return self.wins / self.trades * 100 if self.trades > 0 else 0.0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def sharpe(self) -> float:
|
||||||
|
pnls = []
|
||||||
|
for ys in self.yearly:
|
||||||
|
pnls.append(ys.pnl)
|
||||||
|
if len(pnls) < 2 or np.std(pnls) == 0:
|
||||||
|
return 0.0
|
||||||
|
return float(np.mean(pnls) / np.std(pnls) * np.sqrt(len(pnls)))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def daily_pnl(self) -> float:
|
||||||
|
return self.pnl / (self.years_active * 365) if self.years_active > 0 else 0.0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def worst_year(self) -> YearlyStats | None:
|
||||||
|
valid = [y for y in self.yearly if y.trades >= 10]
|
||||||
|
if not valid:
|
||||||
|
valid = self.yearly
|
||||||
|
return min(valid, key=lambda y: y.accuracy) if valid else None
|
||||||
|
|
||||||
|
def print_summary(self):
|
||||||
|
worst = self.worst_year
|
||||||
|
worst_str = f"{worst.year}({worst.accuracy:.0f}%)" if worst else "N/A"
|
||||||
|
dur = f"{self.avg_trade_duration_h:.0f}h" if self.avg_trade_duration_h >= 1 else f"{self.avg_trade_duration_h * 60:.0f}m"
|
||||||
|
print(f" {self.strategy_name:<30s} {self.asset:>3s} {self.timeframe:>3s} "
|
||||||
|
f"{self.trades:>5d}t {self.accuracy:>5.1f}% "
|
||||||
|
f"€{self.pnl:>+9.0f} DD {self.max_dd:>4.1f}% "
|
||||||
|
f"€/d {self.daily_pnl:>+6.2f} "
|
||||||
|
f"Mkt {self.time_in_market_pct:>4.1f}% {dur:>5s} "
|
||||||
|
f"worst={worst_str} {self.years_active}y")
|
||||||
|
|
||||||
|
def print_yearly(self):
|
||||||
|
print(f"\n {self.strategy_name} [{self.asset} {self.timeframe}] — per anno:")
|
||||||
|
print(f" {'Anno':>6s} {'Trades':>7s} {'Acc':>6s} {'PnL€':>9s}")
|
||||||
|
for ys in sorted(self.yearly, key=lambda y: y.year):
|
||||||
|
print(f" {ys.year:>6d} {ys.trades:>7d} {ys.accuracy:>5.1f}% €{ys.pnl:>+8.0f}")
|
||||||
|
|
||||||
|
|
||||||
|
TF_MINUTES = {"1m": 1, "5m": 5, "15m": 15, "1h": 60, "4h": 240, "1d": 1440}
|
||||||
|
|
||||||
|
|
||||||
|
class Strategy(ABC):
|
||||||
|
"""Classe base per tutte le strategie.
|
||||||
|
|
||||||
|
Sottoclassi devono implementare:
|
||||||
|
- name, description, default_assets, default_timeframes
|
||||||
|
- generate_signals(df, timestamps, **params) -> list[Signal]
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str = "unnamed"
|
||||||
|
description: str = ""
|
||||||
|
default_assets: list[str] = ["BTC", "ETH"]
|
||||||
|
default_timeframes: list[str] = ["15m", "1h"]
|
||||||
|
|
||||||
|
# Parametri di backtest
|
||||||
|
fee_rt: float = 0.002
|
||||||
|
leverage: float = 3.0
|
||||||
|
position_size: float = 0.15
|
||||||
|
initial_capital: float = 1000.0
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def generate_signals(self, df: pd.DataFrame, ts: pd.DatetimeIndex,
|
||||||
|
**params) -> list[Signal]:
|
||||||
|
"""Genera segnali di trading dal dataframe OHLCV.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
df: DataFrame con colonne open, high, low, close, volume, timestamp
|
||||||
|
ts: DatetimeIndex UTC dei timestamp
|
||||||
|
**params: parametri specifici della strategia
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Lista di Signal con idx, direction, entry_price
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def backtest(self, asset: str, tf: str, hold: int = 3,
|
||||||
|
**params) -> BacktestResult | None:
|
||||||
|
"""Esegue backtest su un asset/timeframe."""
|
||||||
|
df = load_data(asset, tf)
|
||||||
|
c = df["close"].values
|
||||||
|
n = len(c)
|
||||||
|
ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||||
|
|
||||||
|
sig_params = {**params, "asset": asset, "tf": tf}
|
||||||
|
signals = self.generate_signals(df, ts, **sig_params)
|
||||||
|
if not signals:
|
||||||
|
return None
|
||||||
|
|
||||||
|
yearly: dict[int, dict] = {}
|
||||||
|
capital = float(self.initial_capital)
|
||||||
|
peak = capital
|
||||||
|
max_dd = 0.0
|
||||||
|
total_bars = 0
|
||||||
|
|
||||||
|
for sig in signals:
|
||||||
|
i = sig.idx
|
||||||
|
if i + hold >= n or i < 1:
|
||||||
|
continue
|
||||||
|
|
||||||
|
entry = sig.entry_price
|
||||||
|
exit_price = c[min(i + hold - 1, n - 1)]
|
||||||
|
actual = (exit_price - entry) / entry * sig.direction
|
||||||
|
net = actual * self.leverage - self.fee_rt * self.leverage
|
||||||
|
|
||||||
|
capital += capital * self.position_size * net
|
||||||
|
capital = max(capital, 10)
|
||||||
|
if capital > peak:
|
||||||
|
peak = capital
|
||||||
|
dd = (peak - capital) / peak
|
||||||
|
max_dd = max(max_dd, dd)
|
||||||
|
total_bars += hold
|
||||||
|
|
||||||
|
year = ts.iloc[i].year
|
||||||
|
if year not in yearly:
|
||||||
|
yearly[year] = {"w": 0, "t": 0, "pnl": 0.0}
|
||||||
|
yearly[year]["t"] += 1
|
||||||
|
if actual > 0:
|
||||||
|
yearly[year]["w"] += 1
|
||||||
|
yearly[year]["pnl"] += net * self.initial_capital
|
||||||
|
|
||||||
|
all_t = sum(d["t"] for d in yearly.values())
|
||||||
|
all_w = sum(d["w"] for d in yearly.values())
|
||||||
|
if all_t == 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
yearly_stats = [
|
||||||
|
YearlyStats(year=y, trades=d["t"], wins=d["w"], pnl=d["pnl"])
|
||||||
|
for y, d in sorted(yearly.items())
|
||||||
|
]
|
||||||
|
|
||||||
|
return BacktestResult(
|
||||||
|
strategy_name=self.name,
|
||||||
|
asset=asset,
|
||||||
|
timeframe=tf,
|
||||||
|
params=params,
|
||||||
|
trades=all_t,
|
||||||
|
wins=all_w,
|
||||||
|
pnl=sum(d["pnl"] for d in yearly.values()),
|
||||||
|
capital=capital,
|
||||||
|
initial_capital=self.initial_capital,
|
||||||
|
max_dd=max_dd * 100,
|
||||||
|
time_in_market_pct=total_bars / n * 100,
|
||||||
|
avg_trade_duration_h=hold * TF_MINUTES.get(tf, 60) / 60,
|
||||||
|
years_active=len(yearly),
|
||||||
|
yearly=yearly_stats,
|
||||||
|
)
|
||||||
|
|
||||||
|
def run_all(self, assets: list[str] | None = None,
|
||||||
|
timeframes: list[str] | None = None,
|
||||||
|
hold: int = 3, **params) -> list[BacktestResult]:
|
||||||
|
"""Esegue backtest su tutte le combinazioni asset/timeframe."""
|
||||||
|
assets = assets or self.default_assets
|
||||||
|
timeframes = timeframes or self.default_timeframes
|
||||||
|
results = []
|
||||||
|
for asset in assets:
|
||||||
|
for tf in timeframes:
|
||||||
|
r = self.backtest(asset, tf, hold=hold, **params)
|
||||||
|
if r and r.trades >= 20:
|
||||||
|
results.append(r)
|
||||||
|
results.sort(key=lambda r: r.accuracy, reverse=True)
|
||||||
|
return results
|
||||||
|
|
||||||
|
def report(self, results: list[BacktestResult] | None = None,
|
||||||
|
assets: list[str] | None = None,
|
||||||
|
timeframes: list[str] | None = None,
|
||||||
|
hold: int = 3, **params):
|
||||||
|
"""Esegue e stampa report completo."""
|
||||||
|
if results is None:
|
||||||
|
results = self.run_all(assets, timeframes, hold, **params)
|
||||||
|
|
||||||
|
print(f"\n{'=' * 120}")
|
||||||
|
print(f" {self.name} — {self.description}")
|
||||||
|
print(f" Fee: {self.fee_rt*100:.1f}% RT | Leva: {self.leverage:.0f}x | Pos: {self.position_size*100:.0f}%")
|
||||||
|
print(f"{'=' * 120}")
|
||||||
|
print(f" {'Nome':<30s} {'A/T':>7s} {'Trades':>6s} {'Acc':>6s} "
|
||||||
|
f"{'PnL€':>10s} {'DD%':>6s} {'€/day':>7s} "
|
||||||
|
f"{'Mkt%':>5s} {'Dur':>5s} {'Worst':>12s} {'Anni':>4s}")
|
||||||
|
print(f" {'─' * 110}")
|
||||||
|
|
||||||
|
for r in results:
|
||||||
|
r.print_summary()
|
||||||
|
|
||||||
|
if results:
|
||||||
|
best = results[0]
|
||||||
|
best.print_yearly()
|
||||||
|
|
||||||
|
return results
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
"""Indicatori tecnici condivisi tra tutte le strategie."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
def keltner_ratio(close: np.ndarray, high: np.ndarray, low: np.ndarray,
|
||||||
|
window: int = 14) -> np.ndarray:
|
||||||
|
"""Rapporto Bollinger / Keltner. Sotto 1 = squeeze (BB dentro KC)."""
|
||||||
|
n = len(close)
|
||||||
|
r = np.full(n, np.nan)
|
||||||
|
for i in range(window, n):
|
||||||
|
wc = close[i - window:i]
|
||||||
|
wh = high[i - window:i]
|
||||||
|
wl = low[i - window:i]
|
||||||
|
ma = np.mean(wc)
|
||||||
|
bb_std = np.std(wc)
|
||||||
|
tr = np.maximum(
|
||||||
|
wh - wl,
|
||||||
|
np.maximum(np.abs(wh - np.roll(wc, 1)), np.abs(wl - np.roll(wc, 1))),
|
||||||
|
)
|
||||||
|
atr = np.mean(tr[1:])
|
||||||
|
kc = (ma + 1.5 * atr) - (ma - 1.5 * atr)
|
||||||
|
bb = (ma + 2 * bb_std) - (ma - 2 * bb_std)
|
||||||
|
if kc > 0:
|
||||||
|
r[i] = bb / kc
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def detect_squeezes(close: np.ndarray, high: np.ndarray, low: np.ndarray,
|
||||||
|
kcr: np.ndarray, sq_thr: float = 0.8,
|
||||||
|
min_dur: int = 5) -> list[dict]:
|
||||||
|
"""Rileva squeeze events: periodi dove BB sta dentro KC."""
|
||||||
|
events: list[dict] = []
|
||||||
|
in_sq = False
|
||||||
|
sq_start = 0
|
||||||
|
for i in range(1, len(close)):
|
||||||
|
if np.isnan(kcr[i]):
|
||||||
|
continue
|
||||||
|
is_sq = kcr[i] < sq_thr
|
||||||
|
if is_sq and not in_sq:
|
||||||
|
in_sq = True
|
||||||
|
sq_start = i
|
||||||
|
elif not is_sq and in_sq:
|
||||||
|
in_sq = False
|
||||||
|
dur = i - sq_start
|
||||||
|
if dur < min_dur:
|
||||||
|
continue
|
||||||
|
events.append({
|
||||||
|
"idx": i, "dur": dur, "sq_start": sq_start,
|
||||||
|
"kcr_at_release": kcr[i],
|
||||||
|
})
|
||||||
|
return events
|
||||||
|
|
||||||
|
|
||||||
|
def ema(arr: np.ndarray, period: int) -> np.ndarray:
|
||||||
|
"""Exponential Moving Average."""
|
||||||
|
r = np.full(len(arr), np.nan)
|
||||||
|
k = 2 / (period + 1)
|
||||||
|
r[period - 1] = np.mean(arr[:period])
|
||||||
|
for i in range(period, len(arr)):
|
||||||
|
r[i] = arr[i] * k + r[i - 1] * (1 - k)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def atr(high: np.ndarray, low: np.ndarray, close: np.ndarray,
|
||||||
|
period: int = 14) -> np.ndarray:
|
||||||
|
"""Average True Range (EMA-smoothed)."""
|
||||||
|
tr = np.maximum(
|
||||||
|
high - low,
|
||||||
|
np.maximum(np.abs(high - np.roll(close, 1)), np.abs(low - np.roll(close, 1))),
|
||||||
|
)
|
||||||
|
tr[0] = high[0] - low[0]
|
||||||
|
r = np.full(len(close), np.nan)
|
||||||
|
r[period - 1] = np.mean(tr[:period])
|
||||||
|
k = 2 / (period + 1)
|
||||||
|
for i in range(period, len(close)):
|
||||||
|
r[i] = tr[i] * k + r[i - 1] * (1 - k)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def rv_annualized(close: np.ndarray, window: int) -> np.ndarray:
|
||||||
|
"""Realized volatility annualizzata (hourly data assumed)."""
|
||||||
|
lr = np.diff(np.log(np.where(close == 0, 1e-10, close)))
|
||||||
|
r = np.full(len(close), np.nan)
|
||||||
|
for i in range(window, len(lr)):
|
||||||
|
r[i + 1] = np.std(lr[i - window:i]) * np.sqrt(24 * 365)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def rolling_correlation(close_a: np.ndarray, close_b: np.ndarray,
|
||||||
|
window: int = 48) -> np.ndarray:
|
||||||
|
"""Correlazione rolling tra rendimenti logaritmici di due asset."""
|
||||||
|
n = max(len(close_a), len(close_b))
|
||||||
|
ret_a = np.diff(np.log(np.where(close_a == 0, 1e-10, close_a)))
|
||||||
|
ret_b = np.diff(np.log(np.where(close_b[:len(close_a)] == 0, 1e-10, close_b[:len(close_a)])))
|
||||||
|
min_len = min(len(ret_a), len(ret_b))
|
||||||
|
corr = np.full(n, np.nan)
|
||||||
|
for i in range(window, min_len):
|
||||||
|
cv = np.corrcoef(ret_a[i - window:i], ret_b[i - window:i])[0, 1]
|
||||||
|
corr[i + 1] = cv if np.isfinite(cv) else 0
|
||||||
|
return corr
|
||||||
@@ -542,30 +542,30 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cuda-bindings"
|
name = "cuda-bindings"
|
||||||
version = "13.2.0"
|
version = "13.3.0"
|
||||||
source = { registry = "https://pypi.org/simple" }
|
source = { registry = "https://pypi.org/simple" }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "cuda-pathfinder", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
|
{ name = "cuda-pathfinder", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
|
||||||
]
|
]
|
||||||
wheels = [
|
wheels = [
|
||||||
{ url = "https://files.pythonhosted.org/packages/e0/a9/3a8241c6e19483ac1f1dcf5c10238205dcb8a6e9d0d4d4709240dff28ff4/cuda_bindings-13.2.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:721104c603f059780d287969be3d194a18d0cc3b713ed9049065a1107706759d", size = 5730273, upload-time = "2026-03-11T00:12:37.18Z" },
|
{ url = "https://files.pythonhosted.org/packages/f9/52/50673d25e46d199556f827514bf646a49471d50538c5e577201245b348a9/cuda_bindings-13.3.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:244a167d81a9d07d3209d02c8e02e848c2b7c38f4d01e8e4d1f9620b173ae006", size = 6051409, upload-time = "2026-05-27T03:59:01.648Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/e9/94/2748597f47bb1600cd466b20cab4159f1530a3a33fe7f70fee199b3abb9e/cuda_bindings-13.2.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1eba9504ac70667dd48313395fe05157518fd6371b532790e96fbb31bbb5a5e1", size = 6313924, upload-time = "2026-03-11T00:12:39.462Z" },
|
{ url = "https://files.pythonhosted.org/packages/88/ee/e8f4bdfb808c3689539b7c035d63b6dac9f236b2d6f807f18c7f5f3ef879/cuda_bindings-13.3.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:820ab45be3f39a088f39c4a04eb8b852d0b339bff8c518da5c258882b8a4e21b", size = 6671833, upload-time = "2026-05-27T03:59:03.761Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/52/c8/b2589d68acf7e3d63e2be330b84bc25712e97ed799affbca7edd7eae25d6/cuda_bindings-13.2.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e865447abfb83d6a98ad5130ed3c70b1fc295ae3eeee39fd07b4ddb0671b6788", size = 5722404, upload-time = "2026-03-11T00:12:44.041Z" },
|
{ url = "https://files.pythonhosted.org/packages/1f/e0/4b3fdba08ff177e9451f376a4ba2df18d76f9158e6a16cdc062bd83db9fa/cuda_bindings-13.3.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f72f67f5790e7fa51e3f893e007e49567573ccdf4ed1ca988fbbbd36cd77847c", size = 6020531, upload-time = "2026-05-27T03:59:07.942Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/1f/92/f899f7bbb5617bb65ec52a6eac1e9a1447a86b916c4194f8a5001b8cde0c/cuda_bindings-13.2.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:46d8776a55d6d5da9dd6e9858fba2efcda2abe6743871dee47dd06eb8cb6d955", size = 6320619, upload-time = "2026-03-11T00:12:45.939Z" },
|
{ url = "https://files.pythonhosted.org/packages/04/40/a2ea4d8f032bfd6c220d50b6f92cd61f33d48f31959da39ed1b178cfee54/cuda_bindings-13.3.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a99c3b8d584f266c616bd0f30c7cd83e33553e3ef2abad41ff5a74fbc033a69a", size = 6653764, upload-time = "2026-05-27T03:59:09.981Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/df/93/eef988860a3ca985f82c4f3174fc0cdd94e07331ba9a92e8e064c260337f/cuda_bindings-13.2.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6629ca2df6f795b784752409bcaedbd22a7a651b74b56a165ebc0c9dcbd504d0", size = 5614610, upload-time = "2026-03-11T00:12:50.337Z" },
|
{ url = "https://files.pythonhosted.org/packages/ae/a0/156efe7816699c2de1ea2395031db7d010b7af23c243563a3ee6f0ecc1de/cuda_bindings-13.3.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a7698fcc4577aa96372866f4d0c9a6cf686cd5c90eab94581c29d37fe6600542", size = 5914803, upload-time = "2026-05-27T03:59:14.011Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/18/23/6db3aba46864aee357ab2415135b3fe3da7e9f1fa0221fa2a86a5968099c/cuda_bindings-13.2.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7dca0da053d3b4cc4869eff49c61c03f3c5dbaa0bcd712317a358d5b8f3f385d", size = 6149914, upload-time = "2026-03-11T00:12:52.374Z" },
|
{ url = "https://files.pythonhosted.org/packages/51/91/510aae64d53227b5b36db6bfaea41514b66d92cd65ddc43aa49566f18313/cuda_bindings-13.3.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:abd908f651160d12c45c5714a38ee102a1173a55433c0d1509ec0e8293beb4a6", size = 6472506, upload-time = "2026-05-27T03:59:16.551Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/c0/87/87a014f045b77c6de5c8527b0757fe644417b184e5367db977236a141602/cuda_bindings-13.2.0-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a6464b30f46692d6c7f65d4a0e0450d81dd29de3afc1bb515653973d01c2cd6e", size = 5685673, upload-time = "2026-03-11T00:12:56.371Z" },
|
{ url = "https://files.pythonhosted.org/packages/01/53/2ef49e5b3734a5531b2ba5d726cba724d9cbb262404e586ed61070604826/cuda_bindings-13.3.0-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a801fa30e75d25b74252123aefc746b6c4275624d2b8640632dd1dfeeaa1f88", size = 6008814, upload-time = "2026-05-27T03:59:20.921Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/ee/5e/c0fe77a73aaefd3fff25ffaccaac69c5a63eafdf8b9a4c476626ef0ac703/cuda_bindings-13.2.0-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f4af9f3e1be603fa12d5ad6cfca7844c9d230befa9792b5abdf7dd79979c3626", size = 6191386, upload-time = "2026-03-11T00:12:58.965Z" },
|
{ url = "https://files.pythonhosted.org/packages/2f/cb/3a9fcf0651e0a49b4d0f1955837ce079245b27086c22fb2f253039bdf324/cuda_bindings-13.3.0-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:94d40ef7b4bdd9dce0244a1baa132e0e538f1eb2c0d162fb3648a15e48515365", size = 6531477, upload-time = "2026-05-27T03:59:23.391Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/5f/58/ed2c3b39c8dd5f96aa7a4abef0d47a73932c7a988e30f5fa428f00ed0da1/cuda_bindings-13.2.0-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:df850a1ff8ce1b3385257b08e47b70e959932f5f432d0a4e46a355962b4e4771", size = 5507469, upload-time = "2026-03-11T00:13:04.063Z" },
|
{ url = "https://files.pythonhosted.org/packages/2b/0f/6987c5ee98f117317a85650ddc79480a3fa59a573ae1c923d0722b56ae71/cuda_bindings-13.3.0-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e5911bea15810b749a8077f8c45423ed785d51618b8e8664dea1fc8f5a2a76c8", size = 5807073, upload-time = "2026-05-27T03:59:28.218Z" },
|
||||||
{ url = "https://files.pythonhosted.org/packages/1f/01/0c941b112ceeb21439b05895eace78ca1aa2eaaf695c8521a068fd9b4c00/cuda_bindings-13.2.0-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e8a16384c6494e5485f39314b0b4afb04bee48d49edb16d5d8593fd35bbd231b", size = 6059693, upload-time = "2026-03-11T00:13:06.003Z" },
|
{ url = "https://files.pythonhosted.org/packages/f6/ab/46ceee07dc19f18a5d1c28d592750ed9dbdc803077eb083576a442c9938c/cuda_bindings-13.3.0-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2870fed7707a37f8af0c02364b05f355ebe8921604e8c68eb56cf66867e0798", size = 6354325, upload-time = "2026-05-27T03:59:30.715Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cuda-pathfinder"
|
name = "cuda-pathfinder"
|
||||||
version = "1.5.4"
|
version = "1.5.5"
|
||||||
source = { registry = "https://pypi.org/simple" }
|
source = { registry = "https://pypi.org/simple" }
|
||||||
wheels = [
|
wheels = [
|
||||||
{ url = "https://files.pythonhosted.org/packages/11/d0/c177e29701cf1d3008d7d2b16b5fc626592ce13bd535f8795c5f57187e0e/cuda_pathfinder-1.5.4-py3-none-any.whl", hash = "sha256:9563d3175ce1828531acf4b94e1c1c7d67208c347ca002493e2654878b26f4b7", size = 51657, upload-time = "2026-04-27T22:42:07.712Z" },
|
{ url = "https://files.pythonhosted.org/packages/11/c8/26f2e4aae92f11522a96043892ba39a90eac610d5242523aa863212bc1c7/cuda_pathfinder-1.5.5-py3-none-any.whl", hash = "sha256:0228c023f95d1480f143ef5c8922d27a2ab052087a942e81dc289c9eb8f91689", size = 51671, upload-time = "2026-05-27T01:21:25.413Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
Reference in New Issue
Block a user