#!/usr/bin/env python3
"""
M35 Macro Risk-On Size Dial Enhancement & ETF-Era Adaptation Research (2018-2026)
- Base M35 (5-factor score, 0-5, lagged 1 day):
  +1 each for: US10Y < SMA20, DXY < SMA50, TIP > SMA20, HYG > SMA50, Copper/Gold > SMA50
  * Score >= 4: Longs x1.5, Shorts x0.5
  * Score <= 1: Longs x0.5, Shorts x1.5
  * Score 2-3 : Longs x1.0, Shorts x1.0
- Stand-in Strategy:
  Daily EMA20 / EMA50 trend long/short, 2.0x daily ATR(14) stops, 1.0% base risk per trade
  (scaled by M35 size dial at entry), next-bar 00:00 UTC open entries, 0.12%/side fees
- Evaluates 6th-factor & replacement variants for 2024-26 ETF-era resilience:
  1. BASE_M35            : Original 5-factor macro dial
  2. M35_PLUS_SMA200     : 6th factor = BTC Close > SMA200 (0-6 scale: >=4 / <=1)
  3. M35_PLUS_ETF10D     : 6th factor = BTC ETF 10d net flows > 0 (post-2024; neutral/SMA200 fallback pre-2024)
  4. M35_PLUS_FUNDING    : 6th factor = Contrarian/Healthy Funding (7d avg 8h funding < 0.03% & > -0.02%, or <= 0.01% carry)
  5. M35_PLUS_BTCSPY     : 6th factor = BTC/SPY relative strength > SMA50
  6. M35_PLUS_BREADTH    : 6th factor = BTC 20d Donchian/Momentum breakout (Close > SMA50 & ROC20 > 0)
  7. M35_REGIME_SWITCH   : Dynamic regime-switching weight (pre-2024: 100% Macro 5-factor; 2024+: 50% Macro + 50% Crypto-Native [ETF flows + SMA200 + BTC/SPY])
  8. M35_REPLACE_CU_ETF  : Replace Copper/Gold with BTC/SPY (pre-2024) -> ETF 10d flows (2024+)
- Metrics: Full-sample CAGR, MaxDD, MAR, 2018-22 MAR, 2024-26 CAGR/MAR, per-year returns (2018-2026),
  and 100-run shuffled-score-date placebo test.
"""

import warnings
warnings.filterwarnings("ignore")

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

# ==============================================================================
# 1. DATA LOADING & PREPROCESSING
# ==============================================================================

UA_OPTS = {"User-Agent": "Mozilla/5.0"}

def load_btc_1h(url):
    print(f"Downloading BTC 1h data from {url}...")
    df = pd.read_csv(url, compression="gzip", storage_options=UA_OPTS)
    df.columns = [c.strip().lower() for c in df.columns]
    time_col = [c for c in df.columns if "time" in c or "date" in c][0]
    if pd.api.types.is_numeric_dtype(df[time_col]):
        df["time"] = pd.to_datetime(df[time_col], unit="ms", utc=True)
    else:
        try:
            df["time"] = pd.to_datetime(pd.to_numeric(df[time_col]), unit="ms", utc=True)
        except Exception:
            df["time"] = pd.to_datetime(df[time_col], utc=True)
    df = df.sort_values("time").drop_duplicates("time").set_index("time")
    df = df[["open", "high", "low", "close", "volume"]].astype(float)
    df = df[df.index >= "2017-06-01"]
    print(f"  -> Loaded BTC 1h: {len(df)} bars ({df.index.min().date()} to {df.index.max().date()})")
    return df


