#!/usr/bin/env python3
"""
Quant Research Suite — 15-Candidate Low-Turnover Swing & Orthogonal Portfolio Blend Screener
- Design Philosophy (informed by 18-idea screen):
  1. High-turnover intraday MR/session engines died from 0.24% round-trip fees (1,000+ trades).
     All 15 candidates here are multi-day swing engines or multi-engine portfolio blends.
  2. Evaluated strictly against the identical NO-DIAL EMA(20)/EMA(50) baseline on BTC & ETH (2018-2026).
  3. Stage 2 automatically runs 100-run date-shuffled placebos and 0.5x/1.5x parameter-neighbour
     plateau checks on every candidate passing the dual-half, MaxDD, and yearly breadth gates.
- Data Sources (strictly approved URLs + yfinance):
  * https://osom-boba.pages.dev/colab/btc_1h_full.csv.gz
  * https://osom-boba.pages.dev/colab/eth_1h_full.csv.gz
  * https://osom-boba.pages.dev/colab/btc_funding_8h.csv
  * https://osom-boba.pages.dev/colab/btc_etf_flows.csv.gz
  * Gold (GC=F) & DXY (DX-Y.NYB) via yfinance (MultiIndex flattened, 1-day lag)
- Rules: 0.12% fee/side | 1.0% total risk budget | 2.0x daily ATR(14) stop | 3.0x notional cap | zero lookahead.
"""

import warnings
warnings.filterwarnings("ignore")

import numpy as np
import pandas as pd
import yfinance as yf

UA_OPTS = {"User-Agent": "Mozilla/5.0"}
FEE_PER_SIDE = 0.0012
BASE_RISK = 0.01
ATR_MULT = 2.0
MAX_LEV = 3.0


# ==============================================================================
# 1. DATA LOADING
# ==============================================================================

def load_ohlcv_1h(url, label):
    print(f"Loading {label} 1h from {url}...")
    df = pd.read_csv(url, storage_options=UA_OPTS)
    df.columns = [c.strip().lower() for c in df.columns]
    dt = pd.to_datetime(df["time"], unit="ms", utc=True)
    out = pd.DataFrame({
        "open": df["open"].astype(float).values,
        "high": df["high"].astype(float).values,
        "low": df["low"].astype(float).values,
        "close": df["close"].astype(float).values,
        "volume": df["volume"].astype(float).values,
    }, index=dt)
    out = out[~out.index.duplicated(keep="first")].sort_index()
    out = out[out.index >= "2017-06-01"]
    print(f"  -> {label}: {len(out)} bars ({out.index.min().date()} to {out.index.max().date()})")
    return out


def load_funding_8h(url):
    print(f"Loading 8h funding from {url}...")
    df = pd.read_csv(url, storage_options=UA_OPTS)
    df.columns = [c.strip().lower() for c in df.columns]
    time_col = "time" if "time" in df.columns else [c for c in df.columns if "time" in c or "date" in c][0]
    dt = pd.to_datetime(df[time_col], unit="ms", utc=True)
    rate_cols = [c for c in df.columns if any(k in c for k in ["fund", "rate", "val"])]
    if not rate_cols:
        rate_cols = [c for c in df.columns if c not in [time_col, "source", "symbol"]]
    s = pd.Series(pd.to_numeric(df[rate_cols[0]], errors="coerce").values, index=dt).dropna()
    s = s[~s.index.duplicated(keep="last")].sort_index()
    print(f"  -> Funding: {len(s)} 8h obs ({s.index.min().date()} to {s.index.max().date()})")
    return s


def load_etf_flows(url):
    print(f"Loading ETF flows from {url}...")
    df = pd.read_csv(url, storage_options=UA_OPTS)
    df.columns = [c.strip().lower() for c in df.columns]
    time_col = "time" if "time" in df.columns else [c for c in df.columns if "time" in c or "date" in c][0]
    dt = pd.to_datetime(df[time_col], utc=True)
    num_cols = [c for c in df.columns if c not in [time_col, "source", "symbol"]]
    prefer = [c for c in num_cols if any(k in c for k in ["net", "total", "flow"])]
    col = prefer[0] if prefer else num_cols[0]
    s = pd.Series(pd.to_numeric(df[col], errors="coerce").values, index=dt).dropna()
    s.index = s.index.floor("D")
    s = s.groupby(level=0).sum().sort_index()
    print(f"  -> ETF flows ({col}): {len(s)} days ({s.index.min().date()} to {s.index.max().date()})")
    return s


def load_macro_yf(start="2017-01-01"):
    tickers = {"gold": "GC=F"}
    out = {}
    for k, tkr in tickers.items():
        print(f"Downloading {k.upper()} ({tkr}) via yfinance...")
        raw = yf.download(tkr, start=start, progress=False, auto_adjust=True)
        if isinstance(raw.columns, pd.MultiIndex):
            raw.columns = raw.columns.get_level_values(0)
        raw.columns = [c.strip().lower() for c in raw.columns]
        s = raw["close"].astype(float)
        if s.index.tz is None:
            s.index = s.index.tz_localize("UTC")
        else:
            s.index = s.index.tz_convert("UTC")
        s.index = s.index.floor("D")
        out[k] = s.groupby(level=0).last().sort_index()
        print(f"  -> {k.upper()}: {len(out[k])} daily rows")
    return pd.DataFrame(out)


