#!/usr/bin/env python3
"""
BTC & ETH Multi-Day Futures Setup Research & Backtest Suite (2017-2026)
- Evaluates 10 orthogonal multi-day strategies (hold 2-30 days, max stop 10%, 0.12%/side fees)
- Next-bar open execution, strict no-lookahead (prior-day macro/daily signals)
- Includes 100-iteration matched-count/hold placebo permutation test per setup
"""

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]
        df["time"] = pd.to_datetime(df[time_col], unit="ms", utc=True) if pd.api.types.is_numeric_dtype(df[time_col]) else 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-09-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 the full calendar day D.
    A 1h bar on day D can ONLY see daily values up to day D-1.
    Therefore, all daily features are shifted by +1 day before forward-filling onto 1h bars.
    """
    df = df_1h.copy()

    # Daily OHLCV aggregation for primary asset
    daily = df.resample("1D").agg({
        "open": "first",
        "high": "max",
        "low": "min",
        "close": "last",
        "volume": "sum"
    }).dropna()

    # Daily True Range & 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()
    daily["atr_pct"] = daily["atr14"] / daily["close"]

    # Daily rolling metrics
    daily["ret_1d"] = daily["close"].pct_change(1)
    daily["ret_5d"] = daily["close"].pct_change(5)
    daily["ret_10d"] = daily["close"].pct_change(10)
    daily["ret_14d"] = daily["close"].pct_change(14)
    daily["ret_20d"] = daily["close"].pct_change(20)
    daily["ret_30d"] = daily["close"].pct_change(30)

    daily["high_20d"] = daily["high"].rolling(20).max()
    daily["low_20d"] = daily["low"].rolling(20).min()
    daily["high_50d"] = daily["high"].rolling(50).max()
    daily["low_50d"] = daily["low"].rolling(50).min()
    daily["sma_20d"] = daily["close"].rolling(20).mean()
    daily["sma_50d"] = daily["close"].rolling(50).mean()
    daily["sma_100d"] = daily["close"].rolling(100).mean()

    # Realized Volatility Term Structure (5d vs 30d annualized)
    daily["rvol_5d"] = daily["ret_1d"].rolling(5).std() * np.sqrt(365)
    daily["rvol_30d"] = daily["ret_1d"].rolling(30).std() * np.sqrt(365)
    daily["vol_ratio_5_30"] = daily["rvol_5d"] / daily["rvol_30d"].replace(0, np.nan)

    # Upside vs Downside Semivariance Asymmetry (14d)
    pos_ret = daily["ret_1d"].clip(lower=0)
    neg_ret = daily["ret_1d"].clip(upper=0)
    up_vol = np.sqrt((pos_ret ** 2).rolling(14).mean())
    dn_vol = np.sqrt((neg_ret ** 2).rolling(14).mean())
    daily["semi_asym_14d"] = (up_vol - dn_vol) / (up_vol + dn_vol).replace(0, np.nan)

    # Volume-Price Divergence & OBV Slope (14d)
    obv = (np.sign(daily["ret_1d"]).fillna(0) * daily["volume"]).cumsum()
    daily["obv_z14"] = (obv - obv.rolling(14).mean()) / obv.rolling(14).std().replace(0, np.nan)
    daily["vol_z20"] = (daily["volume"] - daily["volume"].rolling(20).mean()) / daily["volume"].rolling(20).std().replace(0, np.nan)

    # Weekly Structure (Completed prior weeks only)
    weekly = df.resample("W-SUN").agg({
        "open": "first",
        "high": "max",
        "low": "min",
        "close": "last",
        "volume": "sum"
    }).dropna()
    weekly["wk_range"] = (weekly["high"] - weekly["low"]).replace(0, np.nan)
    weekly["wk_ibs"] = (weekly["close"] - weekly["low"]) / weekly["wk_range"]
    weekly["wk_ret"] = weekly["close"].pct_change(1)
    weekly["wk_high_4w"] = weekly["high"].rolling(4).max()
    weekly["wk_low_4w"] = weekly["low"].rolling(4).min()

    # Shift weekly by 1 period so week ending Sunday is available starting Monday 00:00 UTC
    weekly_shifted = weekly.shift(1)
    weekly_daily = weekly_shifted.reindex(daily.index, method="ffill")
    for col in ["wk_ibs", "wk_ret", "wk_high_4w", "wk_low_4w"]:
        daily[col] = weekly_daily[col]

    # Cross-Asset Crypto Lead/Lag (ETH vs BTC ratio & relative strength)
    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["other_ret_7d"] = aligned_other.pct_change(7)
        daily["other_ret_14d"] = aligned_other.pct_change(14)
        # Relative spread: primary 7d return minus other 7d return
        daily["rel_spread_7d"] = daily["ret_7d"] - daily["other_ret_7d"] if "ret_7d" in daily else daily["close"].pct_change(7) - daily["other_ret_7d"]
        daily["rel_spread_14d"] = daily["ret_14d"] - daily["other_ret_14d"]

    # Macro Daily Features (Gold, US10Y, Oil, Copper, Silver)
    if macro_daily is not None and not macro_daily.empty:
        m_aligned = macro_daily.reindex(daily.index, method="ffill")
        for col in m_aligned.columns:
            daily[f"{col}_ret_10d"] = m_aligned[col].pct_change(10)
            daily[f"{col}_ret_20d"] = m_aligned[col].pct_change(20)
            daily[f"{col}_z20"] = (m_aligned[col] - m_aligned[col].rolling(20).mean()) / m_aligned[col].rolling(20).std().replace(0, np.nan)
            if col == "us10y":
                # Yield basis-point / level change over 15 trading days
                daily["us10y_chg_15d"] = m_aligned[col].diff(15)

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

    # Hourly execution ATR(24) for dynamic stops (strictly lagged by 1 bar)
    h_prev = merged["close"].shift(1)
    h_tr = pd.concat([
        merged["high"] - merged["low"],
        (merged["high"] - h_prev).abs(),
        (merged["low"] - h_prev).abs()
    ], axis=1).max(axis=1)
    merged["atr_24h"] = h_tr.rolling(24).mean().shift(1)

    # New-day trigger flag (first 1h bar of each UTC day, where daily signal updates)
    merged["is_day_open"] = (merged.index.hour == 0)

    return merged


# ==============================================================================
# 3. 10 NEW MULTI-DAY STRATEGY DEFINITIONS
# ==============================================================================

def generate_signals(df):
    """
    Returns a dict of 10 strategies. Each entry contains:
      - 'name': Short label
      - 'logic': One-line hypothesis
      - 'rule': Exact entry/exit rule
      - 'dir': Series (+1 long, -1 short, 0 flat) evaluated at bar close -> enters next bar open
      - 'hold_bars': Max holding duration in 1h bars (48 to 720 bars = 2 to 30 days)
      - 'stop_pct': Hard stop loss percentage (capped <= 0.10)
      - 'tp_pct': Optional take-profit percentage (None if time/trail exit)
      - 'trail_atr': Optional ATR trailing stop multiplier
    """
    strategies = {}
    day_trig = df["is_day_open"]

    # --------------------------------------------------------------------------
    # IDEA 1: Gold Impulse Leading Crypto Liquidity Breakout (GOLD_LEAD)
    # --------------------------------------------------------------------------
    s1 = pd.Series(0, index=df.index)
    if "gold_ret_20d" in df.columns:
        cond_l = day_trig & (df["gold_ret_20d"] > 0.045) & (df["ret_20d"] < 0.05) & (df["close_d"] > df["sma_50d"])
        cond_s = day_trig & (df["gold_ret_20d"] < -0.045) & (df["ret_20d"] > -0.05) & (df["close_d"] < df["sma_50d"])
        s1[cond_l] = 1
        s1[cond_s] = -1
    strategies["01_GOLD_LEAD"] = {
        "logic": "Sustained Gold (GC=F) 20d breakouts signal fiat debasement/liquidity expansion before crypto prices it in.",
        "rule": "Long when Gold 20d ret > +4.5%, crypto 20d ret < +5%, close > SMA50 (inverse for short); hold 14d, 8% stop.",
        "dir": s1, "hold_bars": 14 * 24, "stop_pct": 0.08, "tp_pct": 0.22, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 2: US 10Y Treasury Yield Shock Reversal / Trend (US10Y_SHOCK)
    # --------------------------------------------------------------------------
    s2 = pd.Series(0, index=df.index)
    if "us10y_chg_15d" in df.columns:
        # Sharp drop in 10Y yields (>35 bps) eases financial conditions -> long crypto; sharp spike (>40 bps) -> short
        cond_l = day_trig & (df["us10y_chg_15d"] < -0.35) & (df["close_d"] > df["sma_100d"])
        cond_s = day_trig & (df["us10y_chg_15d"] > 0.40) & (df["close_d"] < df["sma_50d"])
        s2[cond_l] = 1
        s2[cond_s] = -1
    strategies["02_US10Y_SHOCK"] = {
        "logic": "Rapid 15-day drops in US10Y yields trigger multi-week risk-on duration flows into crypto; spikes compress multiples.",
        "rule": "Long if US10Y 15d change < -0.35% & close > SMA100; Short if > +0.40% & close < SMA50; hold 12d, 7.5% stop.",
        "dir": s2, "hold_bars": 12 * 24, "stop_pct": 0.075, "tp_pct": 0.20, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 3: WTI Crude Oil Stagflation Squeeze vs Deflationary Relief (OIL_MACRO)
    # --------------------------------------------------------------------------
    s3 = pd.Series(0, index=df.index)
    if "oil_ret_20d" in df.columns:
        # Extreme oil surge (>+18% in 20d) acts as liquidity tax -> short weak crypto; sharp oil drop (<-15%) -> long
        cond_s = day_trig & (df["oil_ret_20d"] > 0.18) & (df["ret_10d"] < 0.0)
        cond_l = day_trig & (df["oil_ret_20d"] < -0.15) & (df["close_d"] > df["sma_50d"])
        s3[cond_l] = 1
        s3[cond_s] = -1
    strategies["03_OIL_MACRO"] = {
        "logic": "Crude oil supply shocks (>+18% in 20d) drain consumer/speculative liquidity, whereas oil drops fuel risk rallies.",
        "rule": "Short if WTI 20d ret > +18% & crypto 10d ret < 0; Long if WTI 20d ret < -15% & close > SMA50; hold 10d, 7% stop.",
        "dir": s3, "hold_bars": 10 * 24, "stop_pct": 0.07, "tp_pct": 0.18, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 4: Copper/Gold Global Growth Ratio Trend Filter (COPPER_GOLD)
    # --------------------------------------------------------------------------
    s4 = pd.Series(0, index=df.index)
    if "copper_ret_20d" in df.columns and "gold_ret_20d" in df.columns:
        cg_spread = df["copper_ret_20d"] - df["gold_ret_20d"]
        cond_l = day_trig & (cg_spread > 0.06) & (df["close_d"] > df["high_20d"].shift(24))
        cond_s = day_trig & (cg_spread < -0.06) & (df["close_d"] < df["low_20d"].shift(24))
        s4[cond_l] = 1
        s4[cond_s] = -1
    strategies["04_COPPER_GOLD"] = {
        "logic": "Copper outperforming Gold by >6% over 20d confirms global reflationary expansion, validating 20d crypto breakouts.",
        "rule": "Long on 20d high close when Copper-Gold 20d spread > +6%; Short on 20d low close when spread < -6%; hold 15d, 8% stop.",
        "dir": s4, "hold_bars": 15 * 24, "stop_pct": 0.08, "tp_pct": None, "trail_atr": 4.5
    }

    # --------------------------------------------------------------------------
    # IDEA 5: BTC/ETH Cross-Asset Laggard Catch-Up (CROSS_LAG)
    # --------------------------------------------------------------------------
    s5 = pd.Series(0, index=df.index)
    if "rel_spread_14d" in df.columns:
        # When the counterpart asset rallied >10% more over 14d while primary is in uptrend -> catch-up long
        cond_l = day_trig & (df["rel_spread_14d"] < -0.10) & (df["other_ret_14d"] > 0.08) & (df["close_d"] > df["sma_50d"])
        cond_s = day_trig & (df["rel_spread_14d"] > 0.10) & (df["other_ret_14d"] < -0.08) & (df["close_d"] < df["sma_50d"])
        s5[cond_l] = 1
        s5[cond_s] = -1
    strategies["05_CROSS_LAG"] = {
        "logic": "When BTC or ETH leads a >8% 14d impulse and outperforms its peer by >10%, the laggard catches up within 7 days.",
        "rule": "Long laggard if peer 14d ret > +8%, spread < -10%, close > SMA50 (inverse for short); hold 7d, 6.5% stop.",
        "dir": s5, "hold_bars": 7 * 24, "stop_pct": 0.065, "tp_pct": 0.15, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 6: Volatility Term-Structure Contango Breakout (VOL_TERM)
    # --------------------------------------------------------------------------
    s6 = pd.Series(0, index=df.index)
    # 5d realized vol deeply compressed (<0.55x 30d rvol) followed by fresh 20d directional breakout
    cond_l = day_trig & (df["vol_ratio_5_30"] < 0.55) & (df["close_d"] >= df["high_20d"] * 0.995) & (df["close_d"] > df["sma_50d"])
    cond_s = day_trig & (df["vol_ratio_5_30"] < 0.55) & (df["close_d"] <= df["low_20d"] * 1.005) & (df["close_d"] < df["sma_50d"])
    s6[cond_l] = 1
    s6[cond_s] = -1
    strategies["06_VOL_TERM"] = {
        "logic": "Short-term realized vol (5d) dropping below 0.55x 30d vol creates steep term-structure contango prone to gamma expansion.",
        "rule": "Enter at 20d high/low boundary when 5d/30d realized vol ratio < 0.55 aligned with SMA50; hold 14d, 7.5% stop.",
        "dir": s6, "hold_bars": 14 * 24, "stop_pct": 0.075, "tp_pct": None, "trail_atr": 4.0
    }

    # --------------------------------------------------------------------------
    # IDEA 7: Weekly Internal Bar Strength (IBS) Exhaustion Reversal (WK_IBS_REV)
    # --------------------------------------------------------------------------
    s7 = pd.Series(0, index=df.index)
    is_monday = day_trig & (df.index.dayofweek == 0)
    # Prior full week closed in bottom 12% of its range after >8% drop in an overarching bull market -> snapback long
    cond_l = is_monday & (df["wk_ibs"] < 0.12) & (df["wk_ret"] < -0.08) & (df["close_d"] > df["sma_100d"])
    cond_s = is_monday & (df["wk_ibs"] > 0.88) & (df["wk_ret"] > 0.12) & (df["close_d"] < df["sma_100d"])
    s7[cond_l] = 1
    s7[cond_s] = -1
    strategies["07_WK_IBS_REV"] = {
        "logic": "Weekly closes at extreme range tails (IBS < 0.12 or > 0.88) counter to the 100d regime reflect forced liquidations.",
        "rule": "On Monday open, Long if prior week IBS < 0.12 & wk ret < -8% above SMA100 (inverse for short); hold 6d, 7% stop.",
        "dir": s7, "hold_bars": 6 * 24, "stop_pct": 0.07, "tp_pct": 0.14, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 8: 4-Week Failed Breakdown / Spring (WK_SPRING)
    # --------------------------------------------------------------------------
    s8 = pd.Series(0, index=df.index)
    # Price dipped below 4-week low intraday yesterday but closed back above it, with SMA50 rising
    cond_l = day_trig & (df["low_d"] < df["wk_low_4w"]) & (df["close_d"] > df["wk_low_4w"]) & (df["sma_50d"] > df["sma_50d"].shift(24 * 5))
    cond_s = day_trig & (df["high_d"] > df["wk_high_4w"]) & (df["close_d"] < df["wk_high_4w"]) & (df["sma_50d"] < df["sma_50d"].shift(24 * 5))
    s8[cond_l] = 1
    s8[cond_s] = -1
    strategies["08_WK_SPRING"] = {
        "logic": "Wyckoff spring: sweeping the 4-week low and reclaiming it by daily close traps breakout shorts in an uptrend.",
        "rule": "Long when daily low < prior 4w low & close > 4w low with rising SMA50 (inverse for short); hold 10d, 6% stop.",
        "dir": s8, "hold_bars": 10 * 24, "stop_pct": 0.06, "tp_pct": 0.16, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 9: Upside/Downside Semivariance Skew Continuation (SEMI_SKEW)
    # --------------------------------------------------------------------------
    s9 = pd.Series(0, index=df.index)
    # Strong positive upside semivariance dominance (> +0.35) + positive 10d return -> steady institutional accumulation
    cond_l = day_trig & (df["semi_asym_14d"] > 0.35) & (df["ret_10d"] > 0.04) & (df["close_d"] > df["sma_20d"])
    cond_s = day_trig & (df["semi_asym_14d"] < -0.35) & (df["ret_10d"] < -0.04) & (df["close_d"] < df["sma_20d"])
    s9[cond_l] = 1
    s9[cond_s] = -1
    strategies["09_SEMI_SKEW"] = {
        "logic": "Trends driven by upside semivariance rather than symmetric noise persist longer with lower tail-risk.",
        "rule": "Long when 14d semivariance asymmetry > +0.35, 10d ret > +4%, close > SMA20 (inverse short); hold 10d, 7.5% stop.",
        "dir": s9, "hold_bars": 10 * 24, "stop_pct": 0.075, "tp_pct": None, "trail_atr": 3.5
    }

    # --------------------------------------------------------------------------
    # IDEA 10: OBV Accumulation Divergence Before Price Breakout (OBV_DIV)
    # --------------------------------------------------------------------------
    s10 = pd.Series(0, index=df.index)
    # OBV z-score > +1.6 while price 14d return is flat/slightly negative (-4% to +2%) -> stealth accumulation
    cond_l = day_trig & (df["obv_z14"] > 1.6) & (df["ret_14d"].between(-0.04, 0.02)) & (df["close_d"] > df["sma_50d"])
    cond_s = day_trig & (df["obv_z14"] < -1.6) & (df["ret_14d"].between(-0.02, 0.04)) & (df["close_d"] < df["sma_50d"])
    s10[cond_l] = 1
    s10[cond_s] = -1
    strategies["10_OBV_DIV"] = {
        "logic": "Strong 14d On-Balance Volume Z-score (>1.6) during flat price consolidation reveals stealth spot accumulation.",
        "rule": "Long when OBV Z14 > +1.6, 14d ret in [-4%, +2%], close > SMA50 (inverse short); hold 12d, 7% stop.",
        "dir": s10, "hold_bars": 12 * 24, "stop_pct": 0.07, "tp_pct": 0.18, "trail_atr": None
    }

    return strategies


# ==============================================================================
# 4. BACKTEST ENGINE & METRICS
# ==============================================================================

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

def backtest_strategy(df, strat, start_date="2017-01-01"):
    """
    Executes single-position sequential backtest on 1h bars:
    - Signal evaluated at bar i close -> enters at bar i+1 open.
    - Checks intra-bar stop loss, optional take profit, optional ATR trailing stop, and max hold bars.
    - Deducts 0.12% entry + 0.12% exit fees.
    """
    sub = df[df.index >= start_date]
    opens = sub["open"].values
    highs = sub["high"].values
    lows = sub["low"].values
    closes = sub["close"].values
    atrs = sub["atr_24h"].values
    times = sub.index
    sigs = strat["dir"].reindex(sub.index).fillna(0).values

    hold_bars = strat["hold_bars"]
    stop_pct = min(strat["stop_pct"], 0.10)  # Hard cap at 10%
    tp_pct = strat["tp_pct"]
    trail_atr = strat["trail_atr"]

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

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

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

        direction = int(sig)
        hard_stop = entry_price * (1.0 - direction * stop_pct)
        tp_price = entry_price * (1.0 + direction * tp_pct) if tp_pct is not None else None
        best_price = entry_price
        exit_idx = min(entry_idx + hold_bars, n_bars - 1)
        exit_price = closes[exit_idx]
        exit_reason = "TIME"

        for j in range(entry_idx, exit_idx + 1):
            # Update trailing stop after entry bar
            if trail_atr is not None and j > entry_idx and not np.isnan(atrs[j]):
                if direction == 1:
                    best_price = max(best_price, highs[j - 1])
                    t_stop = best_price - trail_atr * atrs[j]
                    hard_stop = max(hard_stop, t_stop)
                else:
                    best_price = min(best_price, lows[j - 1])
                    t_stop = best_price + trail_atr * atrs[j]
                    hard_stop = min(hard_stop, t_stop)

            # Check Stop Loss first (conservative)
            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 = "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 = "STOP"
                break

            # Check 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,
            "net_ret": net_ret,
            "reason": exit_reason
        })

        # Advance index past exit bar (non-overlapping per engine)
        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):
    """
    Runs 100 random-entry simulations matching exact trade count, direction mix, and hold durations.
    Returns % of random runs whose Profit Factor is beaten by the strategy.
    """
    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
    n_trades = len(trades_df)
    stop_pct = min(strat["stop_pct"], 0.10)
    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]
            ep = opens[s_idx]
            hs = ep * (1.0 - d * stop_pct)
            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 = {
        "gold": "GC=F",
        "us10y": "^TNX",
        "oil": "CL=F",
        "copper": "HG=F"
    }
    macro_daily = load_yfinance_daily(macro_tickers, start="2016-08-01")

    print("\nBuilding no-lookahead 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" + "=" * 95)
    print("DETAILED STRATEGY RESULTS (BTC 2017-2026 | 0.12% FEE/SIDE | NEXT-BAR OPEN)")
    print("=" * 95)

    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["net_ret"].values)
            t_h1 = t_btc[t_btc["year"] <= 2020]
            t_h2 = t_btc[t_btc["year"] >= 2021]
            pf_17_20 = compute_pf(t_h1["net_ret"].values)
            pf_21_26 = compute_pf(t_h2["net_ret"].values)

            # Equity curve max drawdown (compounded at 1x trade return)
            eq = (1.0 + t_btc["net_ret"]).cumprod()
            dd = (eq / eq.cummax() - 1.0).min() * 100.0

            # PF by year
            yr_pfs = {}
            for yr in sorted(t_btc["year"].unique()):
                yr_pfs[yr] = round(compute_pf(t_btc[t_btc["year"] == yr]["net_ret"].values), 2)
        else:
            pf_all = pf_17_20 = pf_21_26 = dd = 0.0
            yr_pfs = {}

        # ETH out-of-sample / cross-asset test
        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["net_ret"].values)
        else:
            eth_pf = 0.0

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

        # Verdict rules
        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) | 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),
            "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" + "=" * 95)
    print("SUMMARY TABLE")
    print("=" * 95)
    print(sum_df.to_string(index=False))

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