# =============================================================================
# Batch14 - the 15 NEW standalone BTC/ETH ideas (2026-11-22 list), tested exactly
# as published, on the HOSTED oslib ONLY. Same pipeline as Batch13.
#
# Colab:
#   %run Batch14.py
# Fetches oslib.py from https://osom-boba.pages.dev/colab/oslib.py if missing
# (Runtime > Restart first if you re-run after oslib.py changed).
#
# WHAT COMES FROM OSLIB (nothing fetched or engineered outside it)
#   data     oslib.load(asset, tf)  -> single perp OHLCV series (btc/eth; 1h base
#            resampled to 4h/1d with oslib.resample_ohlcv, complete bars only;
#            the volume column IS present, so the two volume ideas run here -
#            Batch13's spot/taker gap does not affect any Batch14 idea)
#   funding  oslib.funding(asset)   -> 8h stamps (time, funding) for ideas 3/10
#   engine   oslib.walk_1h          -> per-trade walk: stop-first, then target,
#            then z-exit at bar close, then time stop at bar close
#   fees     0.12%/side (oslib FEE 0.07% + SLIP 0.05%) -> 0.24% round trip inside
#            every trade oslib builds
#   risk     1% per trade: oslib.RISK=0.01 compounding inside oslib.tstats
#   stats    oslib.tstats / _window / _tframe / daily_from_trades
#   basket   oslib.engines(df_1h)   -> all 10 live engines (K8...D34) used for the
#            daily-R correlations (oslib K8 curve + equal-1% basket daily sum)
#
# CONVENTIONS (identical to Batch13)
#   * signals evaluated on completed bars; entry at NEXT bar open (walk_1h fills
#     at o[ei]; weekend / quarter-end ideas pass ei explicitly)
#   * ATR(n) = simple mean of true range over n bars = oslib.sma(oslib.true_range)
#   * time exit = first bar CLOSE at/after entry_open + stated holding period
#   * single position at a time; a signal whose entry bar is not after the
#     previous exit bar is skipped (same spirit as oslib.simulate's resume rule)
#   * placebo: 100 shuffled runs. Each run rebuilds every ACTUAL trade with a
#     random entry bar (uniform over eligible bars), inheriting that trade's
#     side, stop distance and target distance, and re-applies the same exit
#     logic (z-condition / time stop). Percentile = % of placebo runs with PF
#     strictly below the actual PF (same headline window on both).
#   * flip: the mirrored rule traded in the opposite direction (thresholds and
#     exits mirrored; two-sided rules swap their direction mapping).
#
# THE 15 IDEAS (published numbers, ranked by placebo-survival odds at 0.24% RT)
#  #01 Turn-of-month long.  Entry: long at 00:00 open of every UTC day that is
#      among the LAST 3 calendar days of a month or the FIRST 3 of the next
#      (consecutive days = one position).  Stop: entry - 2.0xATR(14,d).
#      Exit: 24:00 close of the last TOM day.  Why: month-end ETF/CTA rebalance
#      flow into BTC; calendar, no chart pattern, decorrelated from engines.
#  #02 Volume-climax exhaustion long.  Entry: daily ret <= -6%, volume >= 3.0x
#      SMA20(daily volume), close in top 40% of day range.  Stop: low - 0.5xATR14.
#      Exit: 5d.  Why: 3x-volume washout that closes off the lows = forced
#      seller exhaustion.  Flip: +6% climax closing in bottom 40% -> short.
#  #03 7-day funding-sum squeeze long (2019+).  Entry: sum of last 21 stamps
#      (7d) <= -0.15% -> long next daily open.  Stop: entry - 2.0xATR14.
#      Exit: 7d sum back >= 0, or 14d.  Why: crowded shorts paying ~8%/yr carry
#      = squeeze fuel.  Flip: sum >= +0.15% short, exit sum <= 0 or 14d.
#  #04 Wide-range follow-through long.  Entry: daily range >= 2.5xATR14, ret
#      >= +3%, close >= 75% up the range -> long next open.  Stop: low - 0.25x
#      ATR14.  Exit: 3d.  Why: wide-range trend days continue next day.  Flip:
#      wide-range down day closing <= 25% -> short.
#  #05 Weekend drift short.  Entry: short every Saturday 00:00 UTC open (signal
#      Fri 23:00 close).  Stop: entry + 1.5%.  Exit: cover Monday 00:00 UTC
#      (Sun 23:00 bar close).  Why: weekend liquidity drain, no US institution
#      flow; structural, unconditional.  Flip: long the same window.
#  #06 High-vol regime short.  Entry: HV20 (std of 20 daily log rets, ann.)
#      in the top 20% of its trailing 364d AND daily ret < 0 -> short next
#      open.  Stop: entry + 1.5xATR14.  Exit: HV20 pct <= 60%, or 10d.  Why:
#      deleveraging cascades cluster; bounces fail until vol normalizes.
#      Flip: top-20% HV with a green day -> long.
#  #07 Month-start momentum (both sides).  Entry: if days 1-3 of the month
#      (close vs last close of prior month) >= +3% -> long from day-4 open;
#      <= -3% -> short.  Stop: entry -/+ 2.0xATR14.  Exit: day-7 close.
#      Why: monthly momentum spillover; calendar-triggered continuation.
#      Flip: fade the 3-day move.
#  #08 ETH/BTC ratio 20d momentum -> trade ETH (cross-asset; executed on ETH).
#      Entry: ETH/BTC 20d return >= +5% -> long ETH next daily open; <= -5%
#      -> short ETH.  Stop: entry -/+ 2.0xATR14(ETH).  Exit: 10d.  Why:
#      rotation runs in multi-month waves (alt seasons).  Flip: fade the move.
#  #09 Streak exhaustion (both).  Entry: green bar after 5 consecutive red
#      closes -> long next open; red bar after 5 consecutive green closes ->
#      short.  Stop: signal low - 0.5xATR14 / high + 0.5xATR14.  Exit: 4d.
#      Why: one-sided streaks end in exhaustion spikes.  Flip: continuation.
#  #10 Euphoric funding-sum stall short (2019+).  Entry: 7d funding sum >=
#      +0.30% AND latest 24h ret <= 0 -> short next daily open.  Stop: entry
#      + 1.5xATR14.  Exit: 7d sum <= +0.10%, or 7d.  Why: longs paying ~15%/yr
#      carry while price stalls = positioning unwinds.  Flip: sum <= -0.30%
#      with a green day -> long, exit sum >= -0.10% or 7d.
#  #11 US-session momentum long.  Entry: 11:00->15:00 UTC return >= +1.0%
#      (signal at 15:00 close) -> long 16:00 open.  Stop: entry - 1.0xATR(24,1h).
#      Exit: 22:00 UTC (21:00 bar close).  Why: US-hours risk-on flow keeps
#      pushing into the afternoon.  Flip: <= -1% -> short same window.
#  #12 ETH/BTC vol-ratio stress -> short ETH (cross-asset; executed on ETH).
#      Entry: HV20(ETH)/HV20(BTC) >= 1.5 -> short ETH next daily open.
#      Stop: entry + 1.5xATR14(ETH).  Exit: ratio <= 1.2, or 10d.  Why: ETH
#      stress regimes (depeg scares) persist and underperform.  Flip: long.
#  #13 Asia-hours dip reversion long.  Entry: 00:00->07:00 UTC cumulative
#      return <= -2.0% (signal at 07:00 close) -> long 08:00 open.  Stop:
#      entry - 0.8xATR(24,1h).  Exit: 12:00 UTC.  Why: Asian selling exhausts
#      before the European open.  Flip: >= +2% -> short 08:00->12:00.
#  #14 Quiet-panic low-volume selloff long.  Entry: daily ret <= -3.5% AND
#      volume <= 0.7xSMA20(daily volume) -> long next open.  Stop: low -
#      0.75xATR14.  Exit: 4d.  Why: price down on ABSENT volume = no aggressive
#      sellers, just no buyers; refills upward.  Flip: +3.5% on low volume
#      -> short.
#  #15 Quarter-end weakness short.  Entry: short at the 00:00 open of the LAST
#      calendar day of each quarter (signal on prior close).  Stop: entry +
#      2.0xATR14.  Exit: that day's 24:00 close.  Why: quarter-end de-risking /
#      mark-to-market.  Flip: long the same day.
#
# PER-IDEA OUTPUT: n, win%, PF, avgR, ret%, maxDD%, avg gross move/trade,
#   halves (2017-20 / 2021-26; funding ideas use funding-start-21 / 22-26),
#   placebo PF percentile (100 runs), flipped-direction PF, daily-R correlation
#   with oslib K8 and with the full oslib live basket (equal-1% daily sum).
#
# KEEP RULE (pre-declared): BTC PF > 1.3 in BOTH halves, n >= 30, placebo
#   percentile >= 90, flipped PF < 1, ETH PF > 1.0 (n/a for the cross-asset
#   ideas 8/12, which are executed on ETH - their corr is taken vs the ETH
#   basket), daily-R corr with the live basket < 0.3. One-line verdict per
#   idea; pairwise trade-overlap % among KEEPs at the end.
#
# KNOWN CLUSTER FLAGS (declared up front, the overlap matrix arbitrates):
#   #3/#10 vs Batch13 #4/#11 (funding family, different trigger: 7d sum vs
#     single 8h stamp); #9 vs Batch13 #1 (reversion family, different trigger:
#     5-red streak vs RSI2); #6/#12 short-vol family.
# =============================================================================