# ==============================================================================
# 2. FEATURE ENGINEERING (STRICT NO-LOOKAHEAD, .VALUES ONLY)
# ==============================================================================

def build_features(df_1h, fund_8h, etf_daily, macro_daily, peer_1h=None):
    n = len(df_1h)
    h = df_1h["high"].values
    l = df_1h["low"].values
    c = df_1h["close"].values
    v = df_1h["volume"].values

    # Daily bars & indicators (shifted +1 day so day D close is actionable on day D+1)
    daily = df_1h.resample("1D").agg({"open": "first", "high": "max", "low": "min", "close": "last", "volume": "sum"}).dropna()
    daily.index = daily.index.floor("D")
    dh, dl, dc, dv = daily["high"].values, daily["low"].values, daily["close"].values, daily["volume"].values
    d_prev_c = np.roll(dc, 1)
    d_prev_c[0] = dc[0]
    d_tr = np.maximum(dh - dl, np.maximum(np.abs(dh - d_prev_c), np.abs(dl - d_prev_c)))
    d_atr14 = pd.Series(d_tr).rolling(14).mean().values

    m_al = macro_daily.reindex(daily.index, method="ffill")
    gold_c = m_al["gold"].values
    etf_al = etf_daily.reindex(daily.index).fillna(0.0).values

    # Kaufman Efficiency Ratio (10d & 20d)
    net_10 = np.abs(pd.Series(dc).diff(10).values)
    path_10 = pd.Series(np.abs(np.diff(dc, prepend=dc[0]))).rolling(10).sum().values
    er10 = net_10 / np.maximum(path_10, 1e-9)

    net_20 = np.abs(pd.Series(dc).diff(20).values)
    path_20 = pd.Series(np.abs(np.diff(dc, prepend=dc[0]))).rolling(20).sum().values
    er20 = net_20 / np.maximum(path_20, 1e-9)

    # Peer (ETH/BTC) daily return for cross-crypto lead-lag
    if peer_1h is not None:
        peer_d = peer_1h["close"].resample("1D").last().reindex(daily.index, method="ffill").values
        peer_ret5 = pd.Series(peer_d).pct_change(5).values
        peer_ret10 = pd.Series(peer_d).pct_change(10).values
    else:
        peer_ret5 = np.zeros(len(daily))
        peer_ret10 = np.zeros(len(daily))

    daily_df = pd.DataFrame({
        "d_close": dc,
        "d_atr14": d_atr14,
        "d_ema10": pd.Series(dc).ewm(span=10, adjust=False).mean().values,
        "d_ema20": pd.Series(dc).ewm(span=20, adjust=False).mean().values,
        "d_ema30": pd.Series(dc).ewm(span=30, adjust=False).mean().values,
        "d_ema50": pd.Series(dc).ewm(span=50, adjust=False).mean().values,
        "d_ema75": pd.Series(dc).ewm(span=75, adjust=False).mean().values,
        "d_sma100": pd.Series(dc).rolling(100).mean().values,
        "d_sma200": pd.Series(dc).rolling(200).mean().values,
        "d_hh10": pd.Series(dh).rolling(10).max().values,
        "d_ll10": pd.Series(dl).rolling(10).min().values,
        "d_hh20": pd.Series(dh).rolling(20).max().values,
        "d_ll20": pd.Series(dl).rolling(20).min().values,
        "d_hh30": pd.Series(dh).rolling(30).max().values,
        "d_ll30": pd.Series(dl).rolling(30).min().values,
        "d_hh40": pd.Series(dh).rolling(40).max().values,
        "d_ll40": pd.Series(dl).rolling(40).min().values,
        "d_ret5": pd.Series(dc).pct_change(5).values,
        "d_ret10": pd.Series(dc).pct_change(10).values,
        "d_ret15": pd.Series(dc).pct_change(15).values,
        "d_ret20": pd.Series(dc).pct_change(20).values,
        "d_ret30": pd.Series(dc).pct_change(30).values,
        "d_vol_ma20": pd.Series(dv).rolling(20).mean().values,
        "d_vol": dv,
        "er10": er10,
        "er20": er20,
        "btc_gold_ratio": dc / np.maximum(gold_c, 1e-9),
        "btc_gold_sma30": pd.Series(dc / np.maximum(gold_c, 1e-9)).rolling(30).mean().values,
        "etf_sum3": pd.Series(etf_al).rolling(3).sum().values,
        "etf_sum5": pd.Series(etf_al).rolling(5).sum().values,
        "etf_sum10": pd.Series(etf_al).rolling(10).sum().values,
        "peer_ret5": peer_ret5,
        "peer_ret10": peer_ret10,
    }, index=daily.index)
    daily_lag = daily_df.shift(1)

    out = df_1h.copy()
    day_floors = out.index.floor("D")
    d_idx = daily_lag.index.get_indexer(day_floors)
    valid_d = d_idx >= 0
    for col in daily_lag.columns:
        arr = np.full(n, np.nan, dtype=float)
        src = daily_lag[col].values
        arr[valid_d] = src[d_idx[valid_d]]
        out[col] = arr

    def lag1(arr):
        res = np.roll(arr, 1)
        res[0] = np.nan
        return res

    c_s = pd.Series(c)
    prev_c1 = np.roll(c, 1)
    prev_c1[0] = c[0]
    tr_1h = np.maximum(h - l, np.maximum(np.abs(h - prev_c1), np.abs(l - prev_c1)))
    atr_24h = pd.Series(tr_1h).rolling(24).mean().values
    ema_24h = c_s.ewm(span=24, adjust=False).mean().values
    out["kelt_upper"] = lag1(ema_24h + 2.0 * atr_24h)
    out["kelt_lower"] = lag1(ema_24h - 2.0 * atr_24h)
    out["atr_ratio_24_168"] = lag1(atr_24h / np.maximum(pd.Series(tr_1h).rolling(168).mean().values, 1e-9))
    out["ret_12h"] = lag1(c_s.pct_change(12).values)
    out["c_prev"] = lag1(c)

    # Funding features lagged by 1 completed 8h interval
    f_vals = fund_8h.values
    f_df = pd.DataFrame({
        "f_sum3": pd.Series(f_vals).rolling(3).sum().values,
        "f_sum6": pd.Series(f_vals).rolling(6).sum().values,
        "f_sum9": pd.Series(f_vals).rolling(9).sum().values,
    }, index=fund_8h.index).shift(1)

    pos = np.searchsorted(f_df.index.asi8, out.index.asi8, side="right") - 1
    valid_f = pos >= 0
    for col in f_df.columns:
        arr = np.full(n, np.nan, dtype=float)
        src = f_df[col].values
        arr[valid_f] = src[pos[valid_f]]
        out[col] = arr

    out["hour"] = out.index.hour.values
    return out


