#!/usr/bin/env python3
"""
BTC & ETH Multi-Day Futures Setup Research & Backtest Suite — Batch 2 (2017-2026)
- Evaluates 10 new orthogonal multi-day strategies (#11 to #20) + 1 hardened ablation of #09_SEMI_SKEW
- Hold 2-30 days, stops capped <= 10%, 0.12%/side fees, next-bar open execution
- Strict no-lookahead (all daily/macro features lagged by +1 day before joining to 1h bars)
- 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-08-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()

    # Hourly Close Location Value (CLV) * Volume for intraday accumulation signal
    hl_span = (df["high"] - df["low"]).replace(0, np.nan)
    df["clv_vol"] = (((df["close"] - df["low"]) - (df["high"] - df["close"])) / hl_span).fillna(0.0) * df["volume"]
    df["tp_vol"] = ((df["high"] + df["low"] + df["close"]) / 3.0) * df["volume"]

    # Daily OHLCV + intraday-aggregated metrics
    daily = df.resample("1D").agg({
        "open": "first",
        "high": "max",
        "low": "min",
        "close": "last",
        "volume": "sum",
        "clv_vol": "sum",
        "tp_vol": "sum"
    }).dropna(subset=["open", "high", "low", "close"])

    # Returns & Moving Averages
    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["sma_20d"] = daily["close"].rolling(20).mean()
    daily["sma_50d"] = daily["close"].rolling(50).mean()
    daily["sma_200d"] = daily["close"].rolling(200).mean()
    daily["vol_sma20"] = daily["volume"].rolling(20).mean()

    # Rolling 30-day VWAP & consecutive days above/below 30d VWAP
    vol_30 = daily["volume"].rolling(30).sum().replace(0, np.nan)
    daily["vwap_30d"] = daily["tp_vol"].rolling(30).sum() / vol_30
    above_vwap = (daily["close"] > daily["vwap_30d"]).astype(int)
    below_vwap = (daily["close"] < daily["vwap_30d"]).astype(int)
    daily["prev10_below_vwap"] = below_vwap.shift(1).rolling(10).sum()
    daily["prev10_above_vwap"] = above_vwap.shift(1).rolling(10).sum()

    # Cumulative 10d Volume-Weighted CLV Z-score
    clv_cum10 = daily["clv_vol"].rolling(10).sum()
    daily["clv_z10"] = (clv_cum10 - clv_cum10.rolling(30).mean()) / clv_cum10.rolling(30).std().replace(0, np.nan)

    # Volatility-of-Volatility (14d std of 5d realized vol, ranked over 60d)
    rvol_5d = daily["ret_1d"].rolling(5).std() * np.sqrt(365)
    vov_14d = rvol_5d.rolling(14).std()
    daily["vov_pct60"] = vov_14d.rolling(60).rank(pct=True)

    # Parkinson High-Low Volatility vs Close-to-Close Volatility (14d)
    log_hl_sq = (np.log((daily["high"] / daily["low"]).replace(0, np.nan))) ** 2
    park_vol_14d = np.sqrt(log_hl_sq.rolling(14).mean() / (4.0 * np.log(2.0))) * np.sqrt(365)
    cc_vol_14d = daily["ret_1d"].rolling(14).std() * np.sqrt(365)
    daily["park_cc_ratio"] = park_vol_14d / cc_vol_14d.replace(0, np.nan)

    # 14d Upside/Downside Semivariance Asymmetry (plus 2-day lagged version for exhaustion setup)
    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)
    daily["semi_asym_lag2"] = daily["semi_asym_14d"].shift(2)
    daily["ret_1d_lag1"] = daily["ret_1d"].shift(1)

    # 20d Return-to-Ulcer Index (Downside & Upside Pain Ratios)
    roll_max_20 = daily["close"].rolling(20).max()
    dd_pct_20 = ((daily["close"] - roll_max_20) / roll_max_20) * 100.0
    ulcer_dn_20 = np.sqrt((dd_pct_20 ** 2).rolling(20).mean()).replace(0, np.nan)
    daily["ret_ulcer_dn"] = (daily["ret_20d"] * 100.0) / ulcer_dn_20

    roll_min_20 = daily["close"].rolling(20).min()
    ru_pct_20 = ((daily["close"] - roll_min_20) / roll_min_20) * 100.0
    ulcer_up_20 = np.sqrt((ru_pct_20 ** 2).rolling(20).mean()).replace(0, np.nan)
    daily["ret_ulcer_up"] = (daily["ret_20d"] * 100.0) / ulcer_up_20

    # Cross-Asset ETH/BTC Structural Ratio (30d breakout)
    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")
        pair_ratio = daily["close"] / aligned_other.replace(0, np.nan)
        daily["pair_ratio_ret_30d"] = pair_ratio.pct_change(30)

    # Macro Daily Features (TIP Real Yield ETF, Gold, Silver, USD/JPY)
    if macro_daily is not None and not macro_daily.empty:
        m_aligned = macro_daily.reindex(daily.index, method="ffill")
        if "tip" in m_aligned.columns:
            daily["tip_ret_15d"] = m_aligned["tip"].pct_change(15)
        if "gold" in m_aligned.columns:
            daily["gold_ret_15d"] = m_aligned["gold"].pct_change(15)
            daily["gold_ret_20d"] = m_aligned["gold"].pct_change(20)
        if "silver" in m_aligned.columns and "gold" in m_aligned.columns:
            daily["silver_ret_15d"] = m_aligned["silver"].pct_change(15)
            daily["ag_au_spread_15d"] = daily["silver_ret_15d"] - daily["gold_ret_15d"]
        if "usdjpy" in m_aligned.columns:
            daily["usdjpy_ret_10d"] = m_aligned["usdjpy"].pct_change(10)

    # Shift ALL daily columns by 1 day so day D-1 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", "clv_vol", "tp_vol"], inplace=True)

    # Hourly execution ATR(24) for trailing 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)

    # 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 2 STRATEGY DEFINITIONS (#11 - #20 + HARDENED #09 ABLATION)
# ==============================================================================

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

    # --------------------------------------------------------------------------
    # IDEA 11: TIPS 10Y Real Yield Curve Impulse (11_REAL_YIELD_SLOPE)
    # --------------------------------------------------------------------------
    s11 = pd.Series(0, index=df.index)
    if "tip_ret_15d" in df.columns:
        cond_l = day_trig & (df["tip_ret_15d"] > 0.018) & (df["close_d"] > df["sma_50d"])
        cond_s = day_trig & (df["tip_ret_15d"] < -0.018) & (df["close_d"] < df["sma_50d"])
        s11[cond_l] = 1
        s11[cond_s] = -1
    strategies["11_REAL_YIELD_SLOPE"] = {
        "logic": "TIPS bond rallies (falling 10Y real yields) reduce the opportunity cost of holding non-yielding BTC/ETH.",
        "rule": "Long when TIP 15d ret > +1.8% & close > SMA50 (Short if < -1.8% & close < SMA50); hold 12d, 7.5% stop, 20% TP.",
        "dir": s11, "hold_bars": 12 * 24, "stop_pct": 0.075, "tp_pct": 0.20, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 12: Volatility-of-Volatility Compression Reversal (12_VOL_OF_VOL_CRUSH)
    # --------------------------------------------------------------------------
    s12 = pd.Series(0, index=df.index)
    cond_l = day_trig & (df["vov_pct60"] < 0.10) & (df["ret_5d"] > 0.015) & (df["close_d"] > df["sma_50d"])
    cond_s = day_trig & (df["vov_pct60"] < 0.10) & (df["ret_5d"] < -0.015) & (df["close_d"] < df["sma_50d"])
    s12[cond_l] = 1
    s12[cond_s] = -1
    strategies["12_VOL_OF_VOL_CRUSH"] = {
        "logic": "Bottom-decile 14d Vol-of-Vol signals dealer gamma pinning that resolves in multi-day trend expansion.",
        "rule": "Long when 14d VoV < 10th pctile (60d), 5d ret > +1.5%, close > SMA50 (inverse short); hold 10d, 7% stop, 3.5x ATR trail.",
        "dir": s12, "hold_bars": 10 * 24, "stop_pct": 0.07, "tp_pct": None, "trail_atr": 3.5
    }

    # --------------------------------------------------------------------------
    # IDEA 13: 1h Volume-Weighted Close Location Accumulation (13_PERP_SPOT_LEAD)
    # --------------------------------------------------------------------------
    s13 = pd.Series(0, index=df.index)
    cond_l = day_trig & (df["clv_z10"] > 1.75) & (df["ret_10d"] < 0.04) & (df["close_d"] > df["sma_50d"])
    cond_s = day_trig & (df["clv_z10"] < -1.75) & (df["ret_10d"] > -0.04) & (df["close_d"] < df["sma_50d"])
    s13[cond_l] = 1
    s13[cond_s] = -1
    strategies["13_PERP_SPOT_LEAD"] = {
        "logic": "High 10d hourly Close-Location-Value Z-score (>1.75) during flat price action detects intraday dip absorption.",
        "rule": "Long when 10d cum CLV*Vol Z > +1.75, 10d ret < +4%, close > SMA50 (inverse short); hold 10d, 7% stop, 18% TP.",
        "dir": s13, "hold_bars": 10 * 24, "stop_pct": 0.07, "tp_pct": 0.18, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 14: Parkinson vs Close-to-Close Volatility Ratio (14_HIGH_LOW_ASYM)
    # --------------------------------------------------------------------------
    s14 = pd.Series(0, index=df.index)
    cond_l = day_trig & (df["park_cc_ratio"] < 0.72) & (df["ret_10d"] > 0.05) & (df["close_d"] > df["sma_20d"])
    cond_s = day_trig & (df["park_cc_ratio"] < 0.72) & (df["ret_10d"] < -0.05) & (df["close_d"] < df["sma_20d"])
    s14[cond_l] = 1
    s14[cond_s] = -1
    strategies["14_HIGH_LOW_ASYM"] = {
        "logic": "Low Parkinson-to-Close volatility (<0.72) identifies clean close-to-close institutional trends without intraday chop.",
        "rule": "Long when 14d Parkinson/CC vol < 0.72, 10d ret > +5%, close > SMA20 (inverse short); hold 12d, 7.5% stop, 3.5x ATR trail.",
        "dir": s14, "hold_bars": 12 * 24, "stop_pct": 0.075, "tp_pct": None, "trail_atr": 3.5
    }

    # --------------------------------------------------------------------------
    # IDEA 15: Silver/Gold High-Beta Precious Metals Confirmation (15_SILVER_GOLD_BETA)
    # --------------------------------------------------------------------------
    s15 = pd.Series(0, index=df.index)
    if "gold_ret_20d" in df.columns and "ag_au_spread_15d" in df.columns:
        cond_l = day_trig & (df["gold_ret_20d"] > 0.035) & (df["ag_au_spread_15d"] > 0.025) & (df["close_d"] > df["sma_50d"])
        cond_s = day_trig & (df["gold_ret_20d"] < -0.035) & (df["ag_au_spread_15d"] < -0.025) & (df["close_d"] < df["sma_50d"])
        s15[cond_l] = 1
        s15[cond_s] = -1
    strategies["15_SILVER_GOLD_BETA"] = {
        "logic": "Silver outperforming Gold during a Gold rally confirms speculative reflation rather than defensive risk-off flows.",
        "rule": "Long when Gold 20d > +3.5%, Silver-Gold 15d spread > +2.5%, close > SMA50 (inverse short); hold 14d, 8% stop, 22% TP.",
        "dir": s15, "hold_bars": 14 * 24, "stop_pct": 0.08, "tp_pct": 0.22, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 16: Cross-Pair 30d Ratio Structural Breakout (16_ETH_BTC_REGIME_FLIP)
    # --------------------------------------------------------------------------
    s16 = pd.Series(0, index=df.index)
    if "pair_ratio_ret_30d" in df.columns:
        # When primary/peer ratio breaks out >+12% over 30d with trend confirmation -> ride regime flow
        cond_l = day_trig & (df["pair_ratio_ret_30d"] > 0.12) & (df["close_d"] > df["sma_50d"])
        cond_s = day_trig & (df["pair_ratio_ret_30d"] < -0.12) & (df["close_d"] < df["sma_20d"])
        s16[cond_l] = 1
        s16[cond_s] = -1
    strategies["16_ETH_BTC_REGIME_FLIP"] = {
        "logic": "30-day breakouts (>12%) in the BTC/ETH relative ratio capture sustained multi-week capital rotation regimes.",
        "rule": "Long when Primary/Peer 30d ret > +12% & close > SMA50; Short when < -12% & close < SMA20; hold 12d, 7% stop, 18% TP.",
        "dir": s16, "hold_bars": 12 * 24, "stop_pct": 0.07, "tp_pct": 0.18, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 17: 14d Downside Tail Exhaustion + 2-Day Reversal (17_DOWNSIDE_TAIL_EXHAUST)
    # --------------------------------------------------------------------------
    s17 = pd.Series(0, index=df.index)
    cond_l = (
        day_trig
        & (df["semi_asym_lag2"] < -0.45)
        & (df["ret_1d_lag1"] > 0.0)
        & (df["ret_1d"] > 0.0)
        & (df["close_d"] > df["sma_200d"])
    )
    cond_s = (
        day_trig
        & (df["semi_asym_lag2"] > 0.45)
        & (df["ret_1d_lag1"] < 0.0)
        & (df["ret_1d"] < 0.0)
        & (df["close_d"] < df["sma_200d"])
    )
    s17[cond_l] = 1
    s17[cond_s] = -1
    strategies["17_DOWNSIDE_TAIL_EXHAUST"] = {
        "logic": "Extreme downside semivariance skew (<-0.45) above SMA200 followed by 2 green days marks seller exhaustion.",
        "rule": "Long if S14(t-2) < -0.45, last 2 daily closes green, close > SMA200 (inverse short); hold 8d, 7.5% stop, 18% TP.",
        "dir": s17, "hold_bars": 8 * 24, "stop_pct": 0.075, "tp_pct": 0.18, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 18: USD/JPY Carry-Trade Unwind Trigger (18_DOLLAR_YEN_CARRY)
    # --------------------------------------------------------------------------
    s18 = pd.Series(0, index=df.index)
    if "usdjpy_ret_10d" in df.columns:
        cond_s = day_trig & (df["usdjpy_ret_10d"] < -0.028) & (df["close_d"] < df["sma_20d"])
        cond_l = day_trig & (df["usdjpy_ret_10d"] > 0.028) & (df["close_d"] > df["sma_50d"])
        s18[cond_l] = 1
        s18[cond_s] = -1
    strategies["18_DOLLAR_YEN_CARRY"] = {
        "logic": "Rapid 10d drops in USD/JPY (<-2.8%) signal yen carry-trade deleveraging and cross-asset margin liquidation.",
        "rule": "Short when USDJPY 10d ret < -2.8% & close < SMA20; Long when > +2.8% & close > SMA50; hold 10d, 7% stop, 18% TP.",
        "dir": s18, "hold_bars": 10 * 24, "stop_pct": 0.07, "tp_pct": 0.18, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # IDEA 19: Return-to-Ulcer Pain Ratio Drift (19_RANGE_EFFICIENCY_DRIFT)
    # --------------------------------------------------------------------------
    s19 = pd.Series(0, index=df.index)
    cond_l = day_trig & (df["ret_ulcer_dn"] > 3.5) & (df["close_d"] > df["sma_20d"])
    cond_s = day_trig & (df["ret_ulcer_up"] < -3.5) & (df["close_d"] < df["sma_20d"])
    s19[cond_l] = 1
    s19[cond_s] = -1
    strategies["19_RANGE_EFFICIENCY_DRIFT"] = {
        "logic": "High 20d return relative to Ulcer drawdown pain (>3.5) isolates smooth trends that squeeze counter-trend traders.",
        "rule": "Long when 20d Ret/Ulcer > 3.5 & close > SMA20 (inverse using upside Ulcer for short); hold 10d, 7.5% stop, 3.5x ATR trail.",
        "dir": s19, "hold_bars": 10 * 24, "stop_pct": 0.075, "tp_pct": None, "trail_atr": 3.5
    }

    # --------------------------------------------------------------------------
    # IDEA 20: Rolling 30-Day VWAP Volume Reclaim (20_MONTHLY_ANCHOR_RECLAIM)
    # --------------------------------------------------------------------------
    s20 = pd.Series(0, index=df.index)
    cond_l = (
        day_trig
        & (df["close_d"] > df["vwap_30d"])
        & (df["prev10_below_vwap"] == 10)
        & (df["volume_d"] > 1.3 * df["vol_sma20"])
    )
    cond_s = (
        day_trig
        & (df["close_d"] < df["vwap_30d"])
        & (df["prev10_above_vwap"] == 10)
        & (df["volume_d"] > 1.3 * df["vol_sma20"])
    )
    s20[cond_l] = 1
    s20[cond_s] = -1
    strategies["20_MONTHLY_ANCHOR_RECLAIM"] = {
        "logic": "Reclaiming rolling 30d VWAP on >1.3x volume after 10+ days below forces underwater institutional shorts to cover.",
        "rule": "Long when close > VWAP30 after 10 days below & vol > 1.3x VolSMA20 (inverse short); hold 12d, 7.5% stop, 20% TP.",
        "dir": s20, "hold_bars": 12 * 24, "stop_pct": 0.075, "tp_pct": 0.20, "trail_atr": None
    }

    # --------------------------------------------------------------------------
    # BONUS ABLATION: Hardened #09 Semivariance Skew (09B_SEMI_SKEW_HARD)
    # --------------------------------------------------------------------------
    s09b = pd.Series(0, index=df.index)
    cond_l = day_trig & (df["semi_asym_14d"] > 0.45) & (df["ret_10d"] > 0.05) & (df["close_d"] > df["sma_50d"])
    cond_s = day_trig & (df["semi_asym_14d"] < -0.45) & (df["ret_10d"] < -0.05) & (df["close_d"] < df["sma_50d"])
    s09b[cond_l] = 1
    s09b[cond_s] = -1
    strategies["09B_SEMI_SKEW_HARD"] = {
        "logic": "Hardened Batch-1 winner: tighter semivariance threshold (|S14|>0.45) + SMA50 regime filter to cut 2021-22 chop.",
        "rule": "Long when S14 > +0.45, 10d ret > +5%, close > SMA50 (inverse short); hold 10d, 7.5% stop, 3.5x ATR trail.",
        "dir": s09b, "hold_bars": 10 * 24, "stop_pct": 0.075, "tp_pct": None, "trail_atr": 3.5
    }

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

            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

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

        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
    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 = {
        "tip": "TIP",
        "gold": "GC=F",
        "silver": "SI=F",
        "usdjpy": "JPY=X"
    }
    macro_daily = load_yfinance_daily(macro_tickers, start="2016-08-01")
    # Note: Yahoo's JPY=X quotes USD/JPY (e.g., ~150). Verify orientation; if < 1.0, invert.
    if "usdjpy" in macro_daily.columns and macro_daily["usdjpy"].dropna().median() < 1.0:
        macro_daily["usdjpy"] = 1.0 / macro_daily["usdjpy"]

    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("BATCH 2 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)

            eq = (1.0 + t_btc["net_ret"]).cumprod()
            dd = (eq / eq.cummax() - 1.0).min() * 100.0

            yr_pfs = {}
            for yr in sorted(t_btc["year"].unique()):
                yr_pfs[int(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 = {}

        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 = 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) | 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 (BATCH 2)")
    print("=" * 95)
    print(sum_df.to_string(index=False))

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