def load_etf_flows(url):
    try:
        print(f"Downloading BTC ETF flows from {url}...")
        df = pd.read_csv(url, compression="gzip", storage_options=UA_OPTS)
        df.columns = [c.strip().lower() for c in df.columns]
        date_col = [c for c in df.columns if "date" in c or "time" in c][0]
        if pd.api.types.is_numeric_dtype(df[date_col]):
            unit = "ms" if df[date_col].iloc[0] > 1e11 else "s"
            df["dt"] = pd.to_datetime(df[date_col], unit=unit, utc=True)
        else:
            df["dt"] = pd.to_datetime(df[date_col], utc=True)
        df = df.sort_values("dt").drop_duplicates("dt").set_index("dt")
        df.index = df.index.floor("D")

        # Identify net flow column robustly
        cand_cols = [c for c in df.columns if any(k in c for k in ["net", "total", "flow", "btc", "usd"])]
        if not cand_cols:
            cand_cols = [c for c in df.select_dtypes(include=[np.number]).columns]
        flow_col = None
        for prefer in ["net_flow", "total_net_flow", "netflow", "total", "flow"]:
            matches = [c for c in cand_cols if prefer in c]
            if matches:
                flow_col = matches[0]
                break
        if flow_col is None:
            flow_col = cand_cols[0]

        s = pd.to_numeric(df[flow_col], errors="coerce").groupby(level=0).sum()
        print(f"  -> Loaded ETF flows ({flow_col}): {len(s)} days ({s.index.min().date()} to {s.index.max().date()})")
        return s
    except Exception as e:
        print(f"  [WARN] Could not load ETF flows: {e}")
        return pd.Series(dtype=float)


def load_funding_8h(url):
    try:
        print(f"Downloading BTC 8h funding from {url}...")
        comp = "gzip" if url.endswith(".gz") else "infer"
        df = pd.read_csv(url, compression=comp, storage_options=UA_OPTS)
        df.columns = [c.strip().lower() for c in df.columns]
        time_col = [c for c in df.columns if "time" in c or "date" in c][0]
        if pd.api.types.is_numeric_dtype(df[time_col]):
            unit = "ms" if df[time_col].iloc[0] > 1e11 else "s"
            df["dt"] = pd.to_datetime(df[time_col], unit=unit, utc=True)
        else:
            try:
                num_t = pd.to_numeric(df[time_col])
                unit = "ms" if num_t.iloc[0] > 1e11 else "s"
                df["dt"] = pd.to_datetime(num_t, unit=unit, utc=True)
            except Exception:
                df["dt"] = pd.to_datetime(df[time_col], utc=True)
        df = df.sort_values("dt").set_index("dt")

        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 = list(df.select_dtypes(include=[np.number]).columns)
        rcol = rate_cols[0]
        s_raw = pd.to_numeric(df[rcol], errors="coerce").dropna()
        # Resample 8h funding to daily mean (per 8h period)
        s_daily = s_raw.resample("1D").mean()
        s_daily.index = s_daily.index.floor("D")
        print(f"  -> Loaded Funding ({rcol}): {len(s_daily)} daily rows ({s_daily.index.min().date()} to {s_daily.index.max().date()})")
        return s_daily
    except Exception as e:
        print(f"  [WARN] Could not load funding data: {e}")
        return pd.Series(dtype=float)


def load_yfinance_daily(tickers_dict, start="2017-01-01"):
    macro = {}
    for key, ticker in tickers_dict.items():
        try:
            print(f"Downloading {key} ({ticker}) via yfinance...")
            data = yf.download(ticker, start=start, progress=False, auto_adjust=True)
            if isinstance(data.columns, pd.MultiIndex):
                data.columns = data.columns.get_level_values(0)
            data.columns = [c.strip().lower() for c in data.columns]
            if len(data) > 50:
                s = data["close"].copy()
                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")
                macro[key] = s.groupby(level=0).last().sort_index()
                print(f"  -> Loaded {key}: {len(macro[key])} daily rows")
            else:
                print(f"  [WARN] Insufficient rows for {key}")
        except Exception as e:
            print(f"  [ERROR] Failed to download {key} ({ticker}): {e}")
    return pd.DataFrame(macro)


# ==============================================================================
# 2. FEATURE ENGINEERING & M35 DIAL VARIANTS (STRICT 1-DAY LAG)
# ==============================================================================