# ==============================================================================
# 3. 10 SOLO MULTI-DAY SWING ENGINES (DESIRED_DIR IN {-1, 0, +1})
# ==============================================================================

def get_solo_signals(df, idea_id, scale=1.0):
    n = len(df)
    des = np.zeros(n, dtype=int)
    hr = df["hour"].values
    dc = df["d_close"].values
    c_prev = df["c_prev"].values

    if idea_id == "00_BASELINE_EMA20_50":
        e20, e50 = df["d_ema20"].values, df["d_ema50"].values
        valid = (~np.isnan(e20)) & (~np.isnan(e50))
        des[valid & (e20 > e50)] = 1
        des[valid & (e20 < e50)] = -1

    elif idea_id == "01_ASYM_DONCHIAN_20_10":
        # Classic Turtle asymmetric breakout: 20d breakout entry, 10d channel exit
        if scale < 1.0:
            hh_in, ll_in = df["d_hh10"].values, df["d_ll10"].values
            hh_out, ll_out = df["d_hh10"].values, df["d_ll10"].values
        elif scale > 1.0:
            hh_in, ll_in = df["d_hh30"].values, df["d_ll30"].values
            hh_out, ll_out = df["d_hh20"].values, df["d_ll20"].values
        else:
            hh_in, ll_in = df["d_hh20"].values, df["d_ll20"].values
            hh_out, ll_out = df["d_hh10"].values, df["d_ll10"].values
        sig = 0
        for i in range(n):
            if hr[i] == 0 and (not np.isnan(dc[i])) and (not np.isnan(hh_in[i])):
                if sig == 0:
                    if dc[i] >= hh_in[i]:
                        sig = 1
                    elif dc[i] <= ll_in[i]:
                        sig = -1
                elif sig == 1 and dc[i] <= ll_out[i]:
                    sig = 0
                elif sig == -1 and dc[i] >= hh_out[i]:
                    sig = 0
            des[i] = sig

    elif idea_id == "02_VOL_BREAKOUT_EMA":
        # Daily EMA20/50 trend entered only when prior day volume > 1.25x 20d avg volume
        e20, e50 = df["d_ema20"].values, df["d_ema50"].values
        dv, dvma = df["d_vol"].values, df["d_vol_ma20"].values
        v_mult = 1.25 * scale
        sig = 0
        for i in range(n):
            if hr[i] == 0 and (not np.isnan(e20[i])) and (not np.isnan(e50[i])) and (not np.isnan(dvma[i])):
                if sig == 1 and e20[i] < e50[i]:
                    sig = 0
                elif sig == -1 and e20[i] > e50[i]:
                    sig = 0
                if sig == 0 and dv[i] > v_mult * dvma[i]:
                    sig = 1 if e20[i] > e50[i] else -1
            des[i] = sig

    elif idea_id == "03_DUAL_MOMENTUM_10_30":
        # Absolute + dual-window momentum: both 10d and 30d returns agree in sign
        r_fast = df["d_ret5"].values if scale < 1.0 else (df["d_ret15"].values if scale > 1.0 else df["d_ret10"].values)
        r_slow = df["d_ret15"].values if scale < 1.0 else df["d_ret30"].values
        valid = (~np.isnan(r_fast)) & (~np.isnan(r_slow))
        des[valid & (r_fast > 0.0) & (r_slow > 0.0)] = 1
        des[valid & (r_fast < 0.0) & (r_slow < 0.0)] = -1

    elif idea_id == "04_EFFICIENCY_RATIO_TREND":
        # Trade EMA20/50 only when Kaufman Efficiency Ratio > 0.25 (avoids choppy sideways bleed)
        e20, e50 = df["d_ema20"].values, df["d_ema50"].values
        er = df["er10"].values if scale <= 1.0 else df["er20"].values
        er_th = 0.25 * scale
        sig = 0
        for i in range(n):
            if hr[i] == 0 and (not np.isnan(e20[i])) and (not np.isnan(e50[i])) and (not np.isnan(er[i])):
                if sig == 1 and e20[i] < e50[i]:
                    sig = 0
                elif sig == -1 and e20[i] > e50[i]:
                    sig = 0
                if sig == 0 and er[i] > er_th:
                    sig = 1 if e20[i] > e50[i] else -1
            des[i] = sig

    elif idea_id == "05_KELTNER_SQUEEZE_BO":
        ku, kl = df["kelt_upper"].values, df["kelt_lower"].values
        ar = df["atr_ratio_24_168"].values
        ar_th = 0.85 * scale
        sig = 0
        for i in range(n):
            if np.isnan(ku[i]) or np.isnan(ar[i]) or np.isnan(c_prev[i]):
                continue
            if sig == 0:
                if ar[i] < ar_th and c_prev[i] > ku[i]:
                    sig = 1
                elif ar[i] < ar_th and c_prev[i] < kl[i]:
                    sig = -1
            elif sig == 1 and c_prev[i] < kl[i]:
                sig = 0
            elif sig == -1 and c_prev[i] > ku[i]:
                sig = 0
            des[i] = sig

    elif idea_id == "06_SMA200_REGIME_EMA":
        # Long-only above SMA200 (when EMA20>EMA50), Short-only below SMA200 (when EMA20<EMA50)
        e20 = df["d_ema10"].values if scale < 1.0 else (df["d_ema30"].values if scale > 1.0 else df["d_ema20"].values)
        e50 = df["d_ema30"].values if scale < 1.0 else (df["d_ema75"].values if scale > 1.0 else df["d_ema50"].values)
        s200 = df["d_sma100"].values if scale < 1.0 else df["d_sma200"].values
        valid = (~np.isnan(e20)) & (~np.isnan(e50)) & (~np.isnan(s200)) & (~np.isnan(dc))
        des[valid & (dc > s200) & (e20 > e50)] = 1
        des[valid & (dc < s200) & (e20 < e50)] = -1

    elif idea_id == "07_ETF_FLOW_TREND_HYBRID":
        # Pre-2024: EMA20/50 trend; 2024+: 5d/10d net ETF flow sign filtered by EMA20/50
        e20, e50 = df["d_ema20"].values, df["d_ema50"].values
        ef = df["etf_sum3"].values if scale < 1.0 else (df["etf_sum10"].values if scale > 1.0 else df["etf_sum5"].values)
        is_etf = (df.index >= "2024-01-12")
        for i in range(n):
            if np.isnan(e20[i]) or np.isnan(e50[i]):
                continue
            trend_d = 1 if e20[i] > e50[i] else -1
            if is_etf[i]:
                if not np.isnan(ef[i]):
                    if ef[i] > 0.0 and trend_d == 1:
                        des[i] = 1
                    elif ef[i] < 0.0 and trend_d == -1:
                        des[i] = -1
            else:
                des[i] = trend_d

    elif idea_id == "08_FUNDING_CONFIRMED_TREND":
        # Pre-2020: EMA20/50; 2020+: EMA20/50 confirmed by non-overheated funding (< +0.30% / > -0.15% over 72h)
        e20, e50 = df["d_ema20"].values, df["d_ema50"].values
        fs = df["f_sum6"].values if scale < 1.0 else (df["f_sum9"].values)
        cap = 0.0030 * scale
        for i in range(n):
            if np.isnan(e20[i]) or np.isnan(e50[i]):
                continue
            td = 1 if e20[i] > e50[i] else -1
            if np.isnan(fs[i]):
                des[i] = td
            else:
                if td == 1 and fs[i] < cap:
                    des[i] = 1
                elif td == -1 and fs[i] > -cap:
                    des[i] = -1

    elif idea_id == "09_BTC_GOLD_ROTATION":
        bgr = df["btc_gold_ratio"].values
        bgs = df["btc_gold_sma30"].values
        buf = 0.01 * (scale - 1.0)
        valid = (~np.isnan(bgr)) & (~np.isnan(bgs))
        des[valid & (bgr > bgs * (1.0 + buf))] = 1
        des[valid & (bgr < bgs * (1.0 - buf))] = -1

    elif idea_id == "10_CROSS_CRYPTO_LEAD_MOM":
        # Trade when both asset's own 10d return and peer (BTC/ETH) 10d return agree > threshold
        r_own = df["d_ret5"].values if scale < 1.0 else df["d_ret10"].values
        r_peer = df["peer_ret5"].values if scale < 1.0 else df["peer_ret10"].values
        th = 0.015 * scale
        valid = (~np.isnan(r_own)) & (~np.isnan(r_peer))
        des[valid & (r_own > th) & (r_peer > th)] = 1
        des[valid & (r_own < -th) & (r_peer < -th)] = -1

    return des


