#!/usr/bin/env python3
"""
Quant Research Suite — 18-Idea Orthogonal Engine & Drawdown-Cutter Screener (BTC & ETH, 2018-2026)
- Purpose: Screen 18 structurally distinct, low-correlation strategy engines against the identical
  no-dial EMA(20)/EMA(50) baseline, then run 100-run date-shuffled placebos and 0.5x/1.5x
  parameter-neighbour plateau checks on top survivors under a strict multiple-testing gate.
- 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
  * SPY & Gold (GC=F) via yfinance (MultiIndex flattened, 1-day lag)
- Execution & Risk Rules:
  * Costs: 0.12% per side | Risk: 1.0% per trade | Stop: 2.0x daily ATR(14) | Notional cap: 3.0x equity
  * Strict no-lookahead: all signals computed at bar t-1 close; all entries/exits at bar t open
  * Column assignments built strictly via .values
"""

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 = {"spy": "SPY", "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 (ALL LAGGED TO PREVIOUS BAR CLOSE, .VALUES ONLY)
# ==============================================================================

def build_features(df_1h, fund_8h, etf_daily, macro_daily):
    n = len(df_1h)
    o = df_1h["open"].values
    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)
    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 = daily["high"].values, daily["low"].values, daily["close"].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)))

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

    daily_df = pd.DataFrame({
        "d_atr14": pd.Series(d_tr).rolling(14).mean().values,
        "d_ema20": pd.Series(dc).ewm(span=20, adjust=False).mean().values,
        "d_ema50": pd.Series(dc).ewm(span=50, adjust=False).mean().values,
        "d_sma200": pd.Series(dc).rolling(200).mean().values,
        "d_ret1": pd.Series(dc).pct_change(1).values,
        "d_ret3": pd.Series(dc).pct_change(3).values,
        "d_ret5": pd.Series(dc).pct_change(5).values,
        "d_ret10": pd.Series(dc).pct_change(10).values,
        "d_hh20": pd.Series(dh).rolling(20).max().values,
        "d_ll20": pd.Series(dl).rolling(20).min().values,
        "d_hh40": pd.Series(dh).rolling(40).max().values,
        "d_ll40": pd.Series(dl).rolling(40).min().values,
        "d_range_pct": (dh - dl) / np.maximum(dc, 1e-9),
        "d_range_min7": pd.Series((dh - dl) / np.maximum(dc, 1e-9)).rolling(7).min().values,
        "d_range_min14": pd.Series((dh - dl) / np.maximum(dc, 1e-9)).rolling(14).min().values,
        "spy_ret3": pd.Series(spy_c).pct_change(3).values,
        "spy_ret5": pd.Series(spy_c).pct_change(5).values,
        "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_sum5": pd.Series(etf_al).rolling(5).sum().values,
        "etf_sum10": pd.Series(etf_al).rolling(10).sum().values,
    }, 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

    # 1h indicators shifted +1 bar (so bar i sees bar i-1 close)
    def lag1(arr):
        res = np.roll(arr, 1)
        res[0] = np.nan
        return res

    c_s = pd.Series(c)
    h_s = pd.Series(h)
    l_s = pd.Series(l)
    v_s = pd.Series(v)

    # RSI(2), RSI(4), RSI(14)
    for p in [2, 4, 14]:
        delta = np.diff(c, prepend=c[0])
        g = pd.Series(np.where(delta > 0, delta, 0.0)).ewm(alpha=1.0 / p, adjust=False).mean().values
        ls = pd.Series(np.where(delta < 0, -delta, 0.0)).ewm(alpha=1.0 / p, adjust=False).mean().values
        rsi = 100.0 - (100.0 / (1.0 + g / np.maximum(ls, 1e-12)))
        rsi[:p] = np.nan
        out[f"rsi{p}"] = lag1(rsi)

    # Bollinger Z-scores (24h, 48h, 72h)
    for w in [24, 48, 72]:
        m = c_s.rolling(w).mean().values
        sd = c_s.rolling(w).std().values
        out[f"z{w}"] = lag1((c - m) / np.maximum(sd, 1e-9))

    # Keltner / ATR channels & Volume Z-score
    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))

    v_m = v_s.rolling(48).mean().values
    v_sd = v_s.rolling(48).std().values
    out["vol_z48"] = lag1((v - v_m) / np.maximum(v_sd, 1e-9))
    out["ret_1h"] = lag1(c_s.pct_change(1).values)
    out["ret_4h"] = lag1(c_s.pct_change(4).values)
    out["ret_12h"] = lag1(c_s.pct_change(12).values)
    out["ret_24h"] = lag1(c_s.pct_change(24).values)
    out["ret_72h"] = lag1(c_s.pct_change(72).values)
    out["hh_48h"] = lag1(h_s.rolling(48).max().values)
    out["ll_48h"] = lag1(l_s.rolling(48).min().values)
    out["hh_96h"] = lag1(h_s.rolling(96).max().values)
    out["ll_96h"] = lag1(l_s.rolling(96).min().values)
    out["c_prev"] = lag1(c)
    out["o_prev"] = lag1(o)
    out["h_prev"] = lag1(h)
    out["l_prev"] = lag1(l)

    # Funding features lagged by 1 completed 8h interval
    f_vals = fund_8h.values
    f_df = pd.DataFrame({
        "f_last": f_vals,
        "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,
        "f_sum15": pd.Series(f_vals).rolling(15).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
    out["dow"] = out.index.dayofweek.values
    return out


# ==============================================================================
# 3. 18 ORTHOGONAL SIGNAL GENERATORS (RETURN DESIRED_DIR ARRAY: -1, 0, +1)
# ==============================================================================

def get_desired_signals(df, idea_id, scale=1.0):
    """
    Returns an integer array `desired` of length len(df) in {-1, 0, +1} representing
    the desired position at bar i's OPEN (using strictly bar i-1 information).
    `scale` in {0.5, 1.0, 1.5} perturbs the primary threshold/window for plateau checks.
    """
    n = len(df)
    des = np.zeros(n, dtype=int)
    c_prev = df["c_prev"].values
    hr = df["hour"].values
    dow = df["dow"].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

    # --- FAMILY A: MEAN REVERSION / EXHAUSTION ---
    elif idea_id == "01_BB_ZSCORE_MR":
        z = df["z48"].values
        th = 2.2 * scale
        sig = 0
        for i in range(n):
            if np.isnan(z[i]):
                continue
            if sig == 0:
                if z[i] < -th:
                    sig = 1
                elif z[i] > th:
                    sig = -1
            elif sig == 1 and z[i] >= 0.0:
                sig = 0
            elif sig == -1 and z[i] <= 0.0:
                sig = 0
            des[i] = sig

    elif idea_id == "02_CONNORS_RSI2_PULLBACK":
        rsi2 = df["rsi2"].values
        sma200 = df["d_sma200"].values
        lo_th = 10.0 * scale
        hi_th = 100.0 - 10.0 * scale
        sig = 0
        for i in range(n):
            if np.isnan(rsi2[i]) or np.isnan(sma200[i]) or np.isnan(c_prev[i]):
                continue
            if sig == 0:
                if c_prev[i] > sma200[i] and rsi2[i] < lo_th:
                    sig = 1
                elif c_prev[i] < sma200[i] and rsi2[i] > hi_th:
                    sig = -1
            elif sig == 1 and rsi2[i] > 65.0:
                sig = 0
            elif sig == -1 and rsi2[i] < 35.0:
                sig = 0
            des[i] = sig

    elif idea_id == "03_CAPITULATION_VOL_SPIKE":
        vz = df["vol_z48"].values
        r4 = df["ret_4h"].values
        v_th = 2.5 * scale
        hold = 0
        sig = 0
        for i in range(n):
            if hold > 0:
                hold -= 1
                if hold == 0:
                    sig = 0
            if sig == 0 and (not np.isnan(vz[i])) and (not np.isnan(r4[i])):
                if vz[i] > v_th and r4[i] < -0.025:
                    sig = 1
                    hold = int(round(12 * scale))
                elif vz[i] > v_th and r4[i] > 0.025:
                    sig = -1
                    hold = int(round(12 * scale))
            des[i] = sig

    elif idea_id == "04_OVERNIGHT_REVERSAL":
        r24 = df["ret_24h"].values
        th = 0.03 * scale
        sig = 0
        for i in range(n):
            if hr[i] == 0 and (not np.isnan(r24[i])):
                if r24[i] < -th:
                    sig = 1
                elif r24[i] > th:
                    sig = -1
                else:
                    sig = 0
            des[i] = sig

    # --- FAMILY B: VOLATILITY & BREAKOUT ---
    elif idea_id == "05_NR7_INSIDE_BREAKOUT":
        rng = df["d_range_pct"].values
        rmin = df["d_range_min7"].values if scale <= 1.0 else df["d_range_min14"].values
        sig = 0
        for i in range(n):
            if hr[i] == 0 and (not np.isnan(rng[i])) and (not np.isnan(rmin[i])):
                if rng[i] <= rmin[i] * (1.02 if scale < 1.0 else 1.0):
                    sig = 1 if df["d_ret1"].values[i] >= 0 else -1
                else:
                    sig = 0
            des[i] = sig

    elif idea_id == "06_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 == "07_DONCHIAN_48H_96H":
        hh = df["hh_48h"].values if scale <= 1.0 else df["hh_96h"].values
        ll = df["ll_48h"].values if scale <= 1.0 else df["ll_96h"].values
        sig = 0
        for i in range(n):
            if np.isnan(hh[i]) or np.isnan(ll[i]) or np.isnan(c_prev[i]):
                continue
            if c_prev[i] >= hh[i]:
                sig = 1
            elif c_prev[i] <= ll[i]:
                sig = -1
            des[i] = sig

    elif idea_id == "08_VOL_EXPANSION_MOM":
        ar = df["atr_ratio_24_168"].values
        r12 = df["ret_12h"].values
        ar_th = 1.35 * scale
        sig = 0
        hold = 0
        for i in range(n):
            if hold > 0:
                hold -= 1
                if hold == 0:
                    sig = 0
            if sig == 0 and (not np.isnan(ar[i])) and (not np.isnan(r12[i])):
                if ar[i] > ar_th and r12[i] > 0.015:
                    sig = 1
                    hold = 24
                elif ar[i] > ar_th and r12[i] < -0.015:
                    sig = -1
                    hold = 24
            des[i] = sig

    # --- FAMILY C: INTRADAY SESSION & CALENDAR SEASONALITY ---
    elif idea_id == "09_US_SESSION_MOM":
        # At 13:00 UTC (US open), trade direction of Asia/EU session (00:00-12:00 UTC) until 21:00 UTC
        r12 = df["ret_12h"].values
        th = 0.008 * scale
        sig = 0
        for i in range(n):
            if hr[i] == 13 and (not np.isnan(r12[i])):
                sig = 1 if r12[i] > th else (-1 if r12[i] < -th else 0)
            elif hr[i] == 21:
                sig = 0
            des[i] = sig

    elif idea_id == "10_ASIA_FADE_EU":
        # Fade strong Asia move (>1.2% in 8h) at 08:00 UTC EU open, hold until 15:00 UTC
        r8 = df["ret_12h"].values
        th = 0.015 * scale
        sig = 0
        for i in range(n):
            if hr[i] == 8 and (not np.isnan(r8[i])):
                sig = -1 if r8[i] > th else (1 if r8[i] < -th else 0)
            elif hr[i] == 15:
                sig = 0
            des[i] = sig

    elif idea_id == "11_WEEKEND_DRIFT_REV":
        # Fade Fri-Sun weekend drift at Monday 00:00 UTC for 24h
        r72 = df["ret_72h"].values
        th = 0.025 * scale
        sig = 0
        for i in range(n):
            if dow[i] == 0 and hr[i] == 0 and (not np.isnan(r72[i])):
                sig = -1 if r72[i] > th else (1 if r72[i] < -th else 0)
            elif dow[i] == 1 and hr[i] == 0:
                sig = 0
            des[i] = sig

    elif idea_id == "12_FUNDING_TIMESTAMP_PRE":
        # Pre-funding 2h window (06-08, 14-16, 22-00 UTC): fade extreme funding settlement pressure
        fl = df["f_last"].values
        th = 0.0003 * scale
        for i in range(n):
            if hr[i] in (6, 7, 14, 15, 22, 23) and (not np.isnan(fl[i])):
                if fl[i] > th:
                    des[i] = -1
                elif fl[i] < -th:
                    des[i] = 1

    # --- FAMILY D: PERPETUAL FUNDING CARRY & SQUEEZE ---
    elif idea_id == "13_NEG_FUNDING_SQUEEZE":
        # Long squeeze when 3-period funding < -0.03% and price breaks 12h positive momentum
        fs3 = df["f_sum3"].values
        r12 = df["ret_12h"].values
        th = -0.0003 * scale
        sig = 0
        hold = 0
        for i in range(n):
            if hold > 0:
                hold -= 1
                if hold == 0:
                    sig = 0
            if sig == 0 and (not np.isnan(fs3[i])) and (not np.isnan(r12[i])):
                if fs3[i] < th and r12[i] > 0.005:
                    sig = 1
                    hold = 24
            des[i] = sig

    elif idea_id == "14_FUNDING_CARRY_TREND":
        # Collect positive carry (short when funding > +0.06% over 48h & price < EMA50) or long when deeply negative
        fs6 = df["f_sum6"].values
        e50 = df["d_ema50"].values
        th = 0.0012 * scale
        for i in range(n):
            if np.isnan(fs6[i]) or np.isnan(e50[i]) or np.isnan(c_prev[i]):
                continue
            if fs6[i] > th and c_prev[i] < e50[i]:
                des[i] = -1
            elif fs6[i] < -th and c_prev[i] > e50[i]:
                des[i] = 1

    elif idea_id == "15_FUNDING_DIVERGENCE":
        # Price up >3% over 72h while 72h funding stays negative (spot-led rally = bullish) or vice versa
        fs9 = df["f_sum9"].values
        r72 = df["ret_72h"].values
        r_th = 0.03 * scale
        for i in range(n):
            if np.isnan(fs9[i]) or np.isnan(r72[i]):
                continue
            if r72[i] > r_th and fs9[i] < 0.0:
                des[i] = 1
            elif r72[i] < -r_th and fs9[i] > 0.0009:
                des[i] = -1

    # --- FAMILY E: CROSS-ASSET & ETF FLOW LEAD-LAG ---
    elif idea_id == "16_SPY_LEAD_CRYPTO":
        # Trade crypto in direction of 3-day SPY return at 00:00 UTC when SPY moves > 1.2%
        sr = df["spy_ret3"].values if scale <= 1.0 else df["spy_ret5"].values
        th = 0.012 * scale
        sig = 0
        for i in range(n):
            if hr[i] == 0 and (not np.isnan(sr[i])):
                sig = 1 if sr[i] > th else (-1 if sr[i] < -th else 0)
            des[i] = sig

    elif idea_id == "17_BTC_GOLD_ROTATION":
        # Trend-follow BTC/Gold ratio > SMA30 (digital gold outperformance regime)
        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 == "18_ETF_FLOW_MOM_HYBRID":
        # Pre-2024: 5d BTC momentum; 2024+: 5d/10d net ETF flow sign
        ef = df["etf_sum5"].values if scale <= 1.0 else df["etf_sum10"].values
        dr = df["d_ret5"].values if scale <= 1.0 else df["d_ret10"].values
        is_etf = (df.index >= "2024-01-12")
        for i in range(n):
            if is_etf[i]:
                if not np.isnan(ef[i]) and ef[i] != 0.0:
                    des[i] = 1 if ef[i] > 0 else -1
            else:
                if not np.isnan(dr[i]) and abs(dr[i]) > 0.02 * scale:
                    des[i] = 1 if dr[i] > 0 else -1

    return des


# ==============================================================================
# 4. UNIFIED BACKTESTER, METRICS & PLACEBO
# ==============================================================================

def run_signal_backtest(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))

        # Intraday 2.0x daily ATR(14) hard stop
        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 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_date_shuffle_placebo(df, desired_arr, 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)]

    beat = 0
    for _ in range(n_sims):
        perm = rng.permutation(n_days)
        shuf = np.zeros_like(desired_arr)
        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] = desired_arr[sb[take]]
        _, sim_eq = run_signal_backtest(df, shuf, start_date="2018-01-01")
        if actual_mar > calc_stats(sim_eq)["mar"]:
            beat += 1
    return 100.0 * beat / n_sims


