#!/usr/bin/env python3
"""
BTC & ETH Multi-Day Futures Setup Research & Backtest Suite — Batch 3 (2017-2026)
- Focuses strictly on regime-persistent macro & cross-asset signals (2021-26 PF priority)
- Replaces fixed-day holds / wide 7.5% stops with regime-exit triggers + 2.5x daily ATR(14) stops (capped <= 10%)
- Includes 10 new ideas (#21 to #30): regime fixes for #18 & #11, multi-macro composites, and >=3 macro tightening shorts
- Strict no-lookahead (daily/macro features shifted +1 day), next-bar 00:00 UTC open entries, 0.12%/side fees, 100-run placebo
"""

import warnings
warnings.filterwarnings("ignore")

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

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

def load_crypto_1h(url, name):
    try:
        print(f"Downloading {name} 1h data from {url}...")
        df = pd.read_csv(url, compression="gzip", storage_options={"User-Agent": "Mozilla/5.0"})
        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:
                numeric_ts = pd.to_numeric(df[time_col])
                df["time"] = pd.to_datetime(numeric_ts, 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-01-01"]
        print(f"  -> Loaded {name}: {len(df)} bars ({df.index.min().date()} to {df.index.max().date()})")
        return df
    except Exception as e:
        print(f"  [ERROR] Failed to load {name}: {e}")
        return None


def load_yfinance_daily(tickers_dict, start="2016-06-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")
                macro[key] = s.sort_index()
                print(f"  -> Loaded {key}: {len(s)} 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 (STRICT NO-LOOKAHEAD)
# ==============================================================================

def build_features(df_1h, other_1h, macro_daily):
    """
    Constructs hourly and lagged daily features.
    CRITICAL NO-LOOKAHEAD RULE:
    Daily bars stamped at 00:00 UTC represent calendar day D.
    A 1h bar on day D can ONLY see daily values up to day D-1.
    All daily features are shifted by +1 day before joining onto 1h bars.
    """
    df = df_1h.copy()

    daily = df.resample("1D").agg({
        "open": "first",
        "high": "max",
        "low": "min",
        "close": "last",
        "volume": "sum"
    }).dropna(subset=["open", "high", "low", "close"])

    # Daily True Range & ATR(14) for 2.5x ATR stop sizing
    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()

    # Crypto trend & returns
    daily["sma_20d"] = daily["close"].rolling(20).mean()
    daily["sma_50d"] = daily["close"].rolling(50).mean()
    daily["sma_100d"] = daily["close"].rolling(100).mean()
    daily["ret_10d"] = daily["close"].pct_change(10)
    daily["ret_20d"] = daily["close"].pct_change(20)
    daily["high_60d"] = daily["high"].rolling(60).max()
    daily["low_60d"] = daily["low"].rolling(60).min()

    # Cross-asset ETH / BTC ratio (or peer ratio)
    if other_1h is not None:
        other_daily = other_1h.resample("1D").agg({"close": "last"}).dropna()
        aligned_other = other_daily["close"].reindex(daily.index, method="ffill")
        daily["peer_ret_20d"] = aligned_other.pct_change(20)
        daily["rel_20d"] = daily["ret_20d"] - daily["peer_ret_20d"]

    # Macro daily indicators (forward-filled across weekends/holidays before lag)
    if macro_daily is not None and not macro_daily.empty:
        m = macro_daily.reindex(daily.index, method="ffill")

        # 1. USD/JPY (#18 fix)
        if "usdjpy" in m.columns:
            daily["usdjpy"] = m["usdjpy"]
            daily["usdjpy_sma20"] = m["usdjpy"].rolling(20).mean()
            daily["usdjpy_sma50"] = m["usdjpy"].rolling(50).mean()
            daily["usdjpy_ret10"] = m["usdjpy"].pct_change(10)

        # 2. TIP ETF / Real Yields (#11 fix)
        if "tip" in m.columns:
            daily["tip"] = m["tip"]
            daily["tip_sma20"] = m["tip"].rolling(20).mean()
            daily["tip_sma50"] = m["tip"].rolling(50).mean()
            daily["tip_ret15"] = m["tip"].pct_change(15)

        # 3. US 10Y Nominal Yield (^TNX)
        if "us10y" in m.columns:
            daily["us10y"] = m["us10y"]
            daily["us10y_sma20"] = m["us10y"].rolling(20).mean()
            daily["us10y_sma50"] = m["us10y"].rolling(50).mean()
            daily["us10y_chg15"] = m["us10y"].diff(15)

        # 4. DXY Dollar Index (DX-Y.NYB, fallback to UUP ETF if unavailable)
        dxy_col = "dxy" if ("dxy" in m.columns and m["dxy"].notna().sum() > 200) else ("uup" if "uup" in m.columns else None)
        if dxy_col is not None:
            daily["dxy"] = m[dxy_col]
            daily["dxy_sma20"] = m[dxy_col].rolling(20).mean()
            daily["dxy_sma50"] = m[dxy_col].rolling(50).mean()
            daily["dxy_ret20"] = m[dxy_col].pct_change(20)

        # 5. Gold (GC=F) & Crypto/Gold Ratio
        if "gold" in m.columns:
            daily["gold"] = m["gold"]
            daily["gold_sma50"] = m["gold"].rolling(50).mean()
            cg_ratio = daily["close"] / m["gold"].replace(0, np.nan)
            daily["cg_ratio"] = cg_ratio
            daily["cg_ratio_max90"] = cg_ratio.rolling(90).max()
            daily["cg_ratio_sma50"] = cg_ratio.rolling(50).mean()

        # 6. Copper / Gold Reflation vs Deflationary Tightening Ratio
        if "copper" in m.columns and "gold" in m.columns:
            cu_au = m["copper"] / m["gold"].replace(0, np.nan)
            daily["cu_au"] = cu_au
            daily["cu_au_sma20"] = cu_au.rolling(20).mean()
            daily["cu_au_sma50"] = cu_au.rolling(50).mean()

        # 7. High-Yield Credit ETF (HYG) Risk Appetite vs Stress
        if "hyg" in m.columns:
            daily["hyg"] = m["hyg"]
            daily["hyg_sma20"] = m["hyg"].rolling(20).mean()
            daily["hyg_sma50"] = m["hyg"].rolling(50).mean()

    # Shift ALL daily columns by 1 day so day D-1 close/stats are only visible on day D
    daily_lagged = daily.shift(1)
    daily_lagged.index = daily_lagged.index.floor("D")

    df["day_floor"] = df.index.floor("D")
    merged = df.join(daily_lagged, on="day_floor", rsuffix="_d")
    merged.drop(columns=["day_floor"], inplace=True)

    # Trigger only at 00:00 UTC bar (when prior-day daily signal becomes available)
    merged["is_day_open"] = (merged.index.hour == 0)

    return merged


# ==============================================================================
# 3. BATCH 3 STRATEGY DEFINITIONS (#21 - #30: REGIME-PERSISTENT + 2.5 ATR STOP)
# ==============================================================================

def generate_signals(df):
    """
    Each strategy dict supports:
      - 'entry': Series (+1 long, -1 short, 0 flat) evaluated at bar close -> enters next bar open
      - 'exit_long': Boolean Series (True on day open when long regime breaks -> exits at bar open)
      - 'exit_short': Boolean Series (True on day open when short regime breaks -> exits at bar open)
      - 'max_hold_bars': Safety cap (up to 30 days = 720 bars)
      - 'atr_stop_mult': Stop loss = atr_stop_mult * prior-day ATR(14), capped at 10%
      - 'tp_pct': Optional take profit (None for pure regime-hold runners)
    """
    strategies = {}
    day_trig = df["is_day_open"]

    # --------------------------------------------------------------------------
    # IDEA 21 (#18 FIX): USD/JPY Carry Regime Hold (21_YEN_CARRY_REGIME)
    # --------------------------------------------------------------------------
    e21 = pd.Series(0, index=df.index)
    xl21 = pd.Series(False, index=df.index)
    xs21 = pd.Series(False, index=df.index)
    if "usdjpy" in df.columns:
        e21[day_trig & (df["usdjpy"] > df["usdjpy_sma20"]) & (df["usdjpy"] > df["usdjpy_sma50"]) & (df["close_d"] > df["sma_50d"])] = 1
        e21[day_trig & (df["usdjpy"] < df["usdjpy_sma20"]) & (df["usdjpy"] < df["usdjpy_sma50"]) & (df["close_d"] < df["sma_50d"])] = -1
        xl21 = day_trig & ((df["usdjpy"] < df["usdjpy_sma20"]) | (df["close_d"] < df["sma_50d"]))
        xs21 = day_trig & ((df["usdjpy"] > df["usdjpy_sma20"]) | (df["close_d"] > df["sma_50d"]))
    strategies["21_YEN_CARRY_REGIME"] = {
        "logic": "Fix for #18: hold carry-on longs while USDJPY > SMA20 & BTC > SMA50 (and carry-unwind shorts below), with 2.5 ATR stop.",
        "rule": "Long if USDJPY > SMA20 & SMA50 & close > SMA50 (inverse short); exit when USDJPY or close crosses SMA20/50; 2.5 ATR stop, 30d cap.",
        "entry": e21, "exit_long": xl21, "exit_short": xs21, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 22 (#11 FIX): TIPS Real-Yield Regime Hold (22_REAL_YIELD_REGIME)
    # --------------------------------------------------------------------------
    e22 = pd.Series(0, index=df.index)
    xl22 = pd.Series(False, index=df.index)
    xs22 = pd.Series(False, index=df.index)
    if "tip" in df.columns:
        e22[day_trig & (df["tip"] > df["tip_sma20"]) & (df["tip"] > df["tip_sma50"]) & (df["close_d"] > df["sma_50d"])] = 1
        e22[day_trig & (df["tip"] < df["tip_sma20"]) & (df["tip"] < df["tip_sma50"]) & (df["close_d"] < df["sma_50d"])] = -1
        xl22 = day_trig & ((df["tip"] < df["tip_sma20"]) | (df["close_d"] < df["sma_50d"]))
        xs22 = day_trig & ((df["tip"] > df["tip_sma20"]) | (df["close_d"] > df["sma_50d"]))
    strategies["22_REAL_YIELD_REGIME"] = {
        "logic": "Fix for #11: ride falling real-yield regimes while TIP > SMA20 & BTC > SMA50 (and rising real-yield shorts below).",
        "rule": "Long if TIP > SMA20 & SMA50 & close > SMA50 (inverse short); exit when TIP crosses SMA20 or close crosses SMA50; 2.5 ATR stop, 30d cap.",
        "entry": e22, "exit_long": xl22, "exit_short": xs22, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 23 (LONG ONLY): Triple Macro Liquidity Alignment (23_TRIPLE_MACRO_LONG)
    # --------------------------------------------------------------------------
    e23 = pd.Series(0, index=df.index)
    xl23 = pd.Series(False, index=df.index)
    if "us10y" in df.columns and "dxy" in df.columns:
        e23[day_trig & (df["us10y"] < df["us10y_sma20"]) & (df["dxy"] < df["dxy_sma50"]) & (df["close_d"] > df["sma_50d"])] = 1
        xl23 = day_trig & ((df["us10y"] > df["us10y_sma20"]) | (df["close_d"] < df["sma_50d"]))
    strategies["23_TRIPLE_MACRO_LONG"] = {
        "logic": "Long only when falling 10Y yields (<SMA20) and weak Dollar (<SMA50) align with BTC uptrend (>SMA50).",
        "rule": "Long when US10Y < SMA20, DXY < SMA50, close > SMA50; exit when US10Y > SMA20 or close < SMA50; 2.5 ATR stop, 30d cap.",
        "entry": e23, "exit_long": xl23, "exit_short": pd.Series(False, index=df.index), "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 24 (LONG ONLY): 10Y Yield Drop + DXY + Gold Debasement Alignment (24_DEBASEMENT_LONG)
    # --------------------------------------------------------------------------
    e24 = pd.Series(0, index=df.index)
    xl24 = pd.Series(False, index=df.index)
    if "us10y" in df.columns and "gold" in df.columns:
        e24[day_trig & (df["us10y"] < df["us10y_sma50"]) & (df["gold"] > df["gold_sma50"]) & (df["close_d"] > df["sma_50d"])] = 1
        xl24 = day_trig & ((df["us10y"] > df["us10y_sma50"]) | (df["close_d"] < df["sma_50d"]))
    strategies["24_DEBASEMENT_LONG"] = {
        "logic": "Combines falling 10Y yields (<SMA50) with rising Gold (>SMA50) and BTC > SMA50 to isolate pure fiat-debasement rallies.",
        "rule": "Long when US10Y < SMA50, Gold > SMA50, close > SMA50; exit when US10Y > SMA50 or close < SMA50; 2.5 ATR stop, 30d cap.",
        "entry": e24, "exit_long": xl24, "exit_short": pd.Series(False, index=df.index), "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 25 (LONG ONLY): Crypto/Gold 90d Ratio Breakout + Macro Tailwind (25_CG_RATIO_MACRO)
    # --------------------------------------------------------------------------
    e25 = pd.Series(0, index=df.index)
    xl25 = pd.Series(False, index=df.index)
    if "cg_ratio" in df.columns and "us10y" in df.columns:
        e25[day_trig & (df["cg_ratio"] >= df["cg_ratio_max90"] * 0.999) & (df["us10y"] < df["us10y_sma50"]) & (df["close_d"] > df["sma_50d"])] = 1
        xl25 = day_trig & ((df["cg_ratio"] < df["cg_ratio_sma50"]) | (df["close_d"] < df["sma_50d"]))
    strategies["25_CG_RATIO_MACRO"] = {
        "logic": "Enhances the 90d Crypto/Gold high signal by requiring falling 10Y yields (<SMA50) and holding until ratio < SMA50.",
        "rule": "Long when Crypto/Gold == 90d high, US10Y < SMA50, close > SMA50; exit when Crypto/Gold < SMA50 or close < SMA50; 2.5 ATR stop.",
        "entry": e25, "exit_long": xl25, "exit_short": pd.Series(False, index=df.index), "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 26 (LONG ONLY): Laggard Catch-Up Under Easing Yields (26_LAGGARD_EASING_LONG)
    # --------------------------------------------------------------------------
    e26 = pd.Series(0, index=df.index)
    xl26 = pd.Series(False, index=df.index)
    if "rel_20d" in df.columns and "us10y" in df.columns:
        e26[day_trig & (df["rel_20d"] <= -0.08) & (df["close_d"] > df["sma_50d"]) & (df["us10y"] < df["us10y_sma20"])] = 1
        xl26 = day_trig & ((df["rel_20d"] >= 0.0) | (df["close_d"] < df["sma_50d"]))
    strategies["26_LAGGARD_EASING_LONG"] = {
        "logic": "Pairs the ETH/BTC 20d <= -8% laggard catch-up edge with falling 10Y yields (<SMA20) and exits once spread closes.",
        "rule": "Long when 20d return lags peer by >=8%, close > SMA50, US10Y < SMA20; exit when spread >= 0% or close < SMA50; 2.5 ATR stop.",
        "entry": e26, "exit_long": xl26, "exit_short": pd.Series(False, index=df.index), "max_hold_bars": 20 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 27 (SHORT ONLY #1): Twin Tightening — Rising 10Y + Rising DXY (27_TWIN_TIGHTEN_SHORT)
    # --------------------------------------------------------------------------
    e27 = pd.Series(0, index=df.index)
    xs27 = pd.Series(False, index=df.index)
    if "us10y" in df.columns and "dxy" in df.columns:
        e27[day_trig & (df["us10y"] > df["us10y_sma20"]) & (df["dxy"] > df["dxy_sma50"]) & (df["close_d"] < df["sma_50d"])] = -1
        xs27 = day_trig & ((df["us10y"] < df["us10y_sma20"]) | (df["close_d"] > df["sma_50d"]))
    strategies["27_TWIN_TIGHTEN_SHORT"] = {
        "logic": "SHORT #1: Rising 10Y yields (>SMA20) + rising DXY (>SMA50) drains global dollar liquidity while BTC < SMA50.",
        "rule": "Short when US10Y > SMA20, DXY > SMA50, close < SMA50; exit when US10Y < SMA20 or close > SMA50; 2.5 ATR stop, 30d cap.",
        "entry": e27, "exit_long": pd.Series(False, index=df.index), "exit_short": xs27, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 28 (SHORT ONLY #2): Real-Yield Spike + DXY Surge Tightening (28_REAL_YIELD_DXY_SHORT)
    # --------------------------------------------------------------------------
    e28 = pd.Series(0, index=df.index)
    xs28 = pd.Series(False, index=df.index)
    if "tip" in df.columns and "dxy" in df.columns:
        e28[day_trig & (df["tip"] < df["tip_sma20"]) & (df["dxy"] > df["dxy_sma20"]) & (df["close_d"] < df["sma_50d"])] = -1
        xs28 = day_trig & ((df["tip"] > df["tip_sma20"]) | (df["close_d"] > df["sma_50d"]))
    strategies["28_REAL_YIELD_DXY_SHORT"] = {
        "logic": "SHORT #2: Falling TIPS (rising real yields) + rising DXY (>SMA20) compresses speculative valuations below SMA50.",
        "rule": "Short when TIP < SMA20, DXY > SMA20, close < SMA50; exit when TIP > SMA20 or close > SMA50; 2.5 ATR stop, 30d cap.",
        "entry": e28, "exit_long": pd.Series(False, index=df.index), "exit_short": xs28, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 29 (SHORT ONLY #3): Yen Carry Unwind + Rising 10Y Shock (29_YEN_UNWIND_SHORT)
    # --------------------------------------------------------------------------
    e29 = pd.Series(0, index=df.index)
    xs29 = pd.Series(False, index=df.index)
    if "usdjpy" in df.columns:
        e29[day_trig & (df["usdjpy"] < df["usdjpy_sma20"]) & (df["usdjpy_ret10"] < -0.012) & (df["close_d"] < df["sma_50d"])] = -1
        xs29 = day_trig & ((df["usdjpy"] > df["usdjpy_sma20"]) | (df["close_d"] > df["sma_50d"]))
    strategies["29_YEN_UNWIND_SHORT"] = {
        "logic": "SHORT #3: Sustained Yen appreciation (USDJPY < SMA20 & 10d ret < -1.2%) forces carry-trade deleveraging below SMA50.",
        "rule": "Short when USDJPY < SMA20 & 10d ret < -1.2% & close < SMA50; exit when USDJPY > SMA20 or close > SMA50; 2.5 ATR stop, 25d cap.",
        "entry": e29, "exit_long": pd.Series(False, index=df.index), "exit_short": xs29, "max_hold_bars": 25 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 30 (SHORT ONLY #4): Credit Stress + Deflationary Copper/Gold Tightening (30_CREDIT_DEFLATION_SHORT)
    # --------------------------------------------------------------------------
    e30 = pd.Series(0, index=df.index)
    xs30 = pd.Series(False, index=df.index)
    if "hyg" in df.columns and "cu_au" in df.columns and "dxy" in df.columns:
        e30[day_trig & (df["hyg"] < df["hyg_sma50"]) & (df["cu_au"] < df["cu_au_sma50"]) & (df["dxy"] > df["dxy_sma50"]) & (df["close_d"] < df["sma_50d"])] = -1
        xs30 = day_trig & ((df["hyg"] > df["hyg_sma20"]) | (df["close_d"] > df["sma_50d"]))
    strategies["30_CREDIT_DEFLATION_SHORT"] = {
        "logic": "SHORT #4: High-yield credit stress (HYG < SMA50) + falling Copper/Gold + strong DXY signals risk-off contraction.",
        "rule": "Short when HYG < SMA50, Copper/Gold < SMA50, DXY > SMA50, close < SMA50; exit when HYG > SMA20 or close > SMA50; 2.5 ATR stop.",
        "entry": e30, "exit_long": pd.Series(False, index=df.index), "exit_short": xs30, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    return strategies


# ==============================================================================
# 4. BACKTEST ENGINE & METRICS (REGIME EXIT + 2.5 ATR STOP CAPPED AT 10%)
# ==============================================================================

FEE_PER_SIDE = 0.0012  # 0.12% per side (0.24% round-trip)

def backtest_strategy(df, strat, start_date="2017-01-01"):
    sub = df[df.index >= start_date]
    opens = sub["open"].values
    highs = sub["high"].values
    lows = sub["low"].values
    closes = sub["close"].values
    atrs = sub["atr14"].values
    times = sub.index

    entries = strat["entry"].reindex(sub.index).fillna(0).values
    exit_l = strat["exit_long"].reindex(sub.index).fillna(False).values
    exit_s = strat["exit_short"].reindex(sub.index).fillna(False).values

    max_hold = strat["max_hold_bars"]
    atr_mult = strat["atr_stop_mult"]
    tp_pct = strat["tp_pct"]

    n_bars = len(sub)
    trades = []
    i = 0

    while i < n_bars - 2:
        sig = entries[i]
        if sig == 0:
            i += 1
            continue

        entry_idx = i + 1
        entry_price = opens[entry_idx]
        atr_val = atrs[i]
        if np.isnan(entry_price) or entry_price <= 0 or np.isnan(atr_val) or atr_val <= 0:
            i += 1
            continue

        direction = int(sig)
        # Dynamic 2.5x daily ATR stop, strictly capped at 10%
        stop_dist_pct = min((atr_mult * atr_val) / entry_price, 0.10)
        hard_stop = entry_price * (1.0 - direction * stop_dist_pct)
        tp_price = entry_price * (1.0 + direction * tp_pct) if tp_pct is not None else None

        max_exit_idx = min(entry_idx + max_hold, n_bars - 1)
        exit_idx = max_exit_idx
        exit_price = closes[exit_idx]
        exit_reason = "MAX_HOLD"

        for j in range(entry_idx, max_exit_idx + 1):
            # 1. Check regime-break exit at 00:00 UTC open (after entry bar)
            if j > entry_idx:
                if direction == 1 and exit_l[j]:
                    exit_idx = j
                    exit_price = opens[j]
                    exit_reason = "REGIME_EXIT"
                    break
                elif direction == -1 and exit_s[j]:
                    exit_idx = j
                    exit_price = opens[j]
                    exit_reason = "REGIME_EXIT"
                    break

            # 2. Check intra-bar 2.5 ATR hard stop
            if direction == 1 and lows[j] <= hard_stop:
                exit_idx = j
                exit_price = min(opens[j], hard_stop) if j > entry_idx else hard_stop
                exit_reason = "ATR_STOP"
                break
            elif direction == -1 and highs[j] >= hard_stop:
                exit_idx = j
                exit_price = max(opens[j], hard_stop) if j > entry_idx else hard_stop
                exit_reason = "ATR_STOP"
                break

            # 3. Check optional Take Profit
            if tp_price is not None:
                if direction == 1 and highs[j] >= tp_price:
                    exit_idx = j
                    exit_price = max(opens[j], tp_price) if j > entry_idx else tp_price
                    exit_reason = "TP"
                    break
                elif direction == -1 and lows[j] <= tp_price:
                    exit_idx = j
                    exit_price = min(opens[j], tp_price) if j > entry_idx else tp_price
                    exit_reason = "TP"
                    break

        gross_ret = direction * (exit_price - entry_price) / entry_price
        net_ret = gross_ret - 2.0 * FEE_PER_SIDE

        trades.append({
            "entry_time": times[entry_idx],
            "exit_time": times[exit_idx],
            "year": times[entry_idx].year,
            "dir": direction,
            "bars": exit_idx - entry_idx + 1,
            "stop_pct": stop_dist_pct,
            "net_ret": net_ret,
            "reason": exit_reason
        })

        i = exit_idx + 1

    return pd.DataFrame(trades)


def compute_pf(rets):
    if len(rets) == 0:
        return 0.0
    wins = rets[rets > 0].sum()
    losses = -rets[rets < 0].sum()
    if losses == 0:
        return 99.0 if wins > 0 else 0.0
    return float(wins / losses)


def run_placebo(df, trades_df, strat, n_sims=100, seed=42):
    if len(trades_df) < 5:
        return 0.0

    rng = np.random.default_rng(seed)
    opens = df["open"].values
    highs = df["high"].values
    lows = df["low"].values
    closes = df["close"].values
    n_bars = len(df)

    dirs = trades_df["dir"].values
    holds = trades_df["bars"].values
    stop_pcts = trades_df["stop_pct"].values
    n_trades = len(trades_df)
    tp_pct = strat["tp_pct"]
    actual_pf = compute_pf(trades_df.get("net_ret", pd.Series(dtype=float)).values)

    max_hold = int(holds.max()) + 2
    if n_bars <= max_hold + 10:
        return 0.0

    beat_count = 0
    for _ in range(n_sims):
        rand_starts = rng.integers(1, n_bars - max_hold, size=n_trades)
        sim_rets = np.empty(n_trades)
        for k in range(n_trades):
            s_idx = rand_starts[k]
            d = dirs[k]
            h = holds[k]
            sp = stop_pcts[k]
            ep = opens[s_idx]
            hs = ep * (1.0 - d * sp)
            tp = ep * (1.0 + d * tp_pct) if tp_pct is not None else None
            end_k = min(s_idx + h, n_bars - 1)
            xp = closes[end_k]
            for j in range(s_idx, end_k + 1):
                if d == 1 and lows[j] <= hs:
                    xp = hs
                    break
                elif d == -1 and highs[j] >= hs:
                    xp = hs
                    break
                if tp is not None:
                    if d == 1 and highs[j] >= tp:
                        xp = tp
                        break
                    elif d == -1 and lows[j] <= tp:
                        xp = tp
                        break
            sim_rets[k] = d * (xp - ep) / ep - 2.0 * FEE_PER_SIDE
        if actual_pf > compute_pf(sim_rets):
            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"
    eth_url = "https://osom-boba.pages.dev/colab/eth_1h_full.csv.gz"

    btc_1h = load_crypto_1h(btc_url, "BTC")
    eth_1h = load_crypto_1h(eth_url, "ETH")

    if btc_1h is None:
        print("CRITICAL: Could not load BTC data. Exiting.")
        return

    macro_tickers = {
        "usdjpy": "JPY=X",
        "tip": "TIP",
        "us10y": "^TNX",
        "dxy": "DX-Y.NYB",
        "uup": "UUP",
        "gold": "GC=F",
        "copper": "HG=F",
        "hyg": "HYG"
    }
    macro_daily = load_yfinance_daily(macro_tickers, start="2016-06-01")
    if "usdjpy" in macro_daily.columns and macro_daily["usdjpy"].dropna().median() < 1.0:
        macro_daily["usdjpy"] = 1.0 / macro_daily["usdjpy"]

    print("\nBuilding strict no-lookahead macro & regime features...")
    btc_feat = build_features(btc_1h, eth_1h, macro_daily)
    eth_feat = build_features(eth_1h, btc_1h, macro_daily) if eth_1h is not None else None

    btc_strats = generate_signals(btc_feat)
    eth_strats = generate_signals(eth_feat) if eth_feat is not None else {}

    years_span = max((btc_feat.index.max() - btc_feat.index.min()).days / 365.25, 1.0)
    summary_rows = []

    print("\n" + "=" * 100)
    print("BATCH 3 STRATEGY RESULTS (BTC 2017-2026 | REGIME HOLD + 2.5 ATR STOP | 0.12% FEE/SIDE)")
    print("=" * 100)

    for name, strat in btc_strats.items():
        t_btc = backtest_strategy(btc_feat, strat, start_date="2017-01-01")
        n = len(t_btc)
        trades_yr = n / years_span

        if n > 0:
            pf_all = compute_pf(t_btc.get("net_ret", pd.Series(dtype=float)).values)
            t_h1 = t_btc[t_btc["year"] <= 2020]
            t_h2 = t_btc[t_btc["year"] >= 2021]
            pf_17_20 = compute_pf(t_h1.get("net_ret", pd.Series(dtype=float)).values)
            pf_21_26 = compute_pf(t_h2.get("net_ret", pd.Series(dtype=float)).values)

            eq = (1.0 + t_btc["net_ret"]).cumprod()
            dd = (eq / eq.cummax() - 1.0).min() * 100.0
            avg_hold_d = round(t_btc["bars"].mean() / 24.0, 1)

            yr_pfs = {}
            for yr in sorted(t_btc["year"].unique()):
                yr_pfs[int(yr)] = round(compute_pf(t_btc[t_btc["year"] == yr].get("net_ret", pd.Series(dtype=float)).values), 2)
        else:
            pf_all = pf_17_20 = pf_21_26 = dd = avg_hold_d = 0.0
            yr_pfs = {}

        if eth_feat is not None and name in eth_strats:
            t_eth = backtest_strategy(eth_feat, eth_strats[name], start_date="2017-01-01")
            eth_pf = compute_pf(t_eth.get("net_ret", pd.Series(dtype=float)).values)
        else:
            eth_pf = 0.0

        placebo = run_placebo(btc_feat[btc_feat.index >= "2017-01-01"], t_btc, strat, n_sims=100)

        if (pf_17_20 > 1.3) and (pf_21_26 > 1.3) and (n >= 30) and (eth_pf > 1.0) and (placebo >= 90.0):
            verdict = "KEEP"
        elif (pf_all >= 1.1) and (n >= 60):
            verdict = "NEAR"
        else:
            verdict = "DROP"

        print(f"\n[{name}] -> VERDICT: {verdict}")
        print(f"  Logic : {strat['logic']}")
        print(f"  Rule  : {strat['rule']}")
        print(f"  Stats : n={n} ({trades_yr:.1f}/yr, avg {avg_hold_d}d) | PF={pf_all:.2f} | PF_17-20={pf_17_20:.2f} | PF_21-26={pf_21_26:.2f} | ETH_PF={eth_pf:.2f} | MaxDD={dd:.1f}% | Placebo={placebo:.0f}%")
        print(f"  ByYr  : {yr_pfs}")

        summary_rows.append({
            "Idea": name,
            "n": n,
            "Tr/Yr": round(trades_yr, 1),
            "HoldD": avg_hold_d,
            "PF": round(pf_all, 2),
            "PF_17_20": round(pf_17_20, 2),
            "PF_21_26": round(pf_21_26, 2),
            "ETH_PF": round(eth_pf, 2),
            "MaxDD%": round(dd, 1),
            "Placebo": int(round(placebo)),
            "Verdict": verdict
        })

    sum_df = pd.DataFrame(summary_rows)
    print("\n" + "=" * 100)
    print("SUMMARY TABLE (BATCH 3)")
    print("=" * 100)
    print(sum_df.to_string(index=False))

    print("\n" + "=" * 100)
    print("VERDICTS BLOCK (BATCH 3)")
    print("=" * 100)
    keeps = sum_df[sum_df["Verdict"] == "KEEP"]["Idea"].tolist()
    nears = sum_df[sum_df["Verdict"] == "NEAR"]["Idea"].tolist()
    drops = sum_df[sum_df["Verdict"] == "DROP"]["Idea"].tolist()
    print(f"KEEP ({len(keeps)}): {', '.join(keeps) if keeps else 'None'}")
    print(f"NEAR ({len(nears)}): {', '.join(nears) if nears else 'None'}")
    print(f"DROP ({len(drops)}): {', '.join(drops) if drops else 'None'}")


if __name__ == "__main__":
    main()