def score_to_multipliers(score_series, high_th=4.0, low_th=1.0):
    """
    Maps a risk-on score series to (long_mult, short_mult):
      score >= high_th -> (1.5, 0.5)
      score <= low_th  -> (0.5, 1.5)
      otherwise        -> (1.0, 1.0)
    """
    l_mult = pd.Series(1.0, index=score_series.index)
    s_mult = pd.Series(1.0, index=score_series.index)
    l_mult[score_series >= high_th] = 1.5
    s_mult[score_series >= high_th] = 0.5
    l_mult[score_series <= low_th] = 0.5
    s_mult[score_series <= low_th] = 1.5
    return l_mult, s_mult


def build_daily_and_1h_features(btc_1h, macro_daily, etf_flows, funding_daily):
    """
    Builds daily EMA20/EMA50 trend signals, ATR14, all macro & crypto-native factors,
    and shifts all daily features by +1 day before joining onto 1h bars (strict no-lookahead).
    """
    daily = btc_1h.resample("1D").agg({
        "open": "first",
        "high": "max",
        "low": "min",
        "close": "last",
        "volume": "sum"
    }).dropna(subset=["open", "high", "low", "close"])
    daily.index = daily.index.floor("D")

    # Daily ATR(14)
    prev_close = daily["close"].shift(1)
    tr = pd.concat([
        daily["high"] - daily["low"],
        (daily["high"] - prev_close).abs(),
        (daily["low"] - prev_close).abs()
    ], axis=1).max(axis=1)
    daily["atr14"] = tr.rolling(14).mean()

    # Stand-in Strategy Indicators: Daily EMA20 & EMA50
    daily["ema20"] = daily["close"].ewm(span=20, adjust=False).mean()
    daily["ema50"] = daily["close"].ewm(span=50, adjust=False).mean()
    daily["sma50"] = daily["close"].rolling(50).mean()
    daily["sma200"] = daily["close"].rolling(200).mean()
    daily["roc20"] = daily["close"].pct_change(20)

    # Align macro series (forward-fill weekends/holidays)
    m = macro_daily.reindex(daily.index, method="ffill")

    dxy_col = "dxy" if ("dxy" in m.columns and m["dxy"].notna().sum() > 200) else "uup"
    f_us10y = (m["us10y"] < m["us10y"].rolling(20).mean()).astype(float)
    f_dxy = (m[dxy_col] < m[dxy_col].rolling(50).mean()).astype(float)
    f_tip = (m["tip"] > m["tip"].rolling(20).mean()).astype(float)
    f_hyg = (m["hyg"] > m["hyg"].rolling(50).mean()).astype(float)
    cu_au = m["copper"] / m["gold"].replace(0, np.nan)
    f_cuau = (cu_au > cu_au.rolling(50).mean()).astype(float)

    base_score = f_us10y + f_dxy + f_tip + f_hyg + f_cuau
    daily["base_m35_score"] = base_score

    # Candidate 1: BTC above its own SMA200
    f_sma200 = (daily["close"] > daily["sma200"]).astype(float)
    daily["f_sma200"] = f_sma200

    # Candidate 2: BTC ETF net flows 10-day sum > 0 (from Jan 2024; neutral 0.5 pre-ETF so 2018-22 is untouched)
    etf_aligned = etf_flows.reindex(daily.index).fillna(0.0)
    etf_10d = etf_aligned.rolling(10, min_periods=1).sum()
    has_etf_era = (daily.index >= "2024-01-11") & (etf_aligned.rolling(10).apply(lambda x: np.abs(x).sum() > 0, raw=True).fillna(0) > 0)
    f_etf10d = pd.Series(0.5, index=daily.index)
    f_etf10d[has_etf_era] = (etf_10d[has_etf_era] > 0).astype(float)
    daily["f_etf10d"] = f_etf10d
    daily["has_etf_era"] = has_etf_era.astype(float)

    # Candidate 3: Funding rate (7-day rolling mean of 8h funding)
    # Healthy/non-overheated bull demand: funding > -0.0001 (-0.01%) and < 0.00035 (+0.035% per 8h)
    # Or positive carry regime without extreme crowding: (fund_7d > 0) & (fund_7d < 0.0004)
    if funding_daily is not None and not funding_daily.empty:
        fund_aligned = funding_daily.reindex(daily.index).ffill()
        fund_7d = fund_aligned.rolling(7, min_periods=1).mean()
        has_fund = fund_7d.notna()
        f_fund = pd.Series(0.5, index=daily.index)
        # Positive demand (> 0) without extreme long crowding (< 0.035% / 8h) = 1.0, else 0.0
        f_fund[has_fund] = ((fund_7d[has_fund] > 0.0) & (fund_7d[has_fund] < 0.00035)).astype(float)
    else:
        f_fund = pd.Series(0.5, index=daily.index)
    daily["f_funding"] = f_fund

    # Candidate 4: BTC/SPY relative strength > SMA50
    if "spy" in m.columns:
        btc_spy = daily["close"] / m["spy"].replace(0, np.nan)
        f_btcspy = (btc_spy > btc_spy.rolling(50).mean()).astype(float)
    else:
        f_btcspy = pd.Series(0.5, index=daily.index)
    daily["f_btcspy"] = f_btcspy

    # Candidate 5 (Added): BTC Trend Breadth (Close > SMA50 & 20d ROC > 0)
    f_breadth = ((daily["close"] > daily["sma50"]) & (daily["roc20"] > 0)).astype(float)
    daily["f_breadth"] = f_breadth

    # Build Variant Dial Multipliers (all computed on day D, shifted +1 day below)
    variants = {}

    # 1. BASE_M35 (5-factor: >=4 / <=1)
    l1, s1 = score_to_multipliers(base_score, high_th=4.0, low_th=1.0)
    variants["1_BASE_M35"] = (l1, s1, base_score)

    # 2. M35_PLUS_SMA200 (6-factor: >=4.0 / <=1.5)
    sc2 = base_score + f_sma200
    l2, s2 = score_to_multipliers(sc2, high_th=4.0, low_th=1.5)
    variants["2_M35_PLUS_SMA200"] = (l2, s2, sc2)

    # 3. M35_PLUS_ETF10D (5-factor pre-2024; 6-factor with ETF 10d sum > 0 in 2024+)
    # Pre-2024 f_etf10d=0.5 -> score is x.5, so >=4.5 means base>=4, <=1.5 means base<=1 (100% identical to BASE_M35 pre-2024!)
    # In 2024+ f_etf10d in {0, 1} -> score >=4 triggers on (base>=3 & ETF+) or (base>=4 & ETF-), score <=1 requires (base<=1 & ETF-)
    sc3 = base_score + f_etf10d
    l3, s3 = score_to_multipliers(sc3, high_th=4.0, low_th=1.5)
    variants["3_M35_PLUS_ETF10D"] = (l3, s3, sc3)

    # 4. M35_PLUS_FUNDING (6-factor with 7d funding filter; neutral 0.5 before funding history starts)
    sc4 = base_score + f_fund
    l4, s4 = score_to_multipliers(sc4, high_th=4.0, low_th=1.5)
    variants["4_M35_PLUS_FUNDING"] = (l4, s4, sc4)

    # 5. M35_PLUS_BTCSPY (6-factor with BTC/SPY > SMA50)
    sc5 = base_score + f_btcspy
    l5, s5 = score_to_multipliers(sc5, high_th=4.0, low_th=1.5)
    variants["5_M35_PLUS_BTCSPY"] = (l5, s5, sc5)

    # 6. M35_PLUS_BREADTH (6-factor with BTC > SMA50 & ROC20 > 0)
    sc6 = base_score + f_breadth
    l6, s6 = score_to_multipliers(sc6, high_th=4.0, low_th=1.5)
    variants["6_M35_PLUS_BREADTH"] = (l6, s6, sc6)

    # 7. M35_REGIME_SWITCH:
    # Pre-2024 (pre-ETF): 100% Macro 5-factor score (exact BASE_M35)
    # 2024+ (ETF era): 50% Macro score (0-5) + 50% Crypto-Flow composite (5 * avg(f_etf10d, f_sma200, f_btcspy))
    crypto_comp_5 = 5.0 * (f_etf10d + f_sma200 + f_btcspy) / 3.0
    sc7 = np.where(daily.index >= "2024-01-11", 0.5 * base_score + 0.5 * crypto_comp_5, base_score)
    sc7 = pd.Series(sc7, index=daily.index)
    l7, s7 = score_to_multipliers(sc7, high_th=3.5, low_th=1.5)
    # Preserve exact BASE_M35 thresholds (>=4 / <=1) prior to 2024-01-11
    pre_mask = daily.index < "2024-01-11"
    l7[pre_mask], s7[pre_mask] = l1[pre_mask], s1[pre_mask]
    variants["7_M35_REGIME_SWITCH"] = (l7, s7, sc7)

    # 8. M35_REPLACE_CU_ETF:
    # Replace Copper/Gold (5th factor) with BTC/SPY (pre-2024) and ETF 10d flows (2024+)
    f_5th_rep = np.where(daily.index >= "2024-01-11", f_etf10d, f_btcspy)
    sc8 = f_us10y + f_dxy + f_tip + f_hyg + pd.Series(f_5th_rep, index=daily.index)
    l8, s8 = score_to_multipliers(sc8, high_th=4.0, low_th=1.0)
    variants["8_M35_REPLACE_CU_ETF"] = (l8, s8, sc8)

    # Store all variant multipliers into daily DataFrame before 1-day shift
    for vname, (lm, sm, sc) in variants.items():
        daily[f"{vname}_L"] = lm
        daily[f"{vname}_S"] = sm
        daily[f"{vname}_SC"] = sc

    # STRICT 1-DAY LAG: signal & dial computed on day D close are only actionable on day D+1
    daily_lagged = daily.shift(1)

    df_1h = btc_1h.copy()
    df_1h["day_floor"] = df_1h.index.floor("D")
    merged = df_1h.join(daily_lagged, on="day_floor", rsuffix="_d")
    merged.drop(columns=["day_floor"], inplace=True)
    merged["is_day_open"] = (merged.index.hour == 0)

    return merged, daily_lagged, list(variants.keys())


