ac6f3766b0
GOAL: limitare le perdite delle fade in regime sfavorevole. Diagnosi (3022 trade): le perdite/stop si concentrano nel regime PERSISTENTE (hurst>0.55: stop-rate 43% vs 21% anti-persistente), NON in bassa vol (low-vol e' net positivo). Ricerca web + workflow 11 agenti: l'UNICO meccanismo che riduce DD senza uccidere l'edge e' il filtro Hurst (ADX, vol-expansion, time-stop, ER, vol-target falliscono il gate FR01). Test esterni ADX/vol-expansion NON si replicano su queste fade crypto. TEST DECISIVO PORT06 (gate FR01) SUPERATO: Hurst-skip h<0.55 sulle 6 fade -> FULL Sharpe 6.62->6.76, FULL DD 4.10%->2.39% (quasi dimezzato), OOS Sharpe 8.89->9.15. Migliora il portafoglio (a differenza di FR01 che diluiva). Implementazione: hurst_skip_mask in fade_base.py (rolling-Hurst causale dalle SOLE close -> nessun feed dati esterno, deployabile inline dal worker) + param hurst_max (default None=off) in MR01/MR02/MR07. Test: test_hurst_lossguard.py. Default off -> zero impatto su backtest/parita'/live finche' non attivato. FIX collaterale: regime_fetcher/regime_lab scrivevano DVOL/funding/feature in data/raw/ -> inquinavano la discovery asset del backtest (rompeva il regression-lock PORT06). Spostati in data/regime/ (gitignored). Suite: 54 passed (lock incluso). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
57 lines
2.9 KiB
Python
57 lines
2.9 KiB
Python
import sys; sys.path.insert(0,".")
|
|
import numpy as np, pandas as pd, importlib
|
|
from scripts.analysis.combine_portfolio import IDX, SPLIT, INIT, _norm, metrics, port_returns, build_trades
|
|
from src.portfolio.sleeves import all_sleeve_equities
|
|
from scripts.analysis.regime_lab import load_features
|
|
|
|
def load_strat(mod):
|
|
m=importlib.import_module(mod)
|
|
return next(v() for k,v in vars(m).items() if isinstance(v,type) and hasattr(v,'generate_signals') and getattr(v,'__module__','')==m.__name__)
|
|
FADES={"MR01":("scripts.strategies.MR01_bollinger_fade",dict(bb_window=50,k=2.5,sl_atr=2.0,max_bars=24,trend_max=3.0)),
|
|
"MR02":("scripts.strategies.MR02_donchian_fade",dict(n=20,sl_atr=2.0,max_bars=24,trend_max=3.0)),
|
|
"MR07":("scripts.strategies.MR07_return_reversal",dict(n=50,k=3.5,tp_atr=2.0,sl_atr=1.5,max_bars=24,trend_max=3.0))}
|
|
FEE=0.001; LEV=3; POS=0.15
|
|
|
|
def fade_equity_filtered(code, asset, hurst_thr=None):
|
|
"""equity giornaliera dello sleeve fade, opz. filtrata Hurst<thr (skip hurst>=thr). Convenzione fade_daily_equity."""
|
|
mod,par=FADES[code]; s=load_strat(mod)
|
|
df=load_features(asset,"1h"); ts=pd.to_datetime(df['timestamp'],unit='ms',utc=True)
|
|
h=df['high'].values; l=df['low'].values; c=df['close'].values; hur=df['hurst'].values
|
|
eq=np.full(len(c),INIT,float); cap=INIT; last=-1
|
|
for sg in s.generate_signals(df,ts,**par):
|
|
i=sg.idx
|
|
if i<=last: continue
|
|
if hurst_thr is not None and not np.isnan(hur[i]) and hur[i]>=hurst_thr: continue # FILTRO
|
|
d=sg.direction; tp=sg.metadata['tp']; sl=sg.metadata['sl']; mb=sg.metadata['max_bars']
|
|
j=min(i+mb,len(c)-1); exit_p=c[j]
|
|
for t in range(i+1,j+1):
|
|
if d==1:
|
|
if l[t]<=sl: exit_p=sl;j=t;break
|
|
if h[t]>=tp: exit_p=tp;j=t;break
|
|
else:
|
|
if h[t]>=sl: exit_p=sl;j=t;break
|
|
if l[t]<=tp: exit_p=tp;j=t;break
|
|
ret=(exit_p-c[i])/c[i]*d*LEV-FEE*LEV
|
|
cap=max(cap+cap*POS*ret,10.0); eq[j:]=cap; last=j
|
|
sser=pd.Series(eq,index=ts).resample("1D").last().reindex(IDX).ffill().bfill()
|
|
return _norm(sser)
|
|
|
|
base=all_sleeve_equities()
|
|
fade_ids=["MR01_BTC","MR02_BTC","MR07_BTC","MR01_ETH","MR02_ETH","MR07_ETH"]
|
|
|
|
def port(members):
|
|
dr=port_returns(members); return metrics(dr), metrics(dr,lo=SPLIT)
|
|
|
|
# baseline PORT06
|
|
fB,oB=port(base)
|
|
print(f"PORT06 baseline (17 sleeve): FULL Sharpe {fB['sharpe']:.2f} DD {fB['dd']:.2f}% | OOS Sharpe {oB['sharpe']:.2f} DD {oB['dd']:.2f}% ret {oB['ret']:+.0f}%")
|
|
|
|
# sostituisci le 6 fade con versione Hurst-skip
|
|
for thr in (0.55, 0.50):
|
|
filt=dict(base)
|
|
for fid in fade_ids:
|
|
code,asset=fid.split("_")
|
|
filt[fid]=fade_equity_filtered(code,asset,hurst_thr=thr)
|
|
fF,oF=port(filt)
|
|
print(f"PORT06 + Hurst-skip h<{thr} sulle fade: FULL Sharpe {fF['sharpe']:.2f} DD {fF['dd']:.2f}% | OOS Sharpe {oF['sharpe']:.2f} DD {oF['dd']:.2f}% ret {oF['ret']:+.0f}%")
|