# ==============================================================================
# 5. MAIN 2-STAGE EXECUTION & STRICT MULTIPLE-TESTING GATE
# ==============================================================================

IDEAS = [
    "00_BASELINE_EMA20_50",
    "01_BB_ZSCORE_MR",
    "02_CONNORS_RSI2_PULLBACK",
    "03_CAPITULATION_VOL_SPIKE",
    "04_OVERNIGHT_REVERSAL",
    "05_NR7_INSIDE_BREAKOUT",
    "06_KELTNER_SQUEEZE_BO",
    "07_DONCHIAN_48H_96H",
    "08_VOL_EXPANSION_MOM",
    "09_US_SESSION_MOM",
    "10_ASIA_FADE_EU",
    "11_WEEKEND_DRIFT_REV",
    "12_FUNDING_TIMESTAMP_PRE",
    "13_NEG_FUNDING_SQUEEZE",
    "14_FUNDING_CARRY_TREND",
    "15_FUNDING_DIVERGENCE",
    "16_SPY_LEAD_CRYPTO",
    "17_BTC_GOLD_ROTATION",
    "18_ETF_FLOW_MOM_HYBRID",
]


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

    res = {}
    base_ret = None
    for idea in IDEAS:
        des = get_desired_signals(df, idea, scale=1.0)
        tr_df, eq_s = run_signal_backtest(df, des, 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)

        r_daily = eq_s.pct_change().dropna()
        if idea == "00_BASELINE_EMA20_50":
            base_ret = r_daily
            corr = 1.0
        else:
            common = base_ret.index.intersection(r_daily.index)
            if len(common) > 10 and np.std(r_daily.loc[common].values) > 1e-12:
                corr = float(np.corrcoef(base_ret.loc[common].values, r_daily.loc[common].values)[0, 1])
            else:
                corr = 0.0

        res[idea] = {
            "Asset": asset_name,
            "Idea": idea,
            "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),
            "CorrBase": round(corr, 2),
            "Yearly": yr,
            "Placebo%": np.nan,
            "NbrPass%": np.nan,
        }
        print(f"{idea:<26} | Tr={len(tr_df):<4} | CAGR={res[idea]['CAGR%']:>6.2f}% | DD={res[idea]['MaxDD%']:>5.2f}% | MAR={res[idea]['MAR']:>5.2f} (H1={res[idea]['MAR_18_21']:>4.2f}, H2={res[idea]['MAR_22_26']:>4.2f}) | PF={res[idea]['PF']:>4.2f} | Corr={corr:>5.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)
    eth_df = build_features(eth_1h, fund_8h, etf_d, macro_d)

    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"]

    # Stage 2: Identify Stage-1 survivors that clear dual-half MAR, MaxDD, and yearly breadth gates
    print("\n" + "=" * 116)
    print("STAGE 2: PLACEBO (100-RUN) & 0.5x/1.5x NEIGHBOUR VALIDATION ON STAGE-1 CANDIDATES")
    print("=" * 116)

    candidates = []
    for idea in IDEAS[1:]:
        rb, re = btc_res[idea], eth_res[idea]
        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):
            candidates.append(idea)

    # Always validate top-2 BTC MAR ideas as well so placebo/neighbour diagnostics are visible even if 0 pass
    top2_by_mar = sorted(IDEAS[1:], key=lambda x: btc_res[x]["MAR"], reverse=True)[:2]
    to_validate = list(dict.fromkeys(candidates + top2_by_mar))

    kept = []
    for idea in to_validate:
        rb, re = btc_res[idea], eth_res[idea]
        des_10 = get_desired_signals(btc_df, idea, scale=1.0)
        plac = run_date_shuffle_placebo(btc_df, des_10, rb["MAR"], n_sims=100, seed=42)

        nbr_mars = []
        for sc in [0.5, 1.5]:
            des_sc = get_desired_signals(btc_df, idea, scale=sc)
            _, eq_sc = run_signal_backtest(btc_df, des_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[idea]["Placebo%"] = round(plac, 1)
        btc_res[idea]["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(idea)

        print(f"  {idea:<26}: Halves={halves_ok} | DD_OK={dd_ok} | BTC_Yrs={btc_yrs}/9 | ETH_Yrs={eth_yrs}/9 | Placebo={plac:.1f}% | Nbrs(0.5x/1.5x)={nbr_mars[0]:.2f}/{nbr_mars[1]:.2f} ({nbr_pct:.0f}%) -> {'KEEP' if passed else 'FAIL'}")

    # Compact Combined Summary Table
    rows = []
    for asset_name, rmap in [("BTC", btc_res), ("ETH", eth_res)]:
        for idea in IDEAS:
            r = rmap[idea]
            rows.append({
                "Asset": asset_name,
                "Idea": idea,
                "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"],
                "Corr": r["CorrBase"],
                "Plac%": r["Placebo%"],
                "Nbr%": r["NbrPass%"],
            })

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

    print("\n" + "=" * 116)
    if len(kept) >= 2:
        print(f"VERDICT: KEEP ({', '.join(kept)}) — Multiple independent orthogonal engines cleared all strict BTC/ETH & multiple-testing gates.")
    elif len(kept) == 1:
        print(f"VERDICT: KEEP WITH MULTIPLE-TESTING CAUTION ({kept[0]}) — Only 1/18 ideas passed (expected false-positive count at 10% alpha across 18 trials = 1.8); verify out-of-sample before live sizing.")
    else:
        print("VERDICT: FAIL — 0 of 18 orthogonal ideas cleared the strict dual-half, MaxDD, BTC/ETH yearly, placebo, and neighbour plateau gates.")
    print("=" * 116)


if __name__ == "__main__":
    main()