# ==============================================================================
# 4. BACKTEST ENGINE & MULTI-ENGINE PORTFOLIO BLENDER
# ==============================================================================

def run_single_engine(df, desired_arr, risk_pct=BASE_RISK, start_date="2018-01-01"):
    mask = (df.index >= start_date)
    sub = df.loc[mask]
    n_bars = len(sub)
    if n_bars < 50:
        return pd.DataFrame(), pd.Series(dtype=float)

    idx_pos = df.index.get_indexer(sub.index)
    des = desired_arr[idx_pos]

    opens = sub["open"].values
    highs = sub["high"].values
    lows = sub["low"].values
    closes = sub["close"].values
    atrs = sub["d_atr14"].values
    times = sub.index

    equity = 1.0
    pos_dir = 0
    entry_px = 0.0
    stop_px = 0.0
    lev = 0.0
    entry_t = None

    trades = []
    eq_dates = []
    eq_vals = []

    for i in range(n_bars):
        if pos_dir != 0:
            unr = pos_dir * (closes[i] - entry_px) / entry_px
            mtm = equity * (1.0 + lev * (unr - FEE_PER_SIDE))
        else:
            mtm = equity

        if times[i].hour == 23 or i == n_bars - 1:
            eq_dates.append(times[i].floor("D"))
            eq_vals.append(max(mtm, 1e-6))

        if pos_dir == 1 and lows[i] <= stop_px:
            exit_px = min(opens[i], stop_px)
            net_ret = (exit_px - entry_px) / entry_px - 2.0 * FEE_PER_SIDE
            pnl_eq = lev * net_ret
            equity = max(equity * (1.0 + pnl_eq), 1e-6)
            trades.append({"entry_t": entry_t, "exit_t": times[i], "dir": 1, "pnl_eq": pnl_eq})
            pos_dir = 0
            continue
        elif pos_dir == -1 and highs[i] >= stop_px:
            exit_px = max(opens[i], stop_px)
            net_ret = (entry_px - exit_px) / entry_px - 2.0 * FEE_PER_SIDE
            pnl_eq = lev * net_ret
            equity = max(equity * (1.0 + pnl_eq), 1e-6)
            trades.append({"entry_t": entry_t, "exit_t": times[i], "dir": -1, "pnl_eq": pnl_eq})
            pos_dir = 0
            continue

        if np.isnan(atrs[i]) or atrs[i] <= 0.0:
            continue

        target = int(des[i])
        if pos_dir != 0 and target != pos_dir:
            exit_px = opens[i]
            net_ret = pos_dir * (exit_px - entry_px) / entry_px - 2.0 * FEE_PER_SIDE
            pnl_eq = lev * net_ret
            equity = max(equity * (1.0 + pnl_eq), 1e-6)
            trades.append({"entry_t": entry_t, "exit_t": times[i], "dir": pos_dir, "pnl_eq": pnl_eq})
            pos_dir = 0

        if pos_dir == 0 and target != 0:
            entry_px = opens[i]
            stop_dist = max((ATR_MULT * atrs[i]) / entry_px, 0.005)
            lev = min(risk_pct / stop_dist, MAX_LEV)
            stop_px = entry_px * (1.0 - target * stop_dist)
            pos_dir = target
            entry_t = times[i]

    eq_s = pd.Series(eq_vals, index=pd.DatetimeIndex(eq_dates)).groupby(level=0).last().sort_index()
    return pd.DataFrame(trades), eq_s