import os

import numpy as np
import pandas as pd

OSLIB_URL = "https://osom-boba.pages.dev/colab/oslib.py"


def _ensure_oslib():
    if os.path.exists("oslib.py") and os.path.getsize("oslib.py") > 1000:
        return
    rc = os.system(f'wget -q -O oslib.py "{OSLIB_URL}"')
    if rc == 0 and os.path.exists("oslib.py") and os.path.getsize("oslib.py") > 1000:
        return
    import urllib.request
    urllib.request.urlretrieve(OSLIB_URL, "oslib.py")


_ensure_oslib()
import oslib  # noqa: E402

H1, H4, D1 = oslib.H1, oslib.H4, oslib.D1
COST = oslib.COST                      # 0.12%/side
N_PLACEBO = 100
SPLIT_2017 = "2021-01-01"
SPLIT_2019 = "2022-01-01"


# ---- small helpers (signal math only; data/engine/fees/stats stay oslib) -----
def _complete(df, period_ms, per):
    """oslib.resample_ohlcv keeping only complete buckets (per sub-bars each)."""
    r = oslib.resample_ohlcv(df, period_ms)
    g = df["time"].to_numpy("int64") // period_ms
    cnt = pd.Series(g).value_counts()
    need = cnt.reindex(r["time"].to_numpy("int64") // period_ms).to_numpy()
    return r.iloc[np.asarray(need) == per].reset_index(drop=True)


def base_of(df, tf_ms):
    return {"t": df["time"].to_numpy("int64"),
            "o": df["open"].to_numpy(float), "h": df["high"].to_numpy(float),
            "l": df["low"].to_numpy(float), "c": df["close"].to_numpy(float),
            "tf": int(tf_ms)}


def atr_sma(h, l, c, n):
    """Published convention: ATR(n) = simple mean of true range (oslib pieces)."""
    return oslib.sma(oslib.true_range(h, l, c), n)


def rmean(a, n):
    return pd.Series(a).rolling(n, min_periods=n).mean().to_numpy()


def tsb_after(base, delta_ms):
    """Time-stop fn: first bar CLOSE at/after entry_open + delta_ms -> bars from fill."""
    tc = base["t"] + base["tf"]
    def f(ei):
        j = int(np.searchsorted(tc, base["t"][ei] + delta_ms, side="left"))
        return max(1, j - ei)
    return f


def _noz(entry, side, ei):
    return (None, 0.0)


def zm_bin(cond, side_run):
    """zmaker from a global 0/1 exit-condition array, polarized for the run side."""
    z = cond.astype(float) if side_run > 0 else (1.0 - cond.astype(float))
    def f(entry, side, ei):
        return z, 0.5
    return f


def _sig(i, side, stop_px, tgt_px, tsb, zmaker, ei=None):
    d = dict(i=int(i), side=int(side), stop_px=float(stop_px), tgt_px=float(tgt_px),
             tsb=tsb, zmaker=zmaker)
    if ei is not None:
        d["ei"] = int(ei)
    return d


def vol_daily(ctx, asset):
    """Base-asset volume summed per UTC day, aligned to the asset's daily grid."""
    df1 = ctx[asset]["df"]
    g = df1["time"].to_numpy("int64") // D1
    vd = pd.Series(df1["volume"].to_numpy(float)).groupby(g).sum()
    td = ctx[asset]["1d"]["t"] // D1
    return vd.reindex(td).to_numpy()


def fund_sum7(ctx, asset, t_daily):
    """7-day funding sum (last 21 stamps) as of each daily bar's close.
    NaN before 7 full days of funding coverage. Returns (array, warm_index)."""
    n = len(t_daily)
    f = ctx["fund"].get(asset)
    if f is None or not len(f):
        return np.full(n, np.nan), n
    ft = f["time"].to_numpy("int64")
    fr = f["funding"].to_numpy(float)
    g0 = int(ft.min() // D1)
    g1 = int(ft.max() // D1) + 1
    ds = pd.Series(fr).groupby(ft // D1).sum()
    grid = pd.Series(0.0, index=pd.RangeIndex(g0, g1)).add(ds, fill_value=0.0)
    s7 = grid.rolling(7, min_periods=7).sum()
    gd = t_daily // D1
    out = s7.reindex(gd).to_numpy()
    out = out.astype(float)
    out[gd < g0 + 6] = np.nan
    warm = int(np.searchsorted(gd, g0 + 6, side="left"))
    return out, min(warm, n)


# ---- executor (single position; oslib.walk_1h does all fills/costs) ----------
def execute(sigs, base, name):
    t, o = base["t"], base["o"]
    n = len(t)
    out, taken = [], []
    last_xi = -1
    for s in sorted(sigs, key=lambda d: d["i"]):
        ei = int(s.get("ei", s["i"] + 1))
        if ei <= last_xi or ei >= n:
            continue
        entry = float(o[ei])
        stop = float(s["stop_px"])
        side = int(s["side"])
        if not (np.isfinite(entry) and np.isfinite(stop)) or side * (entry - stop) <= 0:
            continue
        z, zf = s["zmaker"](entry, side, ei)
        tsb = s["tsb"](ei) if callable(s["tsb"]) else int(s["tsb"])
        tgt = float(s["tgt_px"]) if np.isfinite(s["tgt_px"]) else None
        tr = oslib.walk_1h(t, o, base["h"], base["l"], base["c"], ei, side, entry, stop,
                           target=tgt, time_stop_bars=tsb, z=z, z_flip=zf, src=name)
        out.append(tr)
        taken.append(s)
        last_xi = int(tr["xi"])
    return out, taken


def pf_of(trades, start_str, end_str=None):
    tf = oslib._window(oslib._tframe(trades), start_str, end_str)
    return oslib.tstats(tf)["pf"]


def placebo_pct(taken, base, warmup, start_str, actual_pf, n_runs=N_PLACEBO, seed=13):
    """100 shuffled-entry runs on oslib.walk_1h; each placebo trade inherits the
    actual trade's side / stop distance / target distance / exit logic."""
    o = base["o"]
    n = len(o)
    if not taken or not np.isfinite(actual_pf):
        return np.nan
    lo, hi = max(1, int(warmup)), n - 2
    if hi <= lo:
        return np.nan
    rng = np.random.default_rng(seed)
    spec = []
    for s in taken:
        ei0 = int(s.get("ei", s["i"] + 1))
        e0 = float(o[ei0])
        side = int(s["side"])
        rf = abs(e0 - float(s["stop_px"])) / e0
        tf_ = (side * (float(s["tgt_px"]) / e0 - 1.0)) if np.isfinite(s["tgt_px"]) else np.nan
        spec.append((side, rf, tf_, s["tsb"], s["zmaker"]))
    pfs = []
    for _ in range(n_runs):
        trs = []
        for (side, rf, tf_, tsb, zm) in spec:
            ei = int(rng.integers(lo, hi + 1))
            entry = float(o[ei])
            stop = entry - side * rf * entry
            tgt = entry + side * tf_ * entry if np.isfinite(tf_) else None
            ts = tsb(ei) if callable(tsb) else int(tsb)
            z, zf = zm(entry, side, ei)
            trs.append(oslib.walk_1h(base["t"], base["o"], base["h"], base["l"], base["c"],
                                     ei, side, entry, stop, target=tgt, time_stop_bars=ts,
                                     z=z, z_flip=zf, src="PLC"))
        pfs.append(pf_of(trs, start_str))
    return 100.0 * float(np.mean([p < actual_pf for p in pfs]))


# ---- the 15 idea builders (exact published numbers) --------------------------
def i01(ctx, asset, flip):
    """#01 turn-of-month long: long every day in the last 3 / first 3 calendar
    days of a month, one position through the window. Stop = entry - 2 ATR14.
    Exit: 24:00 close of the last TOM day. Flip: short the same windows."""
    B = ctx[asset]["1d"]
    t, o, c = B["t"], B["o"], B["c"]
    h, l = B["h"], B["l"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    dt = pd.to_datetime(t, unit="ms", utc=True)
    dom = dt.day.to_numpy()
    dim = dt.days_in_month.to_numpy()
    tom = (dom > dim - 3) | (dom <= 3)
    warm = 30
    sigs = []
    i = warm
    while i < n:
        if not tom[i]:
            i += 1
            continue
        j = i
        while j + 1 < n and tom[j + 1]:
            j += 1
        if i - 1 >= 1 and np.isfinite(a[i - 1]) and np.isfinite(o[i]) and np.isfinite(o[i - 1]):
            side = -1 if flip else 1
            stop = o[i] - side * 2.0 * a[i - 1]
            tsb = int(j - i)                       # 0 -> exit at the entry bar's close
            sigs.append(_sig(i - 1, side, stop, np.nan, tsb, _noz, ei=i))
        i = j + 1
    return sigs, warm


def i02(ctx, asset, flip):
    """#02 volume-climax exhaustion: ret <= -6%, vol >= 3x SMA20(vol), close in
    top 40% of range -> long. Stop = low - 0.5 ATR; exit 5d. Flip: +6% climax
    closing in bottom 40% -> short."""
    B = ctx[asset]["1d"]
    o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    v = vol_daily(ctx, asset)
    vs = rmean(v, 20)
    rd = pd.Series(c).pct_change().to_numpy()
    rng = h - l
    with np.errstate(invalid="ignore", divide="ignore"):
        pos = np.where(rng > 0, (c - l) / np.where(rng > 0, rng, 1.0), np.nan)
    tsb = tsb_after(B, 5 * D1)
    warm = 30
    sigs = []
    if not flip:
        m = (rd <= -0.06) & (v >= 3.0 * vs) & (pos >= 0.60) & np.isfinite(a)
        for i in range(warm, n - 1):
            if m[i]:
                sigs.append(_sig(i, 1, l[i] - 0.5 * a[i], np.nan, tsb, _noz))
        return sigs, warm
    m = (rd >= 0.06) & (v >= 3.0 * vs) & (pos <= 0.40) & np.isfinite(a)
    for i in range(warm, n - 1):
        if m[i]:
            sigs.append(_sig(i, -1, h[i] + 0.5 * a[i], np.nan, tsb, _noz))
    return sigs, warm


def i03(ctx, asset, flip):
    """#03 7d funding-sum <= -0.15% squeeze long. Stop = entry - 2 ATR14.
    Exit: 7d sum >= 0 or 14d. Flip: sum >= +0.15% short, exit sum <= 0 or 14d."""
    B = ctx[asset]["1d"]
    o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    fs, wfs = fund_sum7(ctx, asset, B["t"])
    tsb = tsb_after(B, 14 * D1)
    warm = max(30, wfs)
    sigs = []
    if not flip:
        cond_x = np.nan_to_num(fs, nan=1.0) >= 0.0
        m = np.isfinite(fs) & (fs <= -0.0015) & np.isfinite(a)
        for i in range(warm, n - 1):
            if m[i]:
                sigs.append(_sig(i, 1, o[i + 1] - 2.0 * a[i], np.nan, tsb, zm_bin(cond_x, 1)))
        return sigs, warm
    cond_x = np.nan_to_num(fs, nan=1.0) <= 0.0
    m = np.isfinite(fs) & (fs >= 0.0015) & np.isfinite(a)
    for i in range(warm, n - 1):
        if m[i]:
            sigs.append(_sig(i, -1, o[i + 1] + 2.0 * a[i], np.nan, tsb, zm_bin(cond_x, -1)))
    return sigs, warm


def i04(ctx, asset, flip):
    """#04 wide-range follow-through: range >= 2.5 ATR14, ret >= +3%, close in
    top 25% -> long. Stop = low - 0.25 ATR; exit 3d. Flip: wide-range down day
    closing in bottom 25% -> short."""
    B = ctx[asset]["1d"]
    o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    rd = pd.Series(c).pct_change().to_numpy()
    rng = h - l
    with np.errstate(invalid="ignore", divide="ignore"):
        pos = np.where(rng > 0, (c - l) / np.where(rng > 0, rng, 1.0), np.nan)
    tsb = tsb_after(B, 3 * D1)
    warm = 30
    sigs = []
    if not flip:
        m = (rng >= 2.5 * a) & (rd >= 0.03) & (pos >= 0.75) & np.isfinite(a)
        for i in range(warm, n - 1):
            if m[i]:
                sigs.append(_sig(i, 1, l[i] - 0.25 * a[i], np.nan, tsb, _noz))
        return sigs, warm
    m = (rng >= 2.5 * a) & (rd <= -0.03) & (pos <= 0.25) & np.isfinite(a)
    for i in range(warm, n - 1):
        if m[i]:
            sigs.append(_sig(i, -1, h[i] + 0.25 * a[i], np.nan, tsb, _noz))
    return sigs, warm


def i05(ctx, asset, flip):
    """#05 weekend drift: short every Sat 00:00 open (signal Fri 23:00 close).
    Stop = entry + 1.5%; cover Monday 00:00 UTC (Sun 23:00 bar close).
    Flip: long the same window."""
    B = ctx[asset]["1h"]
    t, o = B["t"], B["o"]
    n = len(t)
    dt = pd.to_datetime(t, unit="ms", utc=True)
    dow = dt.dayofweek.to_numpy()
    hour23 = (t % D1) == 23 * H1
    hour0 = (t % D1) == 0
    fri = np.where((dow == 4) & hour23)[0]
    warm = int(fri[0]) if len(fri) else n
    tsfn = tsb_after(B, 47 * H1)                 # first close >= Sat00:00+47h = Mon 00:00
    sigs = []
    for fi in fri:
        ei = int(fi) + 1
        if ei >= n or not hour0[ei] or dow[ei] != 5:
            continue
        side = 1 if flip else -1
        stop = o[ei] * (0.985 if side > 0 else 1.015)
        sigs.append(_sig(fi, side, stop, np.nan, tsfn, _noz, ei=ei))
    return sigs, warm


def i06(ctx, asset, flip):
    """#06 high-vol regime short: HV20 (20d log-ret std, annualized) in the top
    20% of its trailing 364d and a red day -> short. Stop = entry + 1.5 ATR14.
    Exit: HV20 pct <= 60% or 10d. Flip: green day in top-20% HV -> long."""
    B = ctx[asset]["1d"]
    o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    lr = np.full(n, np.nan)
    lr[1:] = np.log(c[1:] / c[:-1])
    hv = pd.Series(lr).rolling(20, min_periods=20).std(ddof=1).to_numpy() * np.sqrt(365.0)
    pct = np.full(n, np.nan)
    for i in range(384, n):
        if not np.isfinite(hv[i]):
            continue
        w = hv[i - 364:i]
        w = w[np.isfinite(w)]
        if len(w) >= 200:
            pct[i] = float(np.mean(w < hv[i]))
    rd = pd.Series(c).pct_change().to_numpy()
    tsb = tsb_after(B, 10 * D1)
    warm = 384
    cond_x = np.nan_to_num(pct, nan=1.0) <= 0.60
    sigs = []
    if not flip:
        m = (pct >= 0.80) & (rd < 0.0) & np.isfinite(a)
        for i in range(warm, n - 1):
            if m[i]:
                sigs.append(_sig(i, -1, o[i + 1] + 1.5 * a[i], np.nan, tsb, zm_bin(cond_x, -1)))
        return sigs, warm
    m = (pct >= 0.80) & (rd > 0.0) & np.isfinite(a)
    for i in range(warm, n - 1):
        if m[i]:
            sigs.append(_sig(i, 1, o[i + 1] - 1.5 * a[i], np.nan, tsb, zm_bin(cond_x, 1)))
    return sigs, warm


def i07(ctx, asset, flip):
    """#07 month-start momentum: days 1-3 of month >= +3% (close vs prior month
    last close) -> long day-4 open to day-7 close; <= -3% -> short. Stop =
    entry -/+ 2 ATR14. Flip: fade the 3-day move."""
    B = ctx[asset]["1d"]
    t, o, h, l, c = B["t"], B["o"], B["h"], B["l"], B["c"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    dt = pd.to_datetime(t, unit="ms", utc=True)
    dom = dt.day.to_numpy()
    ym = dt.year.to_numpy() * 12 + dt.month.to_numpy() - 1
    last_of_ym = {}
    for k in range(n):
        last_of_ym[ym[k]] = k
    m3 = (dom == 3)
    r3 = np.full(n, np.nan)
    for k in range(n):
        p = last_of_ym.get(ym[k] - 1)
        if m3[k] and p is not None:
            r3[k] = c[k] / c[p] - 1.0
    tsb = tsb_after(B, 4 * D1)
    warm = 40
    sigs = []
    for i in range(warm, n - 1):
        if not np.isfinite(r3[i]) or not np.isfinite(a[i]):
            continue
        if r3[i] >= 0.03:
            side = -1 if flip else 1
        elif r3[i] <= -0.03:
            side = 1 if flip else -1
        else:
            continue
        stop = o[i + 1] - side * 2.0 * a[i]
        sigs.append(_sig(i, side, stop, np.nan, tsb, _noz))
    return sigs, warm


def i08(ctx, asset, flip):
    """#08 ETH/BTC ratio 20d momentum -> trade ETH (executed on ETH bars):
    ratio +5%/20d -> long ETH; -5% -> short ETH. Stop = entry -/+ 2 ATR14(ETH).
    Exit 10d. Flip: fade the move. Cross-asset idea."""
    B = ctx["eth"]["1d"]
    BB = ctx["btc"]["1d"]
    t, o, c = B["t"], B["o"], B["c"]
    n = len(c)
    gE = t // D1
    gB = BB["t"] // D1
    btc_c = pd.Series(BB["c"], index=gB).reindex(gE).to_numpy()
    with np.errstate(invalid="ignore", divide="ignore"):
        ratio = c / btc_c
    r20 = np.full(n, np.nan)
    r20[20:] = ratio[20:] / ratio[:-20] - 1.0
    fin = np.isfinite(r20) & np.isfinite(ratio)
    warm = int(np.argmax(fin)) if np.any(fin) else n
    aE = atr_sma(B["h"], B["l"], c, 14)
    tsb = tsb_after(B, 10 * D1)
    sigs = []
    for i in range(max(warm, 30), n - 1):
        if not fin[i] or not np.isfinite(aE[i]) or not np.isfinite(o[i + 1]):
            continue
        if r20[i] >= 0.05:
            side = -1 if flip else 1
        elif r20[i] <= -0.05:
            side = 1 if flip else -1
        else:
            continue
        stop = o[i + 1] - side * 2.0 * aE[i]
        sigs.append(_sig(i, side, stop, np.nan, tsb, _noz))
    return sigs, max(warm, 30)


def i09(ctx, asset, flip):
    """#09 streak exhaustion: green bar after 5 consecutive red closes -> long;
    red bar after 5 consecutive green closes -> short. Stop = low - 0.5 ATR14 /
    high + 0.5 ATR14. Exit 4d. Flip: continuation (fade the reversal bar)."""
    B = ctx[asset]["1d"]
    o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    red = (c < o).astype(float)
    grn = (c > o).astype(float)
    cnt_red_prev = pd.Series(red).rolling(5, min_periods=5).sum().shift(1).to_numpy()
    cnt_grn_prev = pd.Series(grn).rolling(5, min_periods=5).sum().shift(1).to_numpy()
    long_sig = (c > o) & (cnt_red_prev == 5.0)
    short_sig = (c < o) & (cnt_grn_prev == 5.0)
    tsb = tsb_after(B, 4 * D1)
    warm = 30
    sigs = []
    if not flip:
        for i in range(warm, n - 1):
            if not np.isfinite(a[i]):
                continue
            if long_sig[i]:
                sigs.append(_sig(i, 1, l[i] - 0.5 * a[i], np.nan, tsb, _noz))
            elif short_sig[i]:
                sigs.append(_sig(i, -1, h[i] + 0.5 * a[i], np.nan, tsb, _noz))
        return sigs, warm
    for i in range(warm, n - 1):
        if not np.isfinite(a[i]):
            continue
        if long_sig[i]:
            sigs.append(_sig(i, -1, h[i] + 0.5 * a[i], np.nan, tsb, _noz))
        elif short_sig[i]:
            sigs.append(_sig(i, 1, l[i] - 0.5 * a[i], np.nan, tsb, _noz))
    return sigs, warm


def i10(ctx, asset, flip):
    """#10 euphoric funding-sum stall short (2019+): 7d sum >= +0.30% and 24h
    ret <= 0 -> short. Stop = entry + 1.5 ATR14. Exit: 7d sum <= +0.10% or 7d.
    Flip: sum <= -0.30% with a green day -> long, exit sum >= -0.10% or 7d."""
    B = ctx[asset]["1d"]
    o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    fs, wfs = fund_sum7(ctx, asset, B["t"])
    rd = pd.Series(c).pct_change().to_numpy()
    tsb = tsb_after(B, 7 * D1)
    warm = max(30, wfs)
    sigs = []
    if not flip:
        cond_x = np.nan_to_num(fs, nan=1.0) <= 0.0010
        m = np.isfinite(fs) & (fs >= 0.0030) & (rd <= 0.0) & np.isfinite(a)
        for i in range(warm, n - 1):
            if m[i]:
                sigs.append(_sig(i, -1, o[i + 1] + 1.5 * a[i], np.nan, tsb, zm_bin(cond_x, -1)))
        return sigs, warm
    cond_x = np.nan_to_num(fs, nan=1.0) >= -0.0010
    m = np.isfinite(fs) & (fs <= -0.0030) & (rd >= 0.0) & np.isfinite(a)
    for i in range(warm, n - 1):
        if m[i]:
            sigs.append(_sig(i, 1, o[i + 1] - 1.5 * a[i], np.nan, tsb, zm_bin(cond_x, 1)))
    return sigs, warm


def i11(ctx, asset, flip):
    """#11 US-session momentum: 11:00->15:00 UTC return >= +1.0% (signal at the
    15:00 close) -> long at 16:00 open. Stop = entry - 1 ATR(24,1h). Exit 22:00
    UTC (21:00 bar close). Flip: <= -1% -> short the same window."""
    B = ctx[asset]["1h"]
    t, o, h, l, c = B["t"], B["o"], B["h"], B["l"], B["c"]
    n = len(t)
    a = atr_sma(h, l, c, 24)
    sig_bars = np.where((t % D1) == 15 * H1)[0]
    warm = 30
    tsfn = tsb_after(B, 6 * H1)                  # first close >= 16:00+6h = 22:00
    sigs = []
    for i in sig_bars:
        i = int(i)
        if i - 5 < 0 or i + 1 >= n or not np.isfinite(a[i]):
            continue
        r5 = c[i] / c[i - 5] - 1.0
        if not (r5 >= 0.01):
            continue
        side = -1 if flip else 1
        stop = o[i + 1] - side * 1.0 * a[i]
        sigs.append(_sig(i, side, stop, np.nan, tsfn, _noz))
    return sigs, warm


def i12(ctx, asset, flip):
    """#12 ETH/BTC vol-ratio stress -> short ETH (executed on ETH bars):
    HV20(ETH)/HV20(BTC) >= 1.5 -> short ETH next daily open. Stop = entry +
    1.5 ATR14(ETH). Exit: ratio <= 1.2 or 10d. Flip: long. Cross-asset idea."""
    B = ctx["eth"]["1d"]
    BB = ctx["btc"]["1d"]
    t, o, c = B["t"], B["o"], B["c"]
    n = len(c)
    gE = t // D1
    gB = BB["t"] // D1
    btc_c = pd.Series(BB["c"], index=gB).reindex(gE).to_numpy()

    def _hv(x):
        s = pd.Series(x, dtype=float)
        lr = np.log(s).diff()
        return lr.rolling(20, min_periods=20).std(ddof=1).to_numpy() * np.sqrt(365.0)

    hvE = _hv(c)
    hvB = _hv(btc_c)
    with np.errstate(invalid="ignore", divide="ignore"):
        ratio = hvE / hvB
    fin = np.isfinite(ratio)
    warm = int(np.argmax(fin)) if np.any(fin) else n
    aE = atr_sma(B["h"], B["l"], c, 14)
    tsb = tsb_after(B, 10 * D1)
    cond_x = np.nan_to_num(ratio, nan=np.inf) <= 1.2
    sigs = []
    for i in range(max(warm, 30), n - 1):
        if not fin[i] or not np.isfinite(aE[i]) or not np.isfinite(o[i + 1]):
            continue
        if ratio[i] >= 1.5:
            side = 1 if flip else -1
            stop = o[i + 1] - side * 1.5 * aE[i]
            sigs.append(_sig(i, side, stop, np.nan, tsb, zm_bin(cond_x, side)))
    return sigs, max(warm, 30)


def i13(ctx, asset, flip):
    """#13 Asia-hours dip reversion: 00:00->07:00 UTC cumulative return <= -2%
    (signal at the 07:00 close) -> long at 08:00 open. Stop = entry - 0.8
    ATR(24,1h). Exit 12:00 UTC. Flip: >= +2% -> short 08:00->12:00."""
    B = ctx[asset]["1h"]
    t, o, h, l, c = B["t"], B["o"], B["h"], B["l"], B["c"]
    n = len(t)
    a = atr_sma(h, l, c, 24)
    sig_bars = np.where((t % D1) == 7 * H1)[0]
    warm = 30
    tsfn = tsb_after(B, 4 * H1)                  # first close >= 08:00+4h = 12:00
    sigs = []
    for i in sig_bars:
        i = int(i)
        if i - 7 < 0 or i + 1 >= n or not np.isfinite(a[i]):
            continue
        cum = c[i] / o[i - 7] - 1.0
        if not (cum <= -0.02):
            continue
        side = -1 if flip else 1
        stop = o[i + 1] - side * 0.8 * a[i]
        sigs.append(_sig(i, side, stop, np.nan, tsfn, _noz))
    return sigs, warm


def i14(ctx, asset, flip):
    """#14 quiet-panic low-volume selloff: ret <= -3.5% on volume <= 0.7x
    SMA20(vol) -> long. Stop = low - 0.75 ATR14; exit 4d. Flip: +3.5% on low
    volume -> short."""
    B = ctx[asset]["1d"]
    o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    v = vol_daily(ctx, asset)
    vs = rmean(v, 20)
    rd = pd.Series(c).pct_change().to_numpy()
    tsb = tsb_after(B, 4 * D1)
    warm = 30
    sigs = []
    if not flip:
        m = (rd <= -0.035) & (v <= 0.7 * vs) & np.isfinite(a)
        for i in range(warm, n - 1):
            if m[i]:
                sigs.append(_sig(i, 1, l[i] - 0.75 * a[i], np.nan, tsb, _noz))
        return sigs, warm
    m = (rd >= 0.035) & (v <= 0.7 * vs) & np.isfinite(a)
    for i in range(warm, n - 1):
        if m[i]:
            sigs.append(_sig(i, -1, h[i] + 0.75 * a[i], np.nan, tsb, _noz))
    return sigs, warm


def i15(ctx, asset, flip):
    """#15 quarter-end weakness: short at the 00:00 open of the LAST calendar
    day of each quarter (signal on prior close). Stop = entry + 2 ATR14.
    Exit: that day's 24:00 close. Flip: long the same day."""
    B = ctx[asset]["1d"]
    t, o, h, l, c = B["t"], B["o"], B["h"], B["l"], B["c"]
    n = len(c)
    a = atr_sma(h, l, c, 14)
    dt = pd.to_datetime(t, unit="ms", utc=True)
    q = dt.year.to_numpy() * 4 + (dt.month.to_numpy() - 1) // 3
    warm = 30
    sigs = []
    for j in range(warm + 1, n - 1):
        if q[j] > q[j + 1] and q[j - 1] == q[j]:
            # j = last daily bar of a quarter; signal at j-1 close, fill at j open
            if not (np.isfinite(a[j - 1]) and np.isfinite(o[j])):
                continue
            side = 1 if flip else -1
            stop = o[j] - side * 2.0 * a[j - 1]
            sigs.append(_sig(j - 1, side, stop, np.nan, 0, _noz, ei=j))
    return sigs, warm


IDEAS = [
    dict(num=1, title="Turn-of-month long (last3+first3 days)", fn=i01, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="long"),
    dict(num=2, title="Volume-climax exhaustion long (3x vol, -6%)", fn=i02, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="long", needs_volume=True),
    dict(num=3, title="7d funding-sum <= -0.15% squeeze long", fn=i03, walk="1d",
         start="fund", split=SPLIT_2019, dirL="long", needs_fund=True),
    dict(num=4, title="Wide-range day follow-through long (2.5 ATR, +3%)", fn=i04, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="long"),
    dict(num=5, title="Weekend drift short (Sat00:00 -> Mon00:00)", fn=i05, walk="1h",
         start="2017-01-01", split=SPLIT_2017, dirL="short"),
    dict(num=6, title="High-vol regime short (HV20 pct>=80, red day)", fn=i06, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="short"),
    dict(num=7, title="Month-start momentum (+/-3% in days 1-3)", fn=i07, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="both"),
    dict(num=8, title="ETH/BTC ratio 20d momentum -> trade ETH", fn=i08, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="both", btc_only=True, trade_ctx="eth"),
    dict(num=9, title="Streak exhaustion (5 red -> green bar)", fn=i09, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="both"),
    dict(num=10, title="Euphoric funding-sum >= +0.30% stall short", fn=i10, walk="1d",
         start="fund", split=SPLIT_2019, dirL="short", needs_fund=True),
    dict(num=11, title="US-session momentum long (11-15h >= +1%)", fn=i11, walk="1h",
         start="2017-01-01", split=SPLIT_2017, dirL="long"),
    dict(num=12, title="ETH/BTC vol-ratio >= 1.5 stress short ETH", fn=i12, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="short", btc_only=True, trade_ctx="eth"),
    dict(num=13, title="Asia-hours dip reversion (00-07h <= -2%)", fn=i13, walk="1h",
         start="2017-01-01", split=SPLIT_2017, dirL="long"),
    dict(num=14, title="Quiet-panic low-volume selloff long", fn=i14, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="long", needs_volume=True),
    dict(num=15, title="Quarter-end last-day weakness short", fn=i15, walk="1d",
         start="2017-01-01", split=SPLIT_2017, dirL="short"),
]


# ---- stats -------------------------------------------------------------------
def f2(x):
    if x is None or not np.isfinite(x):
        return "-"
    if np.isinf(x):
        return "inf"
    return f"{x:.2f}"


def f1(x):
    if x is None or not np.isfinite(x):
        return "-"
    if np.isinf(x):
        return "inf"
    return f"{x:.1f}"


def idea_stats(trades, start_str, split_str):
    tf = oslib._tframe(trades)
    full = oslib.tstats(oslib._window(tf, start_str))
    h1 = oslib.tstats(oslib._window(tf, start_str, split_str))
    h2 = oslib.tstats(oslib._window(tf, split_str))
    ms0 = oslib.ms(start_str)
    mv = [t["side"] * (t["exit"] / t["entry"] - 1.0) for t in trades
          if t["t_out"] >= ms0 and np.isfinite(t["entry"]) and np.isfinite(t["exit"])]
    gross = 100.0 * float(np.mean(mv)) if mv else np.nan
    return dict(n=full["tr"], win=full["win"], pf=full["pf"], avgR=full["avgR"],
                ret=full["ret"], dd=full["dd"], gross=gross,
                h1=(h1["pf"], h1["tr"]), h2=(h2["pf"], h2["tr"]))


def _dtidx(s):
    """Daily series -> DatetimeIndex (oslib k8_daily uses integer day numbers)."""
    if isinstance(s.index, pd.DatetimeIndex):
        return pd.Series(s.to_numpy(), index=s.index)
    return pd.Series(s.to_numpy(),
                     index=pd.to_datetime(np.asarray(s.index).astype("int64") * D1, unit="ms", utc=True))


def corr_daily(a, b):
    if a is None or b is None or not len(a) or not len(b):
        return np.nan
    a2, b2 = _dtidx(a), _dtidx(b)
    idx = a2.index.union(b2.index)
    a2 = a2.reindex(idx).fillna(0.0)
    b2 = b2.reindex(idx).fillna(0.0)
    if a2.std() == 0 or b2.std() == 0:
        return np.nan
    return float(a2.corr(b2))


def overlap_pct(trA, trB):
    """% of the smaller trade set whose [entry, exit) interval overlaps any trade
    of the other idea."""
    if not trA or not trB:
        return np.nan
    A = sorted((int(t["t_in"]), int(t["t_out"])) for t in trA)
    B = sorted((int(t["t_in"]), int(t["t_out"])) for t in trB)
    if len(A) > len(B):
        A, B = B, A
    b0 = np.asarray([x[0] for x in B])
    b1 = np.asarray([x[1] for x in B])
    hit = 0
    for (a0, a1) in A:
        j = int(np.searchsorted(b1, a0, side="right"))
        if j > 0 and np.any(b0[:j] < a1):
            hit += 1
    return 100.0 * hit / len(A)


# ---- run one idea on one asset -----------------------------------------------
def run_idea(spec, ctx, k8d, baskd):
    num, title = spec["num"], spec["title"]
    ta = spec.get("trade_ctx", spec["_asset"])   # ideas 8/12 execute on ETH bars
    row = dict(idea=f"#{num:02d} {title}", asset=ta)
    if spec.get("skip"):
        row.update(status="SKIPPED", note=spec["skip"])
        return row
    if spec.get("btc_only") and spec["_asset"] != "btc":
        row.update(status="N/A", note="cross-asset idea (signal needs BTC data; traded on ETH)")
        return row
    if spec.get("needs_fund") and ctx["fund"].get(ta) is None:
        row.update(status="SKIPPED", note="funding history unavailable for this asset")
        return row
    if spec.get("needs_volume"):
        v = ctx[ta]["df"].get("volume")
        if v is None or float(np.nansum(np.abs(v.to_numpy(float)))) <= 0:
            row.update(status="SKIPPED", note="oslib.load returned no volume field")
            return row
    try:
        base = ctx[ta][spec["walk"]]
        start_str = ctx["fund_start"].get(ta) if spec["start"] == "fund" else spec["start"]
        sigs, warm = spec["fn"](ctx, ta, flip=False)
        trades, taken = execute(sigs, base, f"#{num:02d}")
        st = idea_stats(trades, start_str, spec["split"])
        pct = placebo_pct(taken, base, warm, start_str, st["pf"],
                          seed=1000 * num + 7 + (0 if ta == "btc" else 1))
        fsigs, _fw = spec["fn"](ctx, ta, flip=True)
        ftrades, _ft = execute(fsigs, base, f"#{num:02d}flip")
        fst = oslib.tstats(oslib._window(oslib._tframe(ftrades), start_str))
        d_idea = oslib.daily_from_trades(trades, start_str)
        row.update(status="OK", start=start_str, n=st["n"], win=st["win"], pf=st["pf"],
                   avgR=st["avgR"], ret=st["ret"], dd=st["dd"], gross=st["gross"],
                   h1_pf=st["h1"][0], h1_n=st["h1"][1], h2_pf=st["h2"][0], h2_n=st["h2"][1],
                   plc=pct, flip_pf=fst["pf"],
                   corr_k8=corr_daily(d_idea, k8d[ta]),
                   corr_bask=corr_daily(d_idea, baskd[ta]), trades=trades)
        return row
    except Exception as ex:
        row.update(status="ERROR", note=f"{type(ex).__name__}: {ex}")
        return row


def verdict_of(row):
    if row.get("status") != "OK":
        return row.get("status", "?"), []
    fails = []
    if not (np.isfinite(row["h1_pf"]) and row["h1_pf"] > 1.3):
        fails.append(f"H1 PF {f2(row['h1_pf'])}")
    if not (np.isfinite(row["h2_pf"]) and row["h2_pf"] > 1.3):
        fails.append(f"H2 PF {f2(row['h2_pf'])}")
    if row["n"] < 30:
        fails.append(f"n {row['n']}<30")
    if not (np.isfinite(row["plc"]) and row["plc"] >= 90):
        fails.append(f"plc {f1(row['plc'])}%")
    if not (np.isfinite(row["flip_pf"]) and row["flip_pf"] < 1.0):
        fails.append(f"flip PF {f2(row['flip_pf'])}")
    if row.get("eth_pf") is not None:
        if not (np.isfinite(row["eth_pf"]) and row["eth_pf"] > 1.0):
            fails.append(f"ETH PF {f2(row['eth_pf'])}")
    if not (np.isfinite(row["corr_bask"]) and row["corr_bask"] < 0.3):
        fails.append(f"corrB {f2(row['corr_bask'])}")
    return ("KEEP" if not fails else "DROP"), fails


def main():
    if not oslib.in_colab():
        raise SystemExit("Batch14: run inside Colab - oslib refuses real market data outside /content.")
    print(f"oslib v{oslib.__version__} | cost {COST:.2%}/side (round trip {2 * COST:.2%}) | "
          f"risk 1%/trade (oslib.RISK) | placebo {N_PLACEBO} shuffled runs per idea")
    print("15 NEW ideas - no Batch13 trigger reused (no RSI2 / 20d sweep / single-stamp "
          "funding / shock-bar V-bounce / cascade fade / ratio z / lead-lag / blow-off); "
          "volume ideas 2/14 run (oslib.load has a volume column); ideas 8/12 execute on ETH")

    ctx = {"btc": None, "eth": None, "fund": {}, "fund_start": {}}
    for a in ("btc", "eth"):
        df1 = oslib.load(a, "1h")
        ctx[a] = {"df": df1, "1h": base_of(df1, H1),
                  "4h": base_of(_complete(df1, H4, 6), H4),
                  "1d": base_of(_complete(df1, D1, 24), D1)}
        try:
            f = oslib.funding(a)
            ctx["fund"][a] = f
            ctx["fund_start"][a] = pd.Timestamp(int(f["time"].min()), unit="ms",
                                                tz="UTC").strftime("%Y-%m-%d")
            print(f"  funding {a}: {ctx['fund_start'][a]} -> end | {len(f):,} stamps")
        except Exception as ex:
            ctx["fund"][a] = None
            print(f"  funding {a} unavailable: {ex}")

    print("\nbuilding oslib live engines (K8...D34) for the daily-R correlations ...")
    Eng, k8d, baskd = {}, {}, {}
    for a in ("btc", "eth"):
        Eng[a] = oslib.engines(ctx[a]["df"])
        k8d[a] = oslib._k8_for(ctx[a]["df"])
        b = None
        for nm in oslib.LIVE_ENGINES:
            d = oslib.daily_from_trades(Eng[a][nm])
            b = d if b is None else b.add(d, fill_value=0.0)
        baskd[a] = b
        print(f"  {a}: K8 {len(Eng[a]['K8'])} trades | basket daily series {len(baskd[a])} days")

    rows = {"btc": [], "eth": []}
    trades_keep = {}
    for spec in IDEAS:
        for a in ("btc", "eth"):
            spec["_asset"] = a
            rows[a].append(run_idea(spec, ctx, k8d, baskd))
        rb, re_ = rows["btc"][-1], rows["eth"][-1]
        rb["eth_pf"] = re_.get("pf") if re_.get("status") == "OK" else None
        if rb.get("status") == "OK":
            v, fails = verdict_of(rb)
            rb["verdict"], rb["fails"] = v, "; ".join(fails) or "-"
            if v == "KEEP":
                trades_keep[spec["num"]] = rb["trades"]
        else:
            rb["verdict"] = rb.get("status", "?")
            rb["fails"] = rb.get("note", "-")

    def disp_row(spec, r):
        d = {"idea": f"#{spec['num']:02d} {spec['title']}", "dir": spec["dirL"],
             "start": r.get("start", "-")}
        if r.get("status") == "OK":
            d.update(n=r["n"], win=f1(r["win"]), PF=f2(r["pf"]), avgR=f2(r["avgR"]),
                     ret=f1(r["ret"]), maxDD=f1(r["dd"]), gross=f2(r["gross"]),
                     H1=f"{f2(r['h1_pf'])}/{r['h1_n']}", H2=f"{f2(r['h2_pf'])}/{r['h2_n']}",
                     plc=f1(r["plc"]), flip=f2(r["flip_pf"]),
                     corrK8=f2(r["corr_k8"]), corrB=f2(r["corr_bask"]))
        else:
            d.update(n="-", win="-", PF="-", avgR="-", ret="-", maxDD="-", gross="-",
                     H1="-", H2="-", plc="-", flip="-", corrK8="-", corrB="-",
                     note=str(r.get("note", r.get("status", "")))[:70])
        return d

    for a in ("btc", "eth"):
        print(f"\n=== {a.upper()} | per-idea headline window (see 'start') | halves = PF/n ===")
        print(pd.DataFrame([disp_row(s, r) for s, r in zip(IDEAS, rows[a])]).to_string(index=False))

    print("\n=== VERDICTS (pre-declared KEEP rule, BTC-driven) ===")
    vrows = []
    for spec, r in zip(IDEAS, rows["btc"]):
        verdict = r.get("verdict", r.get("status", "?"))
        fails = r.get("fails", "-")
        eth_note = "n/a" if spec.get("btc_only") else f2(r.get("eth_pf"))
        print(f"  #{spec['num']:02d} {spec['title']}: {verdict}"
              + (f" | fails: {fails}" if fails not in (None, "-") else "")
              + (f" | ETH n/a (cross-asset idea, executed on ETH)" if spec.get("btc_only") and verdict == "KEEP" else ""))
        vrows.append({"idea": r["idea"], "verdict": verdict, "fails": fails,
                      "n": r.get("n"), "PF": f2(r.get("pf")),
                      "H1_PF": f2(r.get("h1_pf")), "H2_PF": f2(r.get("h2_pf")),
                      "plc_pct": f1(r.get("plc")), "flip_PF": f2(r.get("flip_pf")),
                      "ETH_PF": eth_note, "corr_basket": f2(r.get("corr_bask"))})

    print("\n=== pairwise trade-overlap % among KEEPs (interval overlap) ===")
    ks = sorted(trades_keep)
    if len(ks) >= 2:
        print("        " + " ".join(f"#{k:02d} " for k in ks))
        for a in ks:
            cells = []
            for b in ks:
                cells.append("  -- " if a == b else f"{overlap_pct(trades_keep[a], trades_keep[b]):5.1f}")
            print(f"  #{a:02d}  " + " ".join(cells))
    else:
        print(f"  fewer than 2 KEEPs ({len(ks)}) - no overlap matrix")

    try:
        oslib.OUT_DIR.mkdir(parents=True, exist_ok=True)
        pd.DataFrame([{k: v for k, v in r.items() if k != "trades"} for r in rows["btc"]]).to_csv(
            oslib.OUT_DIR / "batch14_btc.csv", index=False)
        pd.DataFrame([{k: v for k, v in r.items() if k != "trades"} for r in rows["eth"]]).to_csv(
            oslib.OUT_DIR / "batch14_eth.csv", index=False)
        pd.DataFrame(vrows).to_csv(oslib.OUT_DIR / "batch14_verdict.csv", index=False)
        print(f"\nWrote batch14_btc.csv, batch14_eth.csv, batch14_verdict.csv -> {oslib.OUT_DIR}")
    except Exception as ex:
        print(f"CSV write skipped: {ex}")


main()