# ==============================================================================
# 3. STAND-IN STRATEGY BACKTEST ENGINE (EMA20/50 + 2-ATR STOP + 1% RISK)
# ==============================================================================

FEE_PER_SIDE = 0.0012   # 0.12% per side
BASE_RISK_PCT = 0.01    # 1.0% base risk per trade (scaled by M35 dial: 0.5%, 1.0%, or 1.5%)
ATR_STOP_MULT = 2.0     # 2.0x daily ATR(14) stop
MAX_LEVERAGE = 3.0      # Cap notional exposure at 3x equity

def run_ema_standin_backtest(df, l_mult_arr, s_mult_arr, start_date="2018-01-01"):
    """
    Runs daily EMA20/EMA50 trend-following long/short strategy on 1h bars:
    - Enters at 00:00 UTC bar open when lagged daily EMA20 > EMA50 (Long) or EMA20 < EMA50 (Short)
    - Exits/flips when daily EMA20/EMA50 crosses against position or 2.0x ATR(14) hard stop is hit
    - Position size = (Base 1% Risk * Dial_Mult) / Stop_Distance_Pct (capped at MAX_LEVERAGE)
    - Returns trade list + daily equity curve (2018-01-01 through end of dataset)
    """
    sub = df[df.index >= start_date]
    n_bars = len(sub)

    opens = sub["open"].values
    highs = sub["high"].values
    lows = sub["low"].values
    closes = sub["close"].values
    ema20 = sub["ema20"].values
    ema50 = sub["ema50"].values
    atrs = sub["atr14"].values
    is_open = sub["is_day_open"].values
    times = sub.index

    # Map full-df multiplier arrays onto sub slice
    idx_pos = df.index.get_indexer(sub.index)
    l_mults = l_mult_arr[idx_pos]
    s_mults = s_mult_arr[idx_pos]

    equity = 1.0
    pos_dir = 0          # 0 = flat, +1 = long, -1 = short
    entry_price = 0.0
    stop_price = 0.0
    notional_lev = 0.0
    entry_time = None

    trades = []
    daily_eq = {}

    for i in range(n_bars):
        # Record daily mark-to-market equity at 23:00 UTC (end of UTC day)
        if pos_dir != 0:
            unr_ret = pos_dir * (closes[i] - entry_price) / entry_price
            mtm_eq = equity * (1.0 + notional_lev * (unr_ret - FEE_PER_SIDE))
        else:
            mtm_eq = equity

        if times[i].hour == 23 or i == n_bars - 1:
            daily_eq[times[i].floor("D")] = max(mtm_eq, 1e-6)

        # 1. Check intraday 2.0x ATR hard stop
        if pos_dir == 1 and lows[i] <= stop_price:
            exit_px = min(opens[i], stop_price)
            net_ret = (exit_px - entry_price) / entry_price - 2.0 * FEE_PER_SIDE
            equity *= (1.0 + notional_lev * net_ret)
            trades.append({"entry_time": entry_time, "exit_time": times[i], "dir": 1, "lev": notional_lev, "net_ret": net_ret, "pnl_eq": notional_lev * net_ret})
            pos_dir = 0
            continue
        elif pos_dir == -1 and highs[i] >= stop_price:
            exit_px = max(opens[i], stop_price)
            net_ret = (entry_price - exit_px) / entry_price - 2.0 * FEE_PER_SIDE
            equity *= (1.0 + notional_lev * net_ret)
            trades.append({"entry_time": entry_time, "exit_time": times[i], "dir": -1, "lev": notional_lev, "net_ret": net_ret, "pnl_eq": notional_lev * net_ret})
            pos_dir = 0
            continue

        # 2. Check daily 00:00 UTC trend signal (based on prior day close)
        if not is_open[i]:
            continue
        if np.isnan(ema20[i]) or np.isnan(ema50[i]) or np.isnan(atrs[i]) or atrs[i] <= 0:
            continue

        desired_dir = 1 if ema20[i] > ema50[i] else -1

        # Exit existing position if trend flipped
        if pos_dir != 0 and pos_dir != desired_dir:
            exit_px = opens[i]
            net_ret = pos_dir * (exit_px - entry_price) / entry_price - 2.0 * FEE_PER_SIDE
            equity *= (1.0 + notional_lev * net_ret)
            trades.append({"entry_time": entry_time, "exit_time": times[i], "dir": pos_dir, "lev": notional_lev, "net_ret": net_ret, "pnl_eq": notional_lev * net_ret})
            pos_dir = 0

        # Enter new position if flat
        if pos_dir == 0:
            entry_price = opens[i]
            stop_dist_pct = (ATR_STOP_MULT * atrs[i]) / entry_price
            stop_dist_pct = max(stop_dist_pct, 0.005)
            dial = l_mults[i] if desired_dir == 1 else s_mults[i]
            if np.isnan(dial):
                dial = 1.0
            risk_budget = BASE_RISK_PCT * dial
            notional_lev = min(risk_budget / stop_dist_pct, MAX_LEVERAGE)
            stop_price = entry_price * (1.0 - desired_dir * stop_dist_pct)
            pos_dir = desired_dir
            entry_time = times[i]

    eq_series = pd.Series(daily_eq).sort_index()
    return pd.DataFrame(trades), eq_series


