#!/usr/bin/env python3
"""
BTC & ETH Multi-Day Futures Setup Research & Backtest Suite — Batch 4 (2017-2026)
- Goal: Preserve Batch-3 macro edge while scaling frequency to 10+ trades/yr (2021-26 PF > 1.3, ETH PF > 1.1)
- Includes:
  * 10 Main Batch-4 Strategies (#31 to #40):
    - #31 & #32: Loosened #22 TIP Real-Yield Regime (TIP > SMA20 only + BTC > SMA20 / SMA50)
    - #33, #34, #35: 5-Factor MACRO SCORE (0-5) long/short engines across thresholds 2 / 3 / 4
    - #36: Fixed #25 Crypto/Gold Ratio (>= 98% of 90d high + macro tailwind)
    - #37: Composite Macro Score + Crypto/Gold Momentum Hybrid (high-frequency macro trend)
    - #38, #39, #40: 3 Dedicated Macro-Score SHORT engines (tightening regimes below SMA50/SMA20)
  * Standalone TIP SMA Sweep Table (10 / 20 / 30 / 50 x BTC SMA20 / SMA50)
- Strict no-lookahead (all daily/macro features shifted +1 day), next-bar 00:00 UTC open entries
- 0.12%/side fees, 2.5x daily ATR(14) stop (capped <= 10%), 100-run placebo, zero-trade ETH crash guards
"""

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, 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 filters
    daily["sma_20d"] = daily["close"].rolling(20).mean()
    daily["sma_50d"] = daily["close"].rolling(50).mean()

    # 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")

        # TIP ETF (Real Yields) + SMA sweep lengths (10, 20, 30, 50)
        if "tip" in m.columns:
            daily["tip"] = m["tip"]
            for w in [10, 20, 30, 50]:
                daily[f"tip_sma{w}"] = m["tip"].rolling(w).mean()

        # 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()

        # DXY Dollar Index (DX-Y.NYB, fallback to UUP ETF)
        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()

        # High-Yield Credit ETF (HYG)
        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()

        # Copper / Gold Ratio & Crypto / Gold Ratio
        if "gold" in m.columns:
            daily["gold"] = m["gold"]
            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_sma20"] = cg_ratio.rolling(20).mean()
            daily["cg_ratio_sma50"] = cg_ratio.rolling(50).mean()

        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_sma50"] = cu_au.rolling(50).mean()

        # 5-Factor MACRO SCORE (0 to 5):
        # +1 each for: US10Y < SMA20, DXY < SMA50, TIP > SMA20, HYG > SMA50, Copper/Gold > SMA50
        f_us10y = (daily["us10y"] < daily["us10y_sma20"]).astype(float) if "us10y" in daily else 0.0
        f_dxy = (daily["dxy"] < daily["dxy_sma50"]).astype(float) if "dxy" in daily else 0.0
        f_tip = (daily["tip"] > daily["tip_sma20"]).astype(float) if "tip" in daily else 0.0
        f_hyg = (daily["hyg"] > daily["hyg_sma50"]).astype(float) if "hyg" in daily else 0.0
        f_cuau = (daily["cu_au"] > daily["cu_au_sma50"]).astype(float) if "cu_au" in daily else 0.0

        daily["macro_score"] = f_us10y + f_dxy + f_tip + f_hyg + f_cuau
        # Invalidate macro_score until core rolling 50d windows are warm
        warmup_mask = daily["sma_50d"].isna()
        if "dxy_sma50" in daily:
            warmup_mask = warmup_mask | daily["dxy_sma50"].isna()
        daily.loc[warmup_mask, "macro_score"] = np.nan

        # Individual sub-scores for specialized short engines
        daily["f_us10y_bull"] = f_us10y
        daily["f_dxy_bull"] = f_dxy
        daily["f_tip_bull"] = f_tip
        daily["f_hyg_bull"] = f_hyg
        daily["f_cuau_bull"] = f_cuau

    # 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 4 STRATEGY DEFINITIONS (#31 - #40)
# ==============================================================================