def blend_engines(df, engine_ids, weights, scale=1.0, start_date="2018-01-01"):
    """
    Runs each sub-engine at `weight * BASE_RISK` (so total risk budget = 1.0% across portfolio)
    and aggregates daily returns + trade logs cleanly.
    """
    all_eq = []
    all_tr = []
    for eid, w in zip(engine_ids, weights):
        des = get_solo_signals(df, eid, scale=scale)
        tr, eq = run_single_engine(df, des, risk_pct=w * BASE_RISK, start_date=start_date)
        all_eq.append(eq)
        if tr is not None and not tr.empty:
            all_tr.append(tr)

    idx = all_eq[0].index
    for eq in all_eq[1:]:
        idx = idx.union(eq.index)
    idx = idx.sort_values()

    tot_ret = np.zeros(len(idx), dtype=float)
    for eq in all_eq:
        r = eq.reindex(idx).ffill().fillna(1.0).pct_change().fillna(0.0).values
        tot_ret += r

    comb_eq = pd.Series(np.cumprod(1.0 + tot_ret), index=idx)
    comb_tr = pd.concat(all_tr, ignore_index=True) if all_tr else pd.DataFrame()
    return comb_tr, comb_eq


# ==============================================================================
# 5. METRICS & 100-RUN DATE-SHUFFLED PLACEBO
# ==============================================================================

