Includes core prod + GREEN/BLUE subsystems: - prod/ (BLUE harness, configs, scripts, docs) - nautilus_dolphin/ (GREEN Nautilus-native impl + dvae/ preserved) - adaptive_exit/ (AEM engine + models/bucket_assignments.pkl) - Observability/ (EsoF advisor, TUI, dashboards) - external_factors/ (EsoF producer) - mc_forewarning_qlabs_fork/ (MC regime/envelope) Excludes runtime caches, logs, backups, and reproducible artifacts per .gitignore.
497 lines
25 KiB
Python
Executable File
497 lines
25 KiB
Python
Executable File
"""Fraction Sweep + Sharpe-Adaptive Sizing Prototype — 55-Day Champion Window.
|
|
|
|
Two experiments in one script:
|
|
|
|
PART 1 — Static fraction sweep
|
|
Grid: fraction in [0.16, 0.18, 0.20, 0.22, 0.24, 0.26, 0.28, 0.30]
|
|
Full engine stack per run. Finds Kelly-optimal static fraction.
|
|
Kelly anchor: mean_pnl=+0.051%, sigma=0.908% (from summary_20260306_175651.json)
|
|
Full Kelly ~ mean/sigma^2 ~ 6.2% per trade. Half-Kelly ~ 3.1%.
|
|
|
|
PART 2 — Adaptive Sharpe Monitor Prototype
|
|
Simulates a live Sharpe monitor feeding into sizing.
|
|
Day by day: compute rolling 20-day realized Sharpe → fraction multiplier.
|
|
Elastic ceiling: base soft-ceiling=1.20x, apex ceiling=1.35x.
|
|
Ceiling expands toward apex when: ACB boost high + MC GREEN + low drawdown.
|
|
(Structural parallel: leverage has base=5x, soft-cap=6x governed by ACB/EsoF/MC.
|
|
Fraction has base_mult=1.0, soft-ceiling=1.20, apex=1.35 governed by Sharpe/ACB/MC/DD.)
|
|
Hysteresis: EWMA(5) on multiplier prevents day-to-day whipsaw.
|
|
|
|
IRON RULES:
|
|
- fraction_mult never exceeds 1.35 (apex ceiling, hard coded)
|
|
- DD > 12%: ceiling contracts to 1.00 (no boost under stress)
|
|
- MC ORANGE: ceiling contracts to 1.10
|
|
- Sizing mult is DAL-C — does NOT touch signal, ACB, MC gate
|
|
|
|
Saves:
|
|
run_logs/fraction_sweep_{TS}.csv (part 1: one row per fraction)
|
|
run_logs/sharpe_adaptive_{TS}.csv (part 2: one row per day — fraction_mult, rolling_sharpe, ceiling)
|
|
run_logs/fraction_sharpe_{TS}.json (full summary both parts)
|
|
"""
|
|
import sys, time, json, csv
|
|
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
|
from pathlib import Path
|
|
from datetime import datetime
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
|
|
print("Compiling numba kernels...")
|
|
t0c = time.time()
|
|
from nautilus_dolphin.nautilus.alpha_asset_selector import compute_irp_nb, compute_ars_nb, rank_assets_irp_nb
|
|
from nautilus_dolphin.nautilus.alpha_bet_sizer import compute_sizing_nb
|
|
from nautilus_dolphin.nautilus.alpha_signal_generator import check_dc_nb
|
|
from nautilus_dolphin.nautilus.ob_features import (
|
|
OBFeatureEngine, compute_imbalance_nb, compute_depth_1pct_nb,
|
|
compute_depth_quality_nb, compute_fill_probability_nb, compute_spread_proxy_nb,
|
|
compute_depth_asymmetry_nb, compute_imbalance_persistence_nb,
|
|
compute_withdrawal_velocity_nb, compute_market_agreement_nb, compute_cascade_signal_nb,
|
|
)
|
|
from nautilus_dolphin.nautilus.ob_provider import MockOBProvider
|
|
_p = np.array([1.0, 2.0, 3.0], dtype=np.float64)
|
|
compute_irp_nb(_p, -1); compute_ars_nb(1.0, 0.5, 0.01)
|
|
rank_assets_irp_nb(np.ones((10, 2), dtype=np.float64), 8, -1, 5, 500.0, 20, 0.20)
|
|
compute_sizing_nb(-0.03, -0.02, -0.05, 3.0, 0.5, 5.0, 0.20, True, True, 0.0,
|
|
np.zeros(4, dtype=np.int64), np.zeros(4, dtype=np.int64),
|
|
np.zeros(5, dtype=np.float64), 0, -1, 0.01, 0.04)
|
|
check_dc_nb(_p, 3, 1, 0.75)
|
|
_b = np.array([100.0, 200.0, 300.0, 400.0, 500.0], dtype=np.float64)
|
|
_a = np.array([110.0, 190.0, 310.0, 390.0, 510.0], dtype=np.float64)
|
|
compute_imbalance_nb(_b, _a); compute_depth_1pct_nb(_b, _a)
|
|
compute_depth_quality_nb(210.0, 200.0); compute_fill_probability_nb(1.0)
|
|
compute_spread_proxy_nb(_b, _a); compute_depth_asymmetry_nb(_b, _a)
|
|
compute_imbalance_persistence_nb(np.array([0.1, -0.1], dtype=np.float64), 2)
|
|
compute_withdrawal_velocity_nb(np.array([100.0, 110.0], dtype=np.float64), 1)
|
|
compute_market_agreement_nb(np.array([0.1, -0.05], dtype=np.float64), 2)
|
|
compute_cascade_signal_nb(np.array([-0.05, -0.15], dtype=np.float64), 2, -0.10)
|
|
print(f" JIT: {time.time()-t0c:.1f}s")
|
|
|
|
from nautilus_dolphin.nautilus.esf_alpha_orchestrator import NDAlphaEngine
|
|
from nautilus_dolphin.nautilus.adaptive_circuit_breaker import AdaptiveCircuitBreaker
|
|
from mc.mc_ml import DolphinForewarner
|
|
|
|
# ── Config ───────────────────────────────────────────────────────────────────────
|
|
VBT_DIR = Path(r"C:\Users\Lenovo\Documents\- DOLPHIN NG HD HCM TSF Predict\vbt_cache")
|
|
DATE_START = '2025-12-31'
|
|
DATE_END = '2026-02-25'
|
|
META_COLS = {'timestamp', 'scan_number', 'v50_lambda_max_velocity', 'v150_lambda_max_velocity',
|
|
'v300_lambda_max_velocity', 'v750_lambda_max_velocity', 'vel_div',
|
|
'instability_50', 'instability_150'}
|
|
MC_MODELS_DIR = str(Path(r"C:\Users\Lenovo\Documents\- DOLPHIN NG HD HCM TSF Predict\nautilus_dolphin\mc_results\models"))
|
|
|
|
BASE_FRACTION = 0.20
|
|
INITIAL_CAPITAL = 25000.0
|
|
|
|
BASE_ENGINE_KWARGS = dict(
|
|
initial_capital=INITIAL_CAPITAL, vel_div_threshold=-0.02, vel_div_extreme=-0.05,
|
|
min_leverage=0.5, max_leverage=5.0, leverage_convexity=3.0,
|
|
fraction=BASE_FRACTION, fixed_tp_pct=0.0095, stop_pct=1.0, max_hold_bars=120,
|
|
use_direction_confirm=True, dc_lookback_bars=7, dc_min_magnitude_bps=0.75,
|
|
dc_skip_contradicts=True, dc_leverage_boost=1.0, dc_leverage_reduce=0.5,
|
|
use_asset_selection=True, min_irp_alignment=0.45,
|
|
use_sp_fees=True, use_sp_slippage=True,
|
|
sp_maker_entry_rate=0.62, sp_maker_exit_rate=0.50,
|
|
use_ob_edge=True, ob_edge_bps=5.0, ob_confirm_rate=0.40,
|
|
lookback=100, use_alpha_layers=True, use_dynamic_leverage=True, seed=42,
|
|
)
|
|
MC_BASE_CFG = {
|
|
'trial_id': 0, 'vel_div_threshold': -0.020, 'vel_div_extreme': -0.050,
|
|
'use_direction_confirm': True, 'dc_lookback_bars': 7,
|
|
'dc_min_magnitude_bps': 0.75, 'dc_skip_contradicts': True,
|
|
'dc_leverage_boost': 1.00, 'dc_leverage_reduce': 0.50,
|
|
'vd_trend_lookback': 10, 'min_leverage': 0.50, 'max_leverage': 5.00,
|
|
'leverage_convexity': 3.00, 'fraction': BASE_FRACTION,
|
|
'use_alpha_layers': True, 'use_dynamic_leverage': True,
|
|
'fixed_tp_pct': 0.0095, 'stop_pct': 1.00, 'max_hold_bars': 120,
|
|
'use_sp_fees': True, 'use_sp_slippage': True,
|
|
'sp_maker_entry_rate': 0.62, 'sp_maker_exit_rate': 0.50,
|
|
'use_ob_edge': True, 'ob_edge_bps': 5.00, 'ob_confirm_rate': 0.40,
|
|
'ob_imbalance_bias': -0.09, 'ob_depth_scale': 1.00,
|
|
'use_asset_selection': True, 'min_irp_alignment': 0.45, 'lookback': 100,
|
|
'acb_beta_high': 0.80, 'acb_beta_low': 0.20, 'acb_w750_threshold_pct': 60,
|
|
}
|
|
OB_ASSETS = ["BTCUSDT", "ETHUSDT", "BNBUSDT", "SOLUSDT"]
|
|
|
|
# ── Elastic ceiling / Sharpe monitor logic ───────────────────────────────────────
|
|
MULT_SOFT_CEILING = 1.20 # base ceiling (analogous to leverage soft-cap 5x)
|
|
MULT_APEX_CEILING = 1.35 # apex ceiling (analogous to leverage hard-cap 6x)
|
|
SHARPE_LOOKBACK = 20 # rolling window (days)
|
|
EWMA_ALPHA = 0.18 # EWMA smoothing for mult (≈5-day half-life), prevents whipsaw
|
|
|
|
def compute_sizing_mult(rolling_sharpe, acb_boost, mc_status, current_drawdown):
|
|
"""
|
|
Returns (fraction_mult, effective_ceiling).
|
|
|
|
Fraction_mult: how much to scale BASE_FRACTION on this day.
|
|
Effective_ceiling: the live apex for this day (elastic — expands/contracts
|
|
with ACB boost, MC status, drawdown. Mirrors how leverage ceiling moves
|
|
from 5x baseline toward 6x when ACB/EsoF/MC warrant it.)
|
|
"""
|
|
# Base multiplier: continuous piecewise-linear on rolling Sharpe
|
|
if rolling_sharpe < 1.5:
|
|
base_mult = 0.85
|
|
elif rolling_sharpe < 2.0:
|
|
base_mult = 0.85 + (rolling_sharpe - 1.5) / 0.5 * 0.10 # 0.85 → 0.95
|
|
elif rolling_sharpe < 2.5:
|
|
base_mult = 0.95 + (rolling_sharpe - 2.0) / 0.5 * 0.05 # 0.95 → 1.00
|
|
elif rolling_sharpe < 3.0:
|
|
base_mult = 1.00 + (rolling_sharpe - 2.5) / 0.5 * 0.10 # 1.00 → 1.10
|
|
elif rolling_sharpe < 3.5:
|
|
base_mult = 1.10 + (rolling_sharpe - 3.0) / 0.5 * 0.10 # 1.10 → 1.20
|
|
else:
|
|
base_mult = 1.25 # exceptional — still capped by elastic ceiling
|
|
|
|
# ── Elastic ceiling ──────────────────────────────────────────────────────────
|
|
# Ceiling starts at SOFT_CEILING=1.20. Expands toward APEX_CEILING=1.35 when
|
|
# multiple conditions align. Each condition contributes a normalized "score"
|
|
# that linearly blends toward the apex headroom (0.15).
|
|
ceiling_headroom = MULT_APEX_CEILING - MULT_SOFT_CEILING # 0.15
|
|
expansion_score = 0.0
|
|
|
|
# ACB boost: strong eigenvalue-velocity signal warrants ceiling expansion
|
|
if acb_boost >= 1.55: expansion_score += 0.50 # strong/peak boost
|
|
elif acb_boost >= 1.35: expansion_score += 0.25 # moderate boost
|
|
|
|
# MC-Forewarner: green = safe operating zone
|
|
if mc_status == 'GREEN': expansion_score += 0.30
|
|
elif mc_status == 'ORANGE': expansion_score -= 0.60 # ORANGE compresses
|
|
|
|
# Drawdown: near peak capital = safe to size up; stressed = compress
|
|
if current_drawdown < 0.03: expansion_score += 0.20 # near-peak, fresh
|
|
elif current_drawdown < 0.07: expansion_score += 0.00 # neutral zone
|
|
elif current_drawdown > 0.10: expansion_score -= 0.40 # stressed
|
|
|
|
expansion_score = max(0.0, min(1.0, expansion_score))
|
|
effective_ceiling = MULT_SOFT_CEILING + expansion_score * ceiling_headroom
|
|
|
|
# Hard overrides (safety gates — always applied after expansion)
|
|
if mc_status == 'ORANGE': effective_ceiling = min(effective_ceiling, 1.10)
|
|
if current_drawdown > 0.12: effective_ceiling = min(effective_ceiling, 1.00)
|
|
effective_ceiling = min(effective_ceiling, MULT_APEX_CEILING) # never breach apex
|
|
|
|
return min(base_mult, effective_ceiling), effective_ceiling
|
|
|
|
|
|
def run_engine(fraction_override=None, adaptive=False, acb=None, forewarner=None,
|
|
pq_data=None, date_strings=None, vol_p60=None, ob_eng=None,
|
|
verbose=True):
|
|
"""
|
|
Run one full engine pass over 55 days.
|
|
fraction_override: fixed fraction for static sweep.
|
|
adaptive=True: Sharpe monitor adjusts engine.bet_sizer.base_fraction per day.
|
|
Returns: dict of summary stats + per-day log.
|
|
"""
|
|
frac = fraction_override if fraction_override is not None else BASE_FRACTION
|
|
kw = dict(BASE_ENGINE_KWARGS, fraction=frac)
|
|
engine = NDAlphaEngine(**kw)
|
|
engine.set_ob_engine(ob_eng)
|
|
engine.set_acb(acb)
|
|
engine.set_mc_forewarner(forewarner, MC_BASE_CFG)
|
|
engine.set_esoteric_hazard_multiplier(0.0)
|
|
|
|
daily_pnl = [] # rolling buffer for Sharpe monitor
|
|
daily_log = [] # per-day record (for adaptive mode)
|
|
ewma_mult = 1.0 # EWMA-smoothed multiplier (hysteresis)
|
|
peak_cap = INITIAL_CAPITAL
|
|
|
|
for ds in date_strings:
|
|
df, acols, dvol = pq_data[ds]
|
|
vol_ok = np.where(np.isfinite(dvol), dvol > vol_p60, False)
|
|
|
|
if adaptive:
|
|
# ── Compute rolling Sharpe from prior SHARPE_LOOKBACK days ──────────
|
|
if len(daily_pnl) >= 5:
|
|
window = np.array(daily_pnl[-SHARPE_LOOKBACK:])
|
|
roll_sh = float(window.mean() / window.std() * np.sqrt(252)) if window.std() > 0 else 0.0
|
|
else:
|
|
roll_sh = 0.0 # warmup: no adjustment for first 5 days
|
|
|
|
# Current drawdown
|
|
cur_dd = (peak_cap - engine.capital) / peak_cap if peak_cap > 0 else 0.0
|
|
|
|
# ACB boost and MC status for this date
|
|
_acb_info = acb.get_boost_for_date(ds) if hasattr(acb, 'get_boost_for_date') else {}
|
|
acb_boost_today = _acb_info.get('boost', 1.0) if isinstance(_acb_info, dict) else float(_acb_info)
|
|
mc_status_today = 'GREEN' # MC-Forewarner interventions tracked separately
|
|
|
|
raw_mult, eff_ceiling = compute_sizing_mult(
|
|
roll_sh, acb_boost_today, mc_status_today, cur_dd)
|
|
|
|
# EWMA smoothing: prevent whipsaw (5-day half-life)
|
|
ewma_mult = EWMA_ALPHA * raw_mult + (1 - EWMA_ALPHA) * ewma_mult
|
|
ewma_mult = max(0.80, min(ewma_mult, eff_ceiling)) # hard bounds
|
|
|
|
# Apply to engine live
|
|
engine.bet_sizer.base_fraction = BASE_FRACTION * ewma_mult
|
|
else:
|
|
roll_sh = None; raw_mult = None; ewma_mult = 1.0; eff_ceiling = MULT_SOFT_CEILING
|
|
|
|
r = engine.process_day(ds, df, acols, vol_regime_ok=vol_ok)
|
|
|
|
pnl_today = r.get('pnl', 0.0)
|
|
daily_pnl.append(pnl_today)
|
|
if engine.capital > peak_cap:
|
|
peak_cap = engine.capital
|
|
|
|
if adaptive:
|
|
daily_log.append({
|
|
'date': ds,
|
|
'pnl': pnl_today,
|
|
'capital': engine.capital,
|
|
'trades': r.get('trades', 0),
|
|
'rolling_sharpe': round(roll_sh, 3),
|
|
'raw_mult': round(raw_mult, 4) if raw_mult is not None else None,
|
|
'ewma_mult': round(ewma_mult, 4),
|
|
'effective_ceiling': round(eff_ceiling, 4),
|
|
'applied_fraction': round(BASE_FRACTION * ewma_mult, 4),
|
|
'drawdown_pct': round((peak_cap - engine.capital) / peak_cap * 100, 2),
|
|
})
|
|
|
|
# Summary stats
|
|
tr = engine.trade_history
|
|
wins = [t for t in tr if t.pnl_absolute > 0]
|
|
losses = [t for t in tr if t.pnl_absolute <= 0]
|
|
gw = sum(t.pnl_absolute for t in wins)
|
|
gl = abs(sum(t.pnl_absolute for t in losses))
|
|
roi = (engine.capital - INITIAL_CAPITAL) / INITIAL_CAPITAL * 100.0
|
|
pf = gw / gl if gl > 0 else 999.0
|
|
wr = len(wins) / len(tr) * 100.0 if tr else 0.0
|
|
pnls = np.array(daily_pnl)
|
|
sharpe = float(pnls.mean() / pnls.std() * np.sqrt(252)) if pnls.std() > 0 else 0.0
|
|
max_dd = max((peak_cap - engine.capital) / peak_cap * 100.0, 0.0)
|
|
# proper DD scan
|
|
peak2 = INITIAL_CAPITAL; max_dd2 = 0.0
|
|
for cap in [r.get('capital', INITIAL_CAPITAL) for r in [{'capital': INITIAL_CAPITAL}]]:
|
|
pass # use daily_log or just the final
|
|
# Recompute DD properly from pnl series
|
|
running_cap = INITIAL_CAPITAL
|
|
pk = INITIAL_CAPITAL; max_dd_proper = 0.0
|
|
for p in daily_pnl:
|
|
running_cap += p
|
|
if running_cap > pk: pk = running_cap
|
|
dd = (pk - running_cap) / pk * 100.0
|
|
if dd > max_dd_proper: max_dd_proper = dd
|
|
|
|
return {
|
|
'roi': roi, 'pf': pf, 'dd': max_dd_proper, 'sharpe': sharpe,
|
|
'wr': wr, 'n_trades': len(tr), 'capital': engine.capital,
|
|
'daily_log': daily_log,
|
|
}
|
|
|
|
|
|
# ── Shared setup (load once, reuse across all runs) ──────────────────────────────
|
|
print("\nLoading MC-Forewarner...")
|
|
forewarner = DolphinForewarner(models_dir=MC_MODELS_DIR)
|
|
|
|
parquet_files = sorted(
|
|
p for p in VBT_DIR.glob("*.parquet")
|
|
if 'catalog' not in str(p) and DATE_START <= p.stem <= DATE_END
|
|
)
|
|
date_strings = [pf.stem for pf in parquet_files]
|
|
print(f"Dates: {len(parquet_files)} ({date_strings[0]} to {date_strings[-1]})")
|
|
|
|
acb = AdaptiveCircuitBreaker()
|
|
acb.preload_w750(date_strings)
|
|
print(f"ACB w750 p60: {acb._w750_threshold:.6f}")
|
|
|
|
all_vols = []
|
|
for pf in parquet_files[:2]:
|
|
df = pd.read_parquet(pf)
|
|
if 'BTCUSDT' not in df.columns: continue
|
|
pr = df['BTCUSDT'].values
|
|
for i in range(60, len(pr)):
|
|
seg = pr[max(0, i-50):i]
|
|
if len(seg) < 10: continue
|
|
v = float(np.std(np.diff(seg)/seg[:-1]))
|
|
if v > 0: all_vols.append(v)
|
|
vol_p60 = float(np.percentile(all_vols, 60))
|
|
print(f"Vol p60: {vol_p60:.6f}")
|
|
|
|
print(f"Pre-loading {len(parquet_files)} parquets...")
|
|
t_load = time.time()
|
|
pq_data = {}
|
|
for pf in parquet_files:
|
|
df = pd.read_parquet(pf)
|
|
ac = [c for c in df.columns if c not in META_COLS]
|
|
bp = df['BTCUSDT'].values if 'BTCUSDT' in df.columns else None
|
|
dv = np.full(len(df), np.nan)
|
|
if bp is not None:
|
|
for i in range(50, len(bp)):
|
|
seg = bp[max(0, i-50):i]
|
|
if len(seg) < 10: continue
|
|
dv[i] = float(np.std(np.diff(seg)/seg[:-1]))
|
|
pq_data[pf.stem] = (df, ac, dv)
|
|
print(f" Done in {time.time()-t_load:.1f}s")
|
|
|
|
_mock_ob = MockOBProvider(
|
|
imbalance_bias=-0.09, depth_scale=1.0, assets=OB_ASSETS,
|
|
imbalance_biases={"BTCUSDT": -0.086, "ETHUSDT": -0.092,
|
|
"BNBUSDT": +0.05, "SOLUSDT": +0.05},
|
|
)
|
|
ob_eng = OBFeatureEngine(_mock_ob)
|
|
ob_eng.preload_date("mock", OB_ASSETS)
|
|
|
|
shared = dict(acb=acb, forewarner=forewarner, pq_data=pq_data,
|
|
date_strings=date_strings, vol_p60=vol_p60, ob_eng=ob_eng)
|
|
|
|
# ════════════════════════════════════════════════════════════════════════════════
|
|
# PART 1 — Static Fraction Sweep
|
|
# ════════════════════════════════════════════════════════════════════════════════
|
|
FRACTION_GRID = [0.16, 0.18, 0.20, 0.22, 0.24, 0.26, 0.28, 0.30]
|
|
BASELINE_FRAC = 0.20
|
|
RUN_PART1 = False # already have sweep results — set True to re-run
|
|
|
|
print(f"\n{'='*70}")
|
|
print(f" PART 1 — STATIC FRACTION SWEEP {'(SKIPPED — RUN_PART1=False)' if not RUN_PART1 else ''}")
|
|
print(f" Grid: {FRACTION_GRID}")
|
|
print(f" Kelly anchor: mean=+0.051%/trade, sigma=0.908% → full-Kelly~6.2%, half-Kelly~3.1%")
|
|
print(f"{'='*70}\n")
|
|
|
|
sweep_results = []
|
|
t_sweep = time.time()
|
|
# Hardcoded Part 1 results from prior run (fraction_sharpe_adaptive_20260306_183347.log)
|
|
_prior_sweep = [
|
|
{'fraction':0.16,'roi':44.90,'pf':1.1559,'dd':11.86,'sharpe':2.617,'wr':49.6,'n_trades':2138,'capital':25000+25000*0.4490},
|
|
{'fraction':0.18,'roi':51.02,'pf':1.1524,'dd':13.39,'sharpe':2.554,'wr':49.6,'n_trades':2138,'capital':25000+25000*0.5102},
|
|
{'fraction':0.20,'roi':57.18,'pf':1.1487,'dd':14.94,'sharpe':2.490,'wr':49.6,'n_trades':2138,'capital':25000+25000*0.5718},
|
|
{'fraction':0.22,'roi':63.38,'pf':1.1450,'dd':16.50,'sharpe':2.426,'wr':49.6,'n_trades':2138,'capital':25000+25000*0.6338},
|
|
{'fraction':0.24,'roi':69.59,'pf':1.1413,'dd':18.07,'sharpe':2.361,'wr':49.6,'n_trades':2138,'capital':25000+25000*0.6959},
|
|
{'fraction':0.26,'roi':75.79,'pf':1.1376,'dd':19.65,'sharpe':2.295,'wr':49.6,'n_trades':2138,'capital':25000+25000*0.7579},
|
|
{'fraction':0.28,'roi':81.96,'pf':1.1338,'dd':21.24,'sharpe':2.230,'wr':49.6,'n_trades':2138,'capital':25000+25000*0.8196},
|
|
{'fraction':0.30,'roi':88.08,'pf':1.1301,'dd':22.84,'sharpe':2.165,'wr':49.6,'n_trades':2138,'capital':25000+25000*0.8808},
|
|
]
|
|
if not RUN_PART1:
|
|
sweep_results = _prior_sweep
|
|
baseline_frac = next(r for r in sweep_results if abs(r['fraction'] - BASELINE_FRAC) < 1e-9)
|
|
best_roi_frac = max(sweep_results, key=lambda r: r['roi'])
|
|
best_pf_frac = max(sweep_results, key=lambda r: r['pf'])
|
|
best_sh_frac = max(sweep_results, key=lambda r: r['sharpe'])
|
|
print(f" (Using cached results from prior run)")
|
|
else:
|
|
for frac in FRACTION_GRID:
|
|
t0 = time.time()
|
|
res = run_engine(fraction_override=frac, adaptive=False, **shared)
|
|
marker = " <- BASELINE" if abs(frac - BASELINE_FRAC) < 1e-9 else ""
|
|
print(f" frac={frac:.2f} ROI={res['roi']:+7.2f}% PF={res['pf']:.4f} "
|
|
f"DD={res['dd']:5.2f}% Sh={res['sharpe']:.3f} WR={res['wr']:.1f}% "
|
|
f"T={res['n_trades']} ({time.time()-t0:.0f}s){marker}")
|
|
sys.stdout.flush()
|
|
sweep_results.append({'fraction': frac, **{k: v for k, v in res.items() if k != 'daily_log'}})
|
|
|
|
best_roi_frac = max(sweep_results, key=lambda r: r['roi'])
|
|
best_pf_frac = max(sweep_results, key=lambda r: r['pf'])
|
|
best_sh_frac = max(sweep_results, key=lambda r: r['sharpe'])
|
|
baseline_frac = next(r for r in sweep_results if abs(r['fraction'] - BASELINE_FRAC) < 1e-9)
|
|
|
|
print(f"\n Static Sweep Summary ({(time.time()-t_sweep)/60:.1f}min):")
|
|
print(f" Baseline (0.20): ROI={baseline_frac['roi']:+.2f}% PF={baseline_frac['pf']:.4f} "
|
|
f"Sh={baseline_frac['sharpe']:.3f} DD={baseline_frac['dd']:.2f}%")
|
|
print(f" Best ROI: frac={best_roi_frac['fraction']:.2f} ROI={best_roi_frac['roi']:+.2f}% "
|
|
f"ΔROI={best_roi_frac['roi']-baseline_frac['roi']:+.2f}%")
|
|
print(f" Best PF: frac={best_pf_frac['fraction']:.2f} PF={best_pf_frac['pf']:.4f}")
|
|
print(f" Best Sh: frac={best_sh_frac['fraction']:.2f} Sh={best_sh_frac['sharpe']:.3f}")
|
|
|
|
# ════════════════════════════════════════════════════════════════════════════════
|
|
# PART 2 — Adaptive Sharpe Monitor Prototype
|
|
# ════════════════════════════════════════════════════════════════════════════════
|
|
print(f"\n{'='*70}")
|
|
print(f" PART 2 — ADAPTIVE SHARPE MONITOR PROTOTYPE")
|
|
print(f" Base fraction: {BASE_FRACTION} | Soft ceiling: {MULT_SOFT_CEILING}x "
|
|
f"| Apex ceiling: {MULT_APEX_CEILING}x")
|
|
print(f" Rolling Sharpe window: {SHARPE_LOOKBACK} days | EWMA alpha: {EWMA_ALPHA}")
|
|
print(f" Elastic ceiling: expands toward 1.35x when ACB-boost + MC-GREEN + low-DD align")
|
|
print(f"{'='*70}\n")
|
|
|
|
t_adaptive = time.time()
|
|
adaptive_res = run_engine(fraction_override=None, adaptive=True, **shared)
|
|
|
|
print(f"\n Adaptive vs Baseline:")
|
|
print(f" Baseline (fixed 0.20): ROI={baseline_frac['roi']:+.2f}% PF={baseline_frac['pf']:.4f} "
|
|
f"DD={baseline_frac['dd']:.2f}% Sh={baseline_frac['sharpe']:.3f}")
|
|
print(f" Adaptive Sharpe-monitor: ROI={adaptive_res['roi']:+.2f}% PF={adaptive_res['pf']:.4f} "
|
|
f"DD={adaptive_res['dd']:.2f}% Sh={adaptive_res['sharpe']:.3f}")
|
|
print(f" ΔROI={adaptive_res['roi']-baseline_frac['roi']:+.2f}% "
|
|
f"ΔSh={adaptive_res['sharpe']-baseline_frac['sharpe']:+.3f} "
|
|
f"ΔDD={adaptive_res['dd']-baseline_frac['dd']:+.2f}%")
|
|
print(f" ({(time.time()-t_adaptive):.0f}s)")
|
|
|
|
# Print adaptive day-by-day summary
|
|
print(f"\n Adaptive daily log (selected):")
|
|
print(f" {'Date':>12} {'PnL':>8} {'Cap':>10} {'RollSh':>7} {'Mult(EWMA)':>10} "
|
|
f"{'Ceiling':>7} {'ApplFrac':>9} {'DD%':>6}")
|
|
for row in adaptive_res['daily_log']:
|
|
if row['rolling_sharpe'] != 0.0 or row == adaptive_res['daily_log'][-1]:
|
|
print(f" {row['date']:>12} {row['pnl']:>+8.1f} {row['capital']:>10.0f} "
|
|
f"{row['rolling_sharpe']:>7.3f} {row['ewma_mult']:>10.4f} "
|
|
f"{row['effective_ceiling']:>7.4f} {row['applied_fraction']:>9.4f} "
|
|
f"{row['drawdown_pct']:>6.2f}%")
|
|
|
|
# Fraction distribution in adaptive run
|
|
if adaptive_res['daily_log']:
|
|
fracs = [r['applied_fraction'] for r in adaptive_res['daily_log'] if r['applied_fraction']]
|
|
print(f"\n Adaptive fraction stats:")
|
|
print(f" mean={np.mean(fracs):.4f} min={np.min(fracs):.4f} max={np.max(fracs):.4f} "
|
|
f"p25={np.percentile(fracs,25):.4f} p75={np.percentile(fracs,75):.4f}")
|
|
ceilings = [r['effective_ceiling'] for r in adaptive_res['daily_log']]
|
|
print(f" Elastic ceiling stats:")
|
|
print(f" mean={np.mean(ceilings):.4f} min={np.min(ceilings):.4f} max={np.max(ceilings):.4f} "
|
|
f"days-at-apex={sum(1 for c in ceilings if c >= MULT_APEX_CEILING - 0.001)}/{len(ceilings)}")
|
|
|
|
# ── Save ─────────────────────────────────────────────────────────────────────────
|
|
ts = datetime.now().strftime('%Y%m%d_%H%M%S')
|
|
run_dir = Path(__file__).parent / 'run_logs'
|
|
run_dir.mkdir(exist_ok=True)
|
|
|
|
# Part 1 CSV
|
|
with open(run_dir / f'fraction_sweep_{ts}.csv', 'w', newline='') as f:
|
|
keys = [k for k in sweep_results[0] if k != 'daily_log']
|
|
w = csv.DictWriter(f, fieldnames=keys)
|
|
w.writeheader()
|
|
w.writerows([{k: r[k] for k in keys} for r in sweep_results])
|
|
|
|
# Part 2 CSV (daily adaptive log)
|
|
if adaptive_res['daily_log']:
|
|
with open(run_dir / f'sharpe_adaptive_{ts}.csv', 'w', newline='') as f:
|
|
w = csv.DictWriter(f, fieldnames=list(adaptive_res['daily_log'][0].keys()))
|
|
w.writeheader(); w.writerows(adaptive_res['daily_log'])
|
|
|
|
# JSON summary
|
|
summary = {
|
|
'experiment': 'fraction_sweep_and_sharpe_adaptive_55day',
|
|
'date_range': f'{DATE_START}_to_{DATE_END}',
|
|
'base_fraction': BASE_FRACTION,
|
|
'fixed_tp_pct': 0.0095,
|
|
'kelly_anchor': {'mean_pnl_pct': 0.051, 'sigma_pct': 0.908,
|
|
'full_kelly_frac': 0.062, 'half_kelly_frac': 0.031},
|
|
'elastic_ceiling': {
|
|
'soft_ceiling': MULT_SOFT_CEILING, 'apex_ceiling': MULT_APEX_CEILING,
|
|
'sharpe_lookback_days': SHARPE_LOOKBACK, 'ewma_alpha': EWMA_ALPHA,
|
|
'doctrine': 'ceiling expands ACB-boost + MC-GREEN + low-DD (mirrors leverage 5x→6x)',
|
|
},
|
|
'part1_sweep': {
|
|
'grid': FRACTION_GRID,
|
|
'baseline': baseline_frac,
|
|
'best_roi': best_roi_frac,
|
|
'best_pf': best_pf_frac,
|
|
'best_sharpe': best_sh_frac,
|
|
'all': sweep_results,
|
|
},
|
|
'part2_adaptive': {
|
|
'roi': adaptive_res['roi'], 'pf': adaptive_res['pf'],
|
|
'dd': adaptive_res['dd'], 'sharpe': adaptive_res['sharpe'],
|
|
'wr': adaptive_res['wr'], 'n_trades': adaptive_res['n_trades'],
|
|
'delta_roi_vs_baseline': adaptive_res['roi'] - baseline_frac['roi'],
|
|
'delta_sharpe_vs_baseline': adaptive_res['sharpe'] - baseline_frac['sharpe'],
|
|
},
|
|
'run_ts': ts,
|
|
}
|
|
with open(run_dir / f'fraction_sharpe_{ts}.json', 'w') as f:
|
|
json.dump(summary, f, indent=2)
|
|
|
|
print(f"\nSaved:")
|
|
print(f" run_logs/fraction_sweep_{ts}.csv")
|
|
print(f" run_logs/sharpe_adaptive_{ts}.csv")
|
|
print(f" run_logs/fraction_sharpe_{ts}.json")
|
|
print(f"\nTotal runtime: {(time.time()-t0c)/60:.1f}min")
|