# ==============================================================================
# 4. METRICS, PERIOD SPLITS & 100-RUN SHUFFLED-SCORE PLACEBO
# ==============================================================================

def compute_period_metrics(eq_series, start_dt=None, end_dt=None):
    s = eq_series.copy()
    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) < 10:
        return {"cagr": 0.0, "max_dd": 0.0, "mar": 0.0}

    # Rebase equity to start of window
    s = s / s.iloc[0]
    days = max((s.index[-1] - s.index[0]).days, 1)
    years = days / 365.25
    cagr = (s.iloc[-1] ** (1.0 / years) - 1.0) * 100.0
    dd_series = s / s.cummax() - 1.0
    max_dd = abs(float(dd_series.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 compute_yearly_returns(eq_series):
    yr_rets = {}
    years = sorted(eq_series.index.year.unique())
    prev_end = 1.0
    for yr in years:
        sub = eq_series[eq_series.index.year == yr]
        if sub.empty:
            continue
        end_val = float(sub.iloc[-1])
        yr_rets[int(yr)] = round((end_val / prev_end - 1.0) * 100.0, 1)
        prev_end = end_val
    return yr_rets


def run_shuffled_score_placebo(df, daily_lagged, vname, actual_mar, n_sims=100, seed=42):
    """
    Shuffles the daily (L_mult, S_mult) pairs across dates (preserving exact marginal
    distribution of dial multipliers while destroying date alignment) and re-runs the
    EMA20/50 backtest 100 times to compute % of runs beaten by actual MAR.
    """
    rng = np.random.default_rng(seed)
    valid_days = daily_lagged.index[daily_lagged.index >= "2018-01-01"]
    l_daily = daily_lagged.loc[valid_days, f"{vname}_L"].fillna(1.0).values
    s_daily = daily_lagged.loc[valid_days, f"{vname}_S"].fillna(1.0).values
    n_days = len(valid_days)

    day_to_pos = pd.Series(np.arange(n_days), index=valid_days)
    bar_day_pos = day_to_pos.reindex(df.index.floor("D")).fillna(0).astype(int).values

    beat_count = 0
    for _ in range(n_sims):
        perm = rng.permutation(n_days)
        shuf_l = l_daily[perm][bar_day_pos]
        shuf_s = s_daily[perm][bar_day_pos]
        _, sim_eq = run_ema_standin_backtest(df, shuf_l, shuf_s, start_date="2018-01-01")
        sim_m = compute_period_metrics(sim_eq)
        if actual_mar > sim_m["mar"]:
            beat_count += 1

    return 100.0 * beat_count / n_sims


# ==============================================================================
# 5. MAIN EXECUTION & REPORTING
# ==============================================================================

def main():
    btc_url = "https://osom-boba.pages.dev/colab/btc_1h_full.csv.gz"
    etf_url = "https://osom-boba.pages.dev/colab/btc_etf_flows.csv.gz"
    fund_url = "https://osom-boba.pages.dev/colab/btc_funding_8h.csv"

    btc_1h = load_btc_1h(btc_url)
    etf_flows = load_etf_flows(etf_url)
    funding_daily = load_funding_8h(fund_url)

    macro_tickers = {
        "tip": "TIP",
        "us10y": "^TNX",
        "dxy": "DX-Y.NYB",
        "uup": "UUP",
        "gold": "GC=F",
        "copper": "HG=F",
        "hyg": "HYG",
        "spy": "SPY"
    }
    macro_daily = load_yfinance_daily(macro_tickers, start="2017-01-01")

    print("\nBuilding 1-day lagged M35 dial variants & EMA20/50 features...")
    df, daily_lagged, variant_names = build_daily_and_1h_features(btc_1h, macro_daily, etf_flows, funding_daily)

    results = []
    yearly_table = {}
    base_metrics = None

    print("\n" + "=" * 108)
    print("M35 SIZE DIAL VARIANTS — STAND-IN DAILY EMA20/50 TREND STRATEGY (2.0x ATR STOP, 1% BASE RISK, 0.12% FEE/SIDE)")
    print("=" * 108)

    for vname in variant_names:
        l_arr = df[f"{vname}_L"].fillna(1.0).values
        s_arr = df[f"{vname}_S"].fillna(1.0).values

        trades_df, eq_series = run_ema_standin_backtest(df, l_arr, s_arr, start_date="2018-01-01")
        m_all = compute_period_metrics(eq_series)
        m_18_22 = compute_period_metrics(eq_series, start_dt="2018-01-01", end_dt="2022-12-31")
        m_24_26 = compute_period_metrics(eq_series, start_dt="2024-01-01")
        yr_rets = compute_yearly_returns(eq_series)
        placebo_pct = run_shuffled_score_placebo(df, daily_lagged, vname, m_all["mar"], n_sims=100, seed=42)

        row = {
            "Variant": vname,
            "Trades": len(trades_df),
            "CAGR%": round(m_all["cagr"], 2),
            "MaxDD%": round(m_all["max_dd"], 2),
            "MAR": round(m_all["mar"], 2),
            "MAR_18_22": round(m_18_22["mar"], 2),
            "CAGR_24_26%": round(m_24_26["cagr"], 2),
            "MAR_24_26": round(m_24_26["mar"], 2),
            "Placebo%": int(round(placebo_pct))
        }
        results.append(row)
        yearly_table[vname] = yr_rets

        if vname == "1_BASE_M35":
            base_metrics = row

        print(f"\n[{vname}]")
        print(f"  Full (2018-26): CAGR={row['CAGR%']:.2f}% | MaxDD={row['MaxDD%']:.2f}% | MAR={row['MAR']:.2f} | Trades={row['Trades']} | Placebo={row['Placebo%']}%")
        print(f"  Sub-Periods   : 2018-22 MAR={row['MAR_18_22']:.2f} (CAGR {m_18_22['cagr']:.1f}%, DD {m_18_22['max_dd']:.1f}%) | 2024-26 MAR={row['MAR_24_26']:.2f} (CAGR {row['CAGR_24_26%']:.1f}%, DD {m_24_26['max_dd']:.1f}%)")
        print(f"  Per-Year (%)  : {yr_rets}")

    res_df = pd.DataFrame(results)

    print("\n" + "=" * 108)
    print("SUMMARY COMPARISON TABLE (2018-2026)")
    print("=" * 108)
    print(res_df.to_string(index=False))

    print("\n" + "=" * 108)
    print("PER-YEAR RETURNS TABLE (%, 2018-2026)")
    print("=" * 108)
    yr_df = pd.DataFrame(yearly_table).T
    yr_df.index.name = "Variant"
    print(yr_df.to_string())

    # --------------------------------------------------------------------------
    # VERDICT SELECTION:
    # Best variant ONLY IF it beats BASE_M35 in 2024-26 (both MAR & CAGR)
    # AND does not lose more than 10% of BASE_M35 MAR in 2018-22.
    # --------------------------------------------------------------------------
    print("\n" + "=" * 108)
    print("FINAL VERDICT (CRITERIA: BEATS BASE M35 IN 2024-26 AND 2018-22 MAR >= 0.90 * BASE 2018-22 MAR)")
    print("=" * 108)

    base_mar_18_22 = base_metrics["MAR_18_22"]
    base_mar_24_26 = base_metrics["MAR_24_26"]
    base_cagr_24_26 = base_metrics["CAGR_24_26%"]
    min_allowed_18_22_mar = 0.90 * base_mar_18_22

    print(f"Base M35 Benchmarks -> 2018-22 MAR: {base_mar_18_22:.2f} (90% floor = {min_allowed_18_22_mar:.2f}) | 2024-26 MAR: {base_mar_24_26:.2f}, CAGR: {base_cagr_24_26:.2f}%")

    qualifying = []
    for r in results:
        if r["Variant"] == "1_BASE_M35":
            continue
        beats_24_26 = (r["MAR_24_26"] > base_mar_24_26) and (r["CAGR_24_26%"] > base_cagr_24_26)
        preserves_18_22 = (r["MAR_18_22"] >= min_allowed_18_22_mar)
        status = "PASS" if (beats_24_26 and preserves_18_22) else "FAIL"
        print(f"  - {r['Variant']:<22}: 2024-26 MAR={r['MAR_24_26']:.2f} (CAGR {r['CAGR_24_26%']:.2f}%), 2018-22 MAR={r['MAR_18_22']:.2f} -> {status}")
        if status == "PASS":
            qualifying.append(r)

    if qualifying:
        best = sorted(qualifying, key=lambda x: (x["MAR_24_26"], x["MAR"]), reverse=True)[0]
        print(f"\nWINNER: {best['Variant']} | Full MAR={best['MAR']:.2f} (CAGR={best['CAGR%']:.2f}%, MaxDD={best['MaxDD%']:.2f}%) | 2024-26 MAR={best['MAR_24_26']:.2f} (vs Base {base_mar_24_26:.2f}) | 2018-22 MAR={best['MAR_18_22']:.2f} (vs Base {base_mar_18_22:.2f}) | Placebo={best['Placebo%']}%")
    else:
        print("\nWINNER: NONE — No candidate beat Base M35 in 2024-26 while keeping >= 90% of Base M35 2018-22 MAR.")


if __name__ == "__main__":
    main()