def calc_stats(eq_s, start_dt=None, end_dt=None):
    if eq_s is None or len(eq_s) < 5:
        return {"cagr": 0.0, "max_dd": 0.0, "mar": 0.0}
    s = eq_s
    if start_dt is not None:
        s = s[s.index >= start_dt]
    if end_dt is not None:
        s = s[s.index <= end_dt]
    if len(s) < 5 or s.iloc[0] <= 0:
        return {"cagr": 0.0, "max_dd": 0.0, "mar": 0.0}
    s = s / s.iloc[0]
    yrs = max((s.index[-1] - s.index[0]).days, 1) / 365.25
    cagr = (float(s.iloc[-1]) ** (1.0 / yrs) - 1.0) * 100.0
    max_dd = abs(float((s / s.cummax() - 1.0).min())) * 100.0
    mar = (cagr / max_dd) if max_dd > 0.01 else 0.0
    return {"cagr": cagr, "max_dd": max_dd, "mar": mar}


def calc_pf(trades_df):
    if trades_df is None or trades_df.empty:
        return 0.0
    pnl = trades_df["pnl_eq"].values
    w = pnl[pnl > 0].sum()
    l = -pnl[pnl < 0].sum()
    return float(w / l) if l > 1e-12 else (99.0 if w > 0 else 0.0)


def calc_yearly(eq_s):
    out = {yr: 0.0 for yr in range(2018, 2027)}
    if eq_s is None or eq_s.empty:
        return out
    prev = 1.0
    for yr in range(2018, 2027):
        sub = eq_s[eq_s.index.year == yr]
        if not sub.empty:
            end_v = float(sub.iloc[-1])
            out[yr] = round((end_v / prev - 1.0) * 100.0, 2)
            prev = end_v
    return out


def run_placebo_100(df, spec, actual_mar, n_sims=100, seed=42):
    rng = np.random.default_rng(seed)
    day_floors = df.index.floor("D")
    unique_days = pd.DatetimeIndex(day_floors.unique()).sort_values()
    n_days = len(unique_days)
    day_idx = unique_days.get_indexer(day_floors)
    day_groups = [np.where(day_idx == d)[0] for d in range(n_days)]

    engine_ids, weights = spec["engines"], spec["weights"]
    orig_sigs = [get_solo_signals(df, eid, scale=1.0) for eid in engine_ids]

    beat = 0
    for _ in range(n_sims):
        perm = rng.permutation(n_days)
        all_eq = []
        for des_orig, w in zip(orig_sigs, weights):
            shuf = np.zeros_like(des_orig)
            for d_tgt, d_src in enumerate(perm):
                tb = day_groups[d_tgt]
                sb = day_groups[d_src]
                if len(sb) > 0:
                    take = np.minimum(np.arange(len(tb)), len(sb) - 1)
                    shuf[tb] = des_orig[sb[take]]
            _, eq = run_single_engine(df, shuf, risk_pct=w * BASE_RISK, start_date="2018-01-01")
            all_eq.append(eq)

        idx = all_eq[0].index
        for eq in all_eq[1:]:
            idx = idx.union(eq.index)
        idx = idx.sort_values()
        tot_ret = np.zeros(len(idx), dtype=float)
        for eq in all_eq:
            tot_ret += eq.reindex(idx).ffill().fillna(1.0).pct_change().fillna(0.0).values
        sim_eq = pd.Series(np.cumprod(1.0 + tot_ret), index=idx)

        if actual_mar > calc_stats(sim_eq)["mar"]:
            beat += 1

    return 100.0 * beat / n_sims


# ==============================================================================
# 6. MAIN 15-CANDIDATE EXECUTION & STRICT VERDICT GATE
# ==============================================================================

CANDIDATES = {
    "00_BASELINE_EMA20_50":       {"engines": ["00_BASELINE_EMA20_50"], "weights": [1.0]},
    "01_ASYM_DONCHIAN_20_10":     {"engines": ["01_ASYM_DONCHIAN_20_10"], "weights": [1.0]},
    "02_VOL_BREAKOUT_EMA":        {"engines": ["02_VOL_BREAKOUT_EMA"], "weights": [1.0]},
    "03_DUAL_MOMENTUM_10_30":     {"engines": ["03_DUAL_MOMENTUM_10_30"], "weights": [1.0]},
    "04_EFFICIENCY_RATIO_TREND":  {"engines": ["04_EFFICIENCY_RATIO_TREND"], "weights": [1.0]},
    "05_KELTNER_SQUEEZE_BO":      {"engines": ["05_KELTNER_SQUEEZE_BO"], "weights": [1.0]},
    "06_SMA200_REGIME_EMA":       {"engines": ["06_SMA200_REGIME_EMA"], "weights": [1.0]},
    "07_ETF_FLOW_TREND_HYBRID":   {"engines": ["07_ETF_FLOW_TREND_HYBRID"], "weights": [1.0]},
    "08_FUNDING_CONFIRMED_TREND": {"engines": ["08_FUNDING_CONFIRMED_TREND"], "weights": [1.0]},
    "09_BTC_GOLD_ROTATION":       {"engines": ["09_BTC_GOLD_ROTATION"], "weights": [1.0]},
    "10_CROSS_CRYPTO_LEAD_MOM":   {"engines": ["10_CROSS_CRYPTO_LEAD_MOM"], "weights": [1.0]},
    # 5 Orthogonal Portfolio Blends (1.0% total risk budget split across uncorrelated engines)
    "11_BLEND_EMA_KELTNER":       {"engines": ["00_BASELINE_EMA20_50", "05_KELTNER_SQUEEZE_BO"], "weights": [0.5, 0.5]},
    "12_BLEND_EMA_ETF":           {"engines": ["00_BASELINE_EMA20_50", "07_ETF_FLOW_TREND_HYBRID"], "weights": [0.5, 0.5]},
    "13_BLEND_EMA_GOLD":          {"engines": ["00_BASELINE_EMA20_50", "09_BTC_GOLD_ROTATION"], "weights": [0.5, 0.5]},
    "14_BLEND_EMA_SMA200_KELT":   {"engines": ["00_BASELINE_EMA20_50", "06_SMA200_REGIME_EMA", "05_KELTNER_SQUEEZE_BO"], "weights": [0.34, 0.33, 0.33]},
    "15_BLEND_4ENGINE_CORE":      {"engines": ["00_BASELINE_EMA20_50", "05_KELTNER_SQUEEZE_BO", "07_ETF_FLOW_TREND_HYBRID", "09_BTC_GOLD_ROTATION"], "weights": [0.25, 0.25, 0.25, 0.25]},
}


def screen_asset(df, asset_name):
    print("\n" + "=" * 116)
    print(f"STAGE 1: 15-CANDIDATE SWING & ORTHOGONAL BLEND SCREEN ON {asset_name} (2018-01-01 to {df.index.max().date()})")
    print("=" * 116)

    res = {}
    for name, spec in CANDIDATES.items():
        tr_df, eq_s = blend_engines(df, spec["engines"], spec["weights"], scale=1.0, start_date="2018-01-01")
        st_all = calc_stats(eq_s)
        st_h1 = calc_stats(eq_s, "2018-01-01", "2021-12-31")
        st_h2 = calc_stats(eq_s, "2022-01-01", "2026-12-31")
        pf = calc_pf(tr_df)
        yr = calc_yearly(eq_s)

        res[name] = {
            "Asset": asset_name,
            "Candidate": name,
            "Trades": len(tr_df),
            "CAGR%": round(st_all["cagr"], 2),
            "MaxDD%": round(st_all["max_dd"], 2),
            "MAR": round(st_all["mar"], 2),
            "MAR_18_21": round(st_h1["mar"], 2),
            "MAR_22_26": round(st_h2["mar"], 2),
            "PF": round(pf, 2),
            "Yearly": yr,
            "Placebo%": np.nan,
            "NbrPass%": np.nan,
        }
        print(f"{name:<27} | Tr={len(tr_df):<4} | CAGR={res[name]['CAGR%']:>6.2f}% | DD={res[name]['MaxDD%']:>5.2f}% | MAR={res[name]['MAR']:>5.2f} (H1={res[name]['MAR_18_21']:>4.2f}, H2={res[name]['MAR_22_26']:>4.2f}) | PF={res[name]['PF']:>4.2f}")
        print(f"   Per-Year: {yr}")
    return res