def build_tip_strategy(df, tip_win=20, btc_sma_col="sma_50d", label_override=None):
    day_trig = df["is_day_open"]
    tip_sma = f"tip_sma{tip_win}"
    e = pd.Series(0, index=df.index)
    xl = pd.Series(False, index=df.index)
    xs = pd.Series(False, index=df.index)
    if "tip" in df.columns and tip_sma in df.columns and btc_sma_col in df.columns:
        e[day_trig & (df["tip"] > df[tip_sma]) & (df["close_d"] > df[btc_sma_col])] = 1
        e[day_trig & (df["tip"] < df[tip_sma]) & (df["close_d"] < df[btc_sma_col])] = -1
        xl = day_trig & ((df["tip"] < df[tip_sma]) | (df["close_d"] < df[btc_sma_col]))
        xs = day_trig & ((df["tip"] > df[tip_sma]) | (df["close_d"] > df[btc_sma_col]))
    btc_tag = "SMA20" if btc_sma_col == "sma_20d" else "SMA50"
    return {
        "name": label_override or f"TIP_SMA{tip_win}_{btc_tag}",
        "logic": f"Loosened #22: hold directional regime while TIP vs SMA{tip_win} agrees with crypto vs {btc_tag} (no TIP SMA50 gate).",
        "rule": f"Long if TIP > SMA{tip_win} & close > {btc_tag} (inverse short); exit when either crosses; 2.5 ATR stop, 30d cap.",
        "entry": e, "exit_long": xl, "exit_short": xs, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }


def generate_signals(df):
    strategies = {}
    day_trig = df["is_day_open"]

    # --------------------------------------------------------------------------
    # IDEA 31: Loosened #22 — TIP > SMA20 Only + BTC > SMA50 (31_TIP20_BTC50)
    # --------------------------------------------------------------------------
    strategies["31_TIP20_BTC50"] = build_tip_strategy(df, tip_win=20, btc_sma_col="sma_50d", label_override="31_TIP20_BTC50")

    # --------------------------------------------------------------------------
    # IDEA 32: Loosened #22 Fast — TIP > SMA20 Only + BTC > SMA20 (32_TIP20_BTC20)
    # --------------------------------------------------------------------------
    strategies["32_TIP20_BTC20"] = build_tip_strategy(df, tip_win=20, btc_sma_col="sma_20d", label_override="32_TIP20_BTC20")

    # --------------------------------------------------------------------------
    # IDEA 33: MACRO SCORE Threshold 3 (Long >= 3 & > SMA50 | Short <= 1 & < SMA50)
    # --------------------------------------------------------------------------
    e33 = pd.Series(0, index=df.index)
    xl33 = pd.Series(False, index=df.index)
    xs33 = pd.Series(False, index=df.index)
    if "macro_score" in df.columns:
        ms = df["macro_score"]
        e33[day_trig & (ms >= 3) & (df["close_d"] > df["sma_50d"])] = 1
        e33[day_trig & (ms <= 1) & (df["close_d"] < df["sma_50d"])] = -1
        xl33 = day_trig & ((ms < 3) | (df["close_d"] < df["sma_50d"]))
        xs33 = day_trig & ((ms > 1) | (df["close_d"] > df["sma_50d"]))
    strategies["33_MACRO_SCORE_T3"] = {
        "logic": "5-factor Macro Score (US10Y<20, DXY<50, TIP>20, HYG>50, Cu/Au>50): Long >= 3 above SMA50, Short <= 1 below SMA50.",
        "rule": "Long if Score >= 3 & close > SMA50; Short if Score <= 1 & close < SMA50; exit on score/SMA50 break; 2.5 ATR stop, 30d cap.",
        "entry": e33, "exit_long": xl33, "exit_short": xs33, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 34: MACRO SCORE Threshold 2 High-Freq (Long >= 2 & > SMA50 | Short <= 2 & < SMA50)
    # --------------------------------------------------------------------------
    e34 = pd.Series(0, index=df.index)
    xl34 = pd.Series(False, index=df.index)
    xs34 = pd.Series(False, index=df.index)
    if "macro_score" in df.columns:
        ms = df["macro_score"]
        e34[day_trig & (ms >= 2) & (df["close_d"] > df["sma_50d"])] = 1
        e34[day_trig & (ms <= 2) & (df["close_d"] < df["sma_50d"])] = -1
        xl34 = day_trig & ((ms < 2) | (df["close_d"] < df["sma_50d"]))
        xs34 = day_trig & ((ms > 2) | (df["close_d"] > df["sma_50d"]))
    strategies["34_MACRO_SCORE_T2"] = {
        "logic": "Higher-frequency Macro Score sweep (T=2): Long when Score >= 2 above SMA50, Short when Score <= 2 below SMA50.",
        "rule": "Long if Score >= 2 & close > SMA50; Short if Score <= 2 & close < SMA50; exit on score/SMA50 break; 2.5 ATR stop, 30d cap.",
        "entry": e34, "exit_long": xl34, "exit_short": xs34, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 35: MACRO SCORE Threshold 4 High-Conviction (Long >= 4 & > SMA20 | Short == 0 & < SMA20)
    # --------------------------------------------------------------------------
    e35 = pd.Series(0, index=df.index)
    xl35 = pd.Series(False, index=df.index)
    xs35 = pd.Series(False, index=df.index)
    if "macro_score" in df.columns:
        ms = df["macro_score"]
        e35[day_trig & (ms >= 4) & (df["close_d"] > df["sma_20d"])] = 1
        e35[day_trig & (ms <= 0) & (df["close_d"] < df["sma_20d"])] = -1
        xl35 = day_trig & ((ms < 3) | (df["close_d"] < df["sma_50d"]))
        xs35 = day_trig & ((ms > 1) | (df["close_d"] > df["sma_50d"]))
    strategies["35_MACRO_SCORE_T4"] = {
        "logic": "Strict entry / hysteresis exit Macro Score (T=4): Long >= 4 above SMA20 (exit < 3), Short == 0 below SMA20 (exit > 1).",
        "rule": "Long if Score >= 4 & close > SMA20 (exit Score < 3 or < SMA50); Short if Score == 0 & close < SMA20 (exit > 1 or > SMA50); 2.5 ATR.",
        "entry": e35, "exit_long": xl35, "exit_short": xs35, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 36: Fixed #25 — Crypto/Gold >= 98% of 90d High + Macro Score >= 3
    # --------------------------------------------------------------------------
    e36 = pd.Series(0, index=df.index)
    xl36 = pd.Series(False, index=df.index)
    if "cg_ratio" in df.columns and "macro_score" in df.columns:
        e36[day_trig & (df["cg_ratio"] >= df["cg_ratio_max90"] * 0.98) & (df["macro_score"] >= 3) & (df["close_d"] > df["sma_50d"])] = 1
        xl36 = day_trig & ((df["cg_ratio"] < df["cg_ratio_sma20"]) | (df["close_d"] < df["sma_50d"]))
    strategies["36_CG_RATIO_98PCT"] = {
        "logic": "Fix for #25: triggers when Crypto/Gold ratio is >= 98% of its 90d high with Macro Score >= 3 and holds until < SMA20.",
        "rule": "Long if Crypto/Gold >= 0.98 * 90d_max, Macro Score >= 3, close > SMA50; exit if Crypto/Gold < SMA20 or close < SMA50; 2.5 ATR stop.",
        "entry": e36, "exit_long": xl36, "exit_short": pd.Series(False, index=df.index), "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 37: Macro Score >= 3 + Fast Trend Breakout (SMA20 Trigger, SMA50 Exit)
    # --------------------------------------------------------------------------
    e37 = pd.Series(0, index=df.index)
    xl37 = pd.Series(False, index=df.index)
    if "macro_score" in df.columns:
        ms = df["macro_score"]
        e37[day_trig & (ms >= 3) & (df["close_d"] > df["sma_20d"]) & (df["close_d"] > df["sma_50d"])] = 1
        xl37 = day_trig & ((ms <= 1) | (df["close_d"] < df["sma_50d"]))
    strategies["37_MACRO_HYSTERESIS_L"] = {
        "logic": "Long-only Macro Score >= 3 with hysteresis exit (holds through minor score dips until Score <= 1 or close < SMA50).",
        "rule": "Long if Macro Score >= 3 & close > SMA20 & SMA50; exit only when Score <= 1 or close < SMA50; 2.5 ATR stop, 30d cap.",
        "entry": e37, "exit_long": xl37, "exit_short": pd.Series(False, index=df.index), "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 38 (SHORT #1): Macro Score <= 1 + Close < SMA50 (38_MSCORE_SHORT_1)
    # --------------------------------------------------------------------------
    e38 = pd.Series(0, index=df.index)
    xs38 = pd.Series(False, index=df.index)
    if "macro_score" in df.columns:
        ms = df["macro_score"]
        e38[day_trig & (ms <= 1) & (df["close_d"] < df["sma_50d"])] = -1
        xs38 = day_trig & ((ms >= 3) | (df["close_d"] > df["sma_50d"]))
    strategies["38_MSCORE_SHORT_1"] = {
        "logic": "SHORT #1: Short when >= 4 of 5 macro factors are tightening (Macro Score <= 1) and BTC < SMA50; cover on Score >= 3.",
        "rule": "Short if Macro Score <= 1 & close < SMA50; exit when Macro Score >= 3 or close > SMA50; 2.5 ATR stop, 30d cap.",
        "entry": e38, "exit_long": pd.Series(False, index=df.index), "exit_short": xs38, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 39 (SHORT #2): Macro Score <= 2 + Fast Momentum Breakdown < SMA20 (39_MSCORE_SHORT_2)
    # --------------------------------------------------------------------------
    e39 = pd.Series(0, index=df.index)
    xs39 = pd.Series(False, index=df.index)
    if "macro_score" in df.columns:
        ms = df["macro_score"]
        e39[day_trig & (ms <= 2) & (df["close_d"] < df["sma_20d"]) & (df["close_d"] < df["sma_50d"])] = -1
        xs39 = day_trig & ((ms >= 3) | (df["close_d"] > df["sma_20d"]))
    strategies["39_MSCORE_SHORT_2"] = {
        "logic": "SHORT #2 (High-Freq): Short when Macro Score <= 2 & close < SMA20 & SMA50; cover swiftly if close reclaims SMA20.",
        "rule": "Short if Macro Score <= 2 & close < SMA20 & SMA50; exit when Macro Score >= 3 or close > SMA20; 2.5 ATR stop, 25d cap.",
        "entry": e39, "exit_long": pd.Series(False, index=df.index), "exit_short": xs39, "max_hold_bars": 25 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    # --------------------------------------------------------------------------
    # IDEA 40 (SHORT #3): Rates + Dollar Tightening Core (US10Y>20 & DXY>50 & TIP<20) (40_RATES_FX_SHORT)
    # --------------------------------------------------------------------------
    e40 = pd.Series(0, index=df.index)
    xs40 = pd.Series(False, index=df.index)
    if "macro_score" in df.columns:
        # Specifically requires all 3 monetary/FX tightening pillars (US10Y > SMA20, DXY > SMA50, TIP < SMA20) + close < SMA50
        tight_core = (df["f_us10y_bull"] == 0) & (df["f_dxy_bull"] == 0) & (df["f_tip_bull"] == 0)
        e40[day_trig & tight_core & (df["close_d"] < df["sma_50d"])] = -1
        xs40 = day_trig & ((~tight_core) | (df["close_d"] > df["sma_50d"]))
    strategies["40_RATES_FX_SHORT"] = {
        "logic": "SHORT #3: Pure monetary/FX tightening short — nominal yields up, real yields up, and DXY > SMA50 while BTC < SMA50.",
        "rule": "Short if US10Y > SMA20, TIP < SMA20, DXY > SMA50, close < SMA50; exit if any condition flips; 2.5 ATR stop, 30d cap.",
        "entry": e40, "exit_long": pd.Series(False, index=df.index), "exit_short": xs40, "max_hold_bars": 30 * 24, "atr_stop_mult": 2.5, "tp_pct": None
    }

    return strategies


# ==============================================================================
# 4. BACKTEST ENGINE & METRICS (WITH ZERO-TRADE ETH & PLACEBO GUARDS)
# ==============================================================================

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

def backtest_strategy(df, strat, start_date="2017-01-01"):
    if df is None or df.empty:
        return pd.DataFrame()

    sub = df[df.index >= start_date]
    if sub.empty:
        return pd.DataFrame()

    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)
        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):
            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

            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

            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 rets is None or 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 safe_eval_trades(trades_df, years_span):
    """Safely extracts metrics even if trades_df is empty (0 trades)."""
    if trades_df is None or trades_df.empty or "net_ret" not in trades_df.columns:
        return {
            "n": 0, "tr_yr": 0.0, "hold_d": 0.0,
            "pf": 0.0, "pf_17_20": 0.0, "pf_21_26": 0.0,
            "dd": 0.0, "by_yr": {}
        }
    n = len(trades_df)
    tr_yr = n / max(years_span, 1.0)
    hold_d = round(float(trades_df["bars"].mean() / 24.0), 1)
    pf_all = compute_pf(trades_df["net_ret"].values)
    t_h1 = trades_df[trades_df["year"] <= 2020]
    t_h2 = trades_df[trades_df["year"] >= 2021]
    pf_17_20 = compute_pf(t_h1["net_ret"].values) if not t_h1.empty else 0.0
    pf_21_26 = compute_pf(t_h2["net_ret"].values) if not t_h2.empty else 0.0
    eq = (1.0 + trades_df["net_ret"]).cumprod()
    dd = float((eq / eq.cummax() - 1.0).min() * 100.0)
    by_yr = {}
    for yr in sorted(trades_df["year"].unique()):
        by_yr[int(yr)] = round(compute_pf(trades_df[trades_df["year"] == yr]["net_ret"].values), 2)
    return {
        "n": n, "tr_yr": tr_yr, "hold_d": hold_d,
        "pf": pf_all, "pf_17_20": pf_17_20, "pf_21_26": pf_21_26,
        "dd": dd, "by_yr": by_yr
    }


def run_placebo(df, trades_df, strat, n_sims=100, seed=42):
    if trades_df is None or trades_df.empty or 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["net_ret"].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, TIP SWEEP TABLE & 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 or btc_1h.empty:
        print("CRITICAL: Could not load BTC data. Exiting.")
        return

    macro_tickers = {
        "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")

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

    btc_years = max((btc_feat.index.max() - btc_feat.index.min()).days / 365.25, 1.0)
    eth_years = max((eth_feat.index.max() - eth_feat.index.min()).days / 365.25, 1.0) if eth_feat is not None else 1.0
    btc_sub = btc_feat[btc_feat.index >= "2017-01-01"]

    # --------------------------------------------------------------------------
    # PART A: TIP SMA SWEEP TABLE (10 / 20 / 30 / 50 x BTC SMA20 / SMA50)
    # --------------------------------------------------------------------------
    print("\n" + "=" * 100)
    print("TIP SMA PARAMETER SWEEP (LOOSENED #22: TIP vs SMA_W & CRYPTO vs SMA20/50 | 2.5 ATR STOP)")
    print("=" * 100)
    sweep_rows = []
    for btc_col in ["sma_50d", "sma_20d"]:
        for tip_w in [10, 20, 30, 50]:
            st_b = build_tip_strategy(btc_feat, tip_win=tip_w, btc_sma_col=btc_col)
            tb = backtest_strategy(btc_feat, st_b, start_date="2017-01-01")
            mb = safe_eval_trades(tb, btc_years)
            if eth_feat is not None:
                st_e = build_tip_strategy(eth_feat, tip_win=tip_w, btc_sma_col=btc_col)
                te = backtest_strategy(eth_feat, st_e, start_date="2017-01-01")
                me = safe_eval_trades(te, eth_years)
                eth_pf_val = me["pf"]
            else:
                eth_pf_val = 0.0
            plac = run_placebo(btc_sub, tb, st_b, n_sims=100)
            sweep_rows.append({
                "Config": st_b["name"],
                "n": mb["n"],
                "Tr/Yr": round(mb["tr_yr"], 1),
                "HoldD": mb["hold_d"],
                "PF": round(mb["pf"], 2),
                "PF_17_20": round(mb["pf_17_20"], 2),
                "PF_21_26": round(mb["pf_21_26"], 2),
                "ETH_PF": round(eth_pf_val, 2),
                "MaxDD%": round(mb["dd"], 1),
                "Placebo": int(round(plac))
            })
    print(pd.DataFrame(sweep_rows).to_string(index=False))

    # --------------------------------------------------------------------------
    # PART B: 10 BATCH-4 STRATEGIES (#31 - #40)
    # --------------------------------------------------------------------------
    btc_strats = generate_signals(btc_feat)
    eth_strats = generate_signals(eth_feat) if eth_feat is not None else {}
    summary_rows = []

    print("\n" + "=" * 100)
    print("BATCH 4 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")
        mb = safe_eval_trades(t_btc, btc_years)

        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")
            me = safe_eval_trades(t_eth, eth_years)
            eth_pf = me["pf"]
            eth_n = me["n"]
        else:
            eth_pf = 0.0
            eth_n = 0

        placebo = run_placebo(btc_sub, t_btc, strat, n_sims=100)

        if (mb["pf_17_20"] > 1.3) and (mb["pf_21_26"] > 1.3) and (mb["n"] >= 30) and (eth_pf > 1.0) and (placebo >= 90.0):
            verdict = "KEEP"
        elif (mb["pf"] >= 1.1) and (mb["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={mb['n']} ({mb['tr_yr']:.1f}/yr, avg {mb['hold_d']}d) | PF={mb['pf']:.2f} | PF_17-20={mb['pf_17_20']:.2f} | PF_21-26={mb['pf_21_26']:.2f} | ETH_PF={eth_pf:.2f} (n={eth_n}) | MaxDD={mb['dd']:.1f}% | Placebo={placebo:.0f}%")
        print(f"  ByYr  : {mb['by_yr']}")

        summary_rows.append({
            "Idea": name,
            "n": mb["n"],
            "Tr/Yr": round(mb["tr_yr"], 1),
            "HoldD": mb["hold_d"],
            "PF": round(mb["pf"], 2),
            "PF_17_20": round(mb["pf_17_20"], 2),
            "PF_21_26": round(mb["pf_21_26"], 2),
            "ETH_PF": round(eth_pf, 2),
            "MaxDD%": round(mb["dd"], 1),
            "Placebo": int(round(placebo)),
            "Verdict": verdict
        })

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

    print("\n" + "=" * 100)
    print("VERDICTS BLOCK (BATCH 4)")
    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()