def main():
    btc_1h = load_ohlcv_1h("https://osom-boba.pages.dev/colab/btc_1h_full.csv.gz", "BTC")
    eth_1h = load_ohlcv_1h("https://osom-boba.pages.dev/colab/eth_1h_full.csv.gz", "ETH")
    fund_8h = load_funding_8h("https://osom-boba.pages.dev/colab/btc_funding_8h.csv")
    etf_d = load_etf_flows("https://osom-boba.pages.dev/colab/btc_etf_flows.csv.gz")
    macro_d = load_macro_yf("2017-01-01")

    btc_df = build_features(btc_1h, fund_8h, etf_d, macro_d, peer_1h=eth_1h)
    eth_df = build_features(eth_1h, fund_8h, etf_d, macro_d, peer_1h=btc_1h)

    btc_res = screen_asset(btc_df, "BTC")
    eth_res = screen_asset(eth_df, "ETH")

    btc_base = btc_res["00_BASELINE_EMA20_50"]
    eth_base = eth_res["00_BASELINE_EMA20_50"]

    print("\n" + "=" * 116)
    print("STAGE 2: 100-RUN PLACEBO & 0.5x/1.5x PARAMETER NEIGHBOUR VALIDATION")
    print("=" * 116)

    names = list(CANDIDATES.keys())[1:]
    stage1_pass = []
    for name in names:
        rb, re = btc_res[name], eth_res[name]
        halves_ok = (rb["MAR_18_21"] > btc_base["MAR_18_21"]) and (rb["MAR_22_26"] > btc_base["MAR_22_26"])
        dd_ok = (rb["MaxDD%"] <= btc_base["MaxDD%"] + 3.0)
        btc_yrs = sum(1 for y in range(2018, 2027) if rb["Yearly"][y] > btc_base["Yearly"][y])
        eth_yrs = sum(1 for y in range(2018, 2027) if re["Yearly"][y] > eth_base["Yearly"][y])
        if halves_ok and dd_ok and (btc_yrs >= 5) and (eth_yrs >= 4):
            stage1_pass.append(name)

    top3_mar = sorted(names, key=lambda x: btc_res[x]["MAR"], reverse=True)[:3]
    to_check = list(dict.fromkeys(stage1_pass + top3_mar))

    kept = []
    for name in to_check:
        rb, re = btc_res[name], eth_res[name]
        spec = CANDIDATES[name]
        plac = run_placebo_100(btc_df, spec, rb["MAR"], n_sims=100, seed=42)

        nbr_mars = []
        for sc in [0.5, 1.5]:
            _, eq_sc = blend_engines(btc_df, spec["engines"], spec["weights"], scale=sc, start_date="2018-01-01")
            nbr_mars.append(calc_stats(eq_sc)["mar"])
        nbr_pct = 100.0 * sum(1 for m in nbr_mars if m > btc_base["MAR"]) / len(nbr_mars)

        btc_res[name]["Placebo%"] = round(plac, 1)
        btc_res[name]["NbrPass%"] = round(nbr_pct, 1)

        halves_ok = (rb["MAR_18_21"] > btc_base["MAR_18_21"]) and (rb["MAR_22_26"] > btc_base["MAR_22_26"])
        dd_ok = (rb["MaxDD%"] <= btc_base["MaxDD%"] + 3.0)
        btc_yrs = sum(1 for y in range(2018, 2027) if rb["Yearly"][y] > btc_base["Yearly"][y])
        eth_yrs = sum(1 for y in range(2018, 2027) if re["Yearly"][y] > eth_base["Yearly"][y])

        passed = halves_ok and dd_ok and (btc_yrs >= 5) and (eth_yrs >= 4) and (plac >= 90.0) and (nbr_pct >= 70.0)
        if passed:
            kept.append(name)

        print(f"  {name:<27}: Halves={halves_ok} ({rb['MAR_18_21']}>{btc_base['MAR_18_21']}, {rb['MAR_22_26']}>{btc_base['MAR_22_26']}) | DD_OK={dd_ok} | BTC_Yrs={btc_yrs}/9 | ETH_Yrs={eth_yrs}/9 | Placebo={plac:.1f}% | Nbrs={nbr_mars[0]:.2f}/{nbr_mars[1]:.2f} ({nbr_pct:.0f}%) -> {'KEEP' if passed else 'FAIL'}")

    rows = []
    for asset_name, rmap in [("BTC", btc_res), ("ETH", eth_res)]:
        for name in CANDIDATES.keys():
            r = rmap[name]
            rows.append({
                "Asset": asset_name,
                "Candidate": name,
                "Tr": r["Trades"],
                "CAGR%": r["CAGR%"],
                "MaxDD%": r["MaxDD%"],
                "MAR": r["MAR"],
                "H1_MAR": r["MAR_18_21"],
                "H2_MAR": r["MAR_22_26"],
                "PF": r["PF"],
                "Plac%": r["Placebo%"],
                "Nbr%": r["NbrPass%"],
            })

    print("\n" + "=" * 116)
    print("FINAL COMPACT COMPARISON TABLE (15 CANDIDATES vs BASELINE | BTC & ETH | 2018-2026)")
    print("=" * 116)
    print(pd.DataFrame(rows).to_string(index=False))

    print("\n" + "=" * 116)
    if kept:
        print(f"VERDICT: KEEP ({', '.join(kept)}) — Cleared dual-half MAR, MaxDD, BTC/ETH yearly breadth, 90% placebo, and 0.5x/1.5x plateau gates.")
    else:
        print("VERDICT: FAIL — 0 of 15 candidates cleared every strict BTC/ETH, placebo, and neighbour plateau gate.")
    print("=" * 116)


if __name__ == "__main__":
    main()