# ===== nearmiss.py - do past near-miss ideas GROW THE BASKET when added at small risk? =====
# Colab:  !wget -q -O nearmiss.py https://osom-boba.pages.dev/colab/nearmiss.py
#         %run nearmiss.py
# Box (synthetic smoke only):  python3 nearmiss.py --smoke
#
# Same conventions as tilt.py: hosted oslib, COST 0.12%/side, Binance 1h perp data + Binance funding,
# PnL = R * min(risk_weight, trade stop distance), equity compounds from 1.0 on exit-time PnL,
# maxOpen 4 across the whole basket (a new entry is skipped while 4 positions are open; candidates
# compete for the same slots), and cut30 on every unit (an engine's new entries pause for the week
# while its last 30 exited trades have PF < 1.0; reset each UTC Monday; n < 30 stays on).
# Live basket: K8 2%; COCO, B1G, S5 3%; V7, R0, C1, C2, MOM30, D34, Q3 1%.
#   (oslib.engines gives the first 10; Q3 = batch16 idea #3 with the live params W180 p10 arm10 N7
#    trail15 stop 2.0 ATR, via batch16.sim.)
#
# 1) DISCOVERY - re-runs every single-asset idea in batch16, batch17, batch15, batch14 (Batch14z file)
#    and batch13 (N1..N15, batch13c file) exactly as those scripts build them (their own functions),
#    BTC-traded trades only (the bot trades BTCUSDT), headline 2017+ by exit time.
#    NEAR-MISS = BTC n >= 60 (relaxed to >= 40 if fewer than 6 qualify), BTC PF >= 1.05, ETH PF >= 0.9
#    (or n/a), and not a live engine. Pinned regardless: B16#02 (4H squeeze), B16#18 (funding carry),
#    B13:N3 (crowded-long funding short) - the paper-tracked ones. Capped at the 18 with the most
#    expected R per year (trades/yr x (PF-1) x avg loss).
# 2) BASKET ADD - each near-miss is added to the live basket at 0.25%, 0.5% and 1% risk on BTC and ETH.
#    Reported: total return, CAGR, maxDD, MAR, MAR in 2017-20 and 2021-26, years 2020-2026 beating
#    the baseline (BTC, ETH), daily-PnL correlation with the baseline basket, trades/yr.
# 3) PLACEBO - random-entry runs with the same trade count, sides, holds and stop distances on BTC
#    1h bars (cost included), added at the same risk; percentile of the real basket MAR. 100 runs, only
#    for candidates that pass every other gate at some risk.
# 4) BEST COMBINED SET - greedy: add the passer (at its best risk) that raises BTC CAGR the most while
#    the set still passes the gates vs baseline; stop when nothing helps. Placebo on the final set.
# ADD_SMALL: MAR >= baseline in both halves, maxDD no more than 3 pts worse, beats baseline in >= 4/7
#   years on BTC and >= 3/7 on ETH, placebo >= 80.  Best risk = highest BTC CAGR among passing levels.
import os, sys, re, time, types, subprocess, traceback, heapq
from pathlib import Path

T0 = time.time()
BASE_URL = "https://osom-boba.pages.dev/colab/"
try:
    _HERE = Path(__file__).resolve().parent
except Exception:
    _HERE = Path.cwd()

def _download(name):
    here = Path.cwd() / name
    url = BASE_URL + name + "?nc=" + str(int(time.time()))
    tmp = Path(str(here) + ".tmp")
    try:
        try:
            subprocess.run(["wget", "-q", "-O", str(tmp), url], check=True)
        except Exception:
            from urllib.request import urlopen, Request
            tmp.write_bytes(urlopen(Request(url, headers={"User-Agent": "osom-nearmiss/1.0"}), timeout=120).read())
        if tmp.stat().st_size < 1000:
            raise RuntimeError("download too small")
        os.replace(str(tmp), str(here))
    except Exception as ex:
        if not here.exists():
            raise
        print(f"  could not refresh {name} ({type(ex).__name__}); using the local copy", flush=True)

def _need(name, refresh):
    if not refresh:
        for d in (Path.cwd(), _HERE):
            if (d / name).exists():
                if str(d) not in sys.path:
                    sys.path.insert(0, str(d))
                return d / name
        print(f"{name} missing -> downloading " + BASE_URL + name, flush=True)
    _download(name)
    if str(Path.cwd()) not in sys.path:
        sys.path.insert(0, str(Path.cwd()))
    return Path.cwd() / name

IN_COLAB_DIR = Path("/content").exists()
_need("oslib.py", IN_COLAB_DIR)
import numpy as np
import pandas as pd
import oslib
from oslib import load, funding, engines, in_colab, synthetic_1h, LIVE_RISK, COST, H1, H4, D1

assert abs(COST - 0.0012) < 1e-12, "Expected COST=0.0012"
print(f"nearmiss | oslib v{oslib.__version__} | cost {100*COST:.2f}%/side | live mix + Q3 | maxOpen 4 | cut30", flush=True)

NAN = np.nan
START = "2017-01-01"
SPLIT = "2021-01-01"
MAX_OPEN = 4
N_PLC = 100
SEED = 20261123
YEARS = list(range(2020, 2027))
RISKS = (0.0025, 0.005, 0.01)
MON0 = -3 * D1
W1MS = 7 * D1
N_MIN, N_MIN_RELAX = 60, 40
MAX_CAND = 18
PINNED = ("B16#02", "B16#18", "B13:N3")
LIVE_NAMES = ("B16#03",)   # Q3 is live (with N7 / stop 2.0); the batch16 default is the same idea
BASE_RISK = dict(LIVE_RISK)
BASE_RISK["Q3"] = 0.01
ROWS = []
FIND = []

def ms(s):
    return int(pd.Timestamp(s, tz="UTC").value // 1_000_000)

T_START, T_SPLIT, T_END = ms(START), ms(SPLIT), ms("2027-01-01")

def f2(x, nd=2):
    try:
        return "n/a" if x is None or not np.isfinite(x) else f"{x:.{nd}f}"
    except Exception:
        return "n/a"

def fr(x):
    return "   n/a" if x is None or not np.isfinite(x) else f"{100*x:7.1f}"

def rec(**kw):
    ROWS.append(kw)

def pf_of(R):
    R = np.asarray(R, dtype=float)
    R = R[np.isfinite(R)]
    if not len(R):
        return NAN
    pos, neg = R[R > 0].sum(), -R[R < 0].sum()
    return pos / neg if neg > 0 else (99.0 if pos > 0 else NAN)

def week_of(t):
    return (np.asarray(t, dtype="int64") - MON0) // W1MS

def week_start(w):
    return np.asarray(w, dtype="int64") * W1MS + MON0

# ---------------------------------------------------------------------------
# trades -> packed arrays (units carry their own risk weight)
# ---------------------------------------------------------------------------
def clean(trs):
    out = []
    for tr in trs or []:
        try:
            R, r = float(tr.get("R", NAN)), float(tr.get("risk", NAN))
            et, xt = int(tr.get("entry_time", 0)), int(tr.get("exit_time", 0))
        except Exception:
            continue
        if np.isfinite(R) and np.isfinite(r) and r > 0 and xt >= et > 0:
            out.append(dict(entry_time=et, exit_time=xt, R=R, risk=r, side=int(tr.get("side", 0) or 0)))
    out.sort(key=lambda d: (d["entry_time"], d["exit_time"]))
    return out

def pack(units):
    """units: list of (name, weight, trades)."""
    names = [u[0] for u in units]
    base = np.array([float(u[1]) for u in units], dtype=float)
    rows = []
    for k, (nm, w, trs) in enumerate(units):
        for tr in trs:
            if tr["entry_time"] >= T_START:
                rows.append((tr["entry_time"], tr["exit_time"], tr["R"], tr["risk"], k))
    if not rows:
        z = np.array([], dtype="int64"); e = np.array([], dtype=float)
        return dict(entry=z, exit=z, R=e, risk=e, unit=np.array([], dtype=int), week=z, names=names, base=base, n=0)
    rows.sort(key=lambda x: (x[0], names[x[4]]))
    entry, exit_, R, risk, unit = (np.array(x) for x in zip(*rows))
    return dict(entry=entry.astype("int64"), exit=exit_.astype("int64"), R=R.astype(float), risk=risk.astype(float),
                unit=unit.astype(int), week=week_of(entry), names=names, base=base, n=len(R))

def cut30_mult(P):
    U = len(P["names"])
    if P["n"] == 0:
        return np.ones((0, U)), np.array([], dtype="int64")
    W = np.unique(np.concatenate([week_of(P["exit"]), P["week"]]))
    M = np.ones((len(W), U), dtype=float)
    starts = week_start(W)
    for u in range(U):
        m = P["unit"] == u
        if m.sum() < 30:
            continue
        xt, R = P["exit"][m], P["R"][m]
        o = np.argsort(xt, kind="stable")
        xt, R = xt[o], R[o]
        idx = np.searchsorted(xt, starts, "left")
        for i, i1 in enumerate(idx):
            if i1 >= 30:
                sl = R[i1 - 30:i1]
                if pf_of(sl) < 1.0:
                    M[i, u] = 0.0
    return M, W

def apply_maxopen(entry, exit_, take, max_open=MAX_OPEN):
    kept = np.zeros(len(entry), dtype=bool)
    heap = []
    for i in range(len(entry)):
        if not take[i]:
            continue
        t = int(entry[i])
        while heap and heap[0] <= t:
            heapq.heappop(heap)
        if len(heap) < max_open:
            kept[i] = True
            heapq.heappush(heap, int(exit_[i]))
    return kept

def run_path(P, use_cut=True):
    if P["n"] == 0:
        return empty_stats()
    if use_cut:
        M, W = cut30_mult(P)
        wi = np.clip(np.searchsorted(W, P["week"]), 0, len(W) - 1)
        m = M[wi, P["unit"]]
    else:
        m = np.ones(P["n"])
    take = apply_maxopen(P["entry"], P["exit"], m > 0)
    pnl = np.where(take, P["R"] * np.minimum(P["base"][P["unit"]], P["risk"]), 0.0)
    pnl = np.where(np.isfinite(pnl), pnl, 0.0)
    st = stats_from(P["exit"][take], pnl[take])
    st["taken_by_unit"] = np.bincount(P["unit"][take], minlength=len(P["names"]))
    st["pnl_by_unit"] = np.bincount(P["unit"][take], weights=pnl[take], minlength=len(P["names"]))
    return st

def empty_stats():
    return dict(ret=NAN, cagr=NAN, dd=NAN, mar=NAN, pf=NAN, n=0, eq=1.0, daily=pd.Series(dtype=float),
                taken_by_unit=np.zeros(0), pnl_by_unit=np.zeros(0))

def stats_from(exit_t, pnl):
    if not len(exit_t):
        return empty_stats()
    day = (np.asarray(exit_t, dtype="int64") // D1) * D1
    s = pd.Series(np.asarray(pnl, dtype=float), index=day).groupby(level=0).sum().sort_index()
    r = s.to_numpy()
    eq = np.cumprod(1.0 + r)
    if not np.isfinite(eq).all() or (eq <= 0).any():
        return dict(ret=-1.0, cagr=-1.0, dd=-1.0, mar=NAN, pf=pf_of(pnl), n=int(len(pnl)), eq=0.0, daily=s)
    end = float(eq[-1])
    peak = np.maximum.accumulate(np.r_[1.0, eq])[1:]
    dd = float(min(0.0, (eq / peak - 1.0).min()))
    t0, t1 = int(s.index[0]), int(s.index[-1])
    years = max(1.0 / 365.25, (t1 - t0) / (365.25 * D1))
    cagr = float(end ** (1.0 / years) - 1.0) if end > 0 else -1.0
    mar = float(cagr / abs(dd)) if dd < 0 else NAN
    return dict(ret=end - 1.0, cagr=cagr, dd=dd, mar=mar, pf=pf_of(pnl), n=int(len(pnl)), eq=end, daily=s)

def window_stats(daily, t0, t1):
    if daily is None or not len(daily):
        return dict(ret=NAN, cagr=NAN, dd=NAN, mar=NAN, n=0)
    sl = daily[(daily.index >= t0) & (daily.index < t1)]
    if not len(sl):
        return dict(ret=NAN, cagr=NAN, dd=NAN, mar=NAN, n=0)
    st = stats_from(sl.index.to_numpy(), sl.to_numpy())
    return {k: st[k] for k in ("ret", "cagr", "dd", "mar", "n")}

def yearly_rets(daily):
    return {y: window_stats(daily, ms(f"{y}-01-01"), ms(f"{y+1}-01-01"))["ret"] for y in YEARS}

def beats_years(va, vb):
    hit = 0
    for y in YEARS:
        a, b = va.get(y, NAN), vb.get(y, NAN)
        if np.isfinite(a) and np.isfinite(b) and a > b:
            hit += 1
    return hit

def enrich(st, base_st):
    h1 = window_stats(st["daily"], T_START, T_SPLIT)
    h2 = window_stats(st["daily"], T_SPLIT, T_END)
    yrs = yearly_rets(st["daily"])
    byrs = yearly_rets(base_st["daily"]) if base_st is not None else {y: NAN for y in YEARS}
    return dict(st=st, h1=h1, h2=h2, yrs=yrs, beats=beats_years(yrs, byrs))

def gate_fails(b, e, bb, be):
    """b/e = enriched BTC/ETH with candidate, bb/be = baselines. Placebo handled separately."""
    fails = []
    def ge(x, y):
        return np.isfinite(x) and np.isfinite(y) and x >= y - 1e-12
    if not (ge(b["h1"]["mar"], bb["h1"]["mar"]) and ge(b["h2"]["mar"], bb["h2"]["mar"])):
        fails.append("halves")
    if not (np.isfinite(b["st"]["dd"]) and np.isfinite(bb["st"]["dd"]) and b["st"]["dd"] >= bb["st"]["dd"] - 0.03):
        fails.append("DD")
    if b["beats"] < 4:
        fails.append("yrsBTC")
    if e is None or e["beats"] < 3:
        fails.append("yrsETH")
    return fails

def daily_full(st_daily_or_trades, weight=1.0, is_trades=False):
    if is_trades:
        rows = [(tr["exit_time"] // D1 * D1, weight * tr["R"] * min(1.0, tr["risk"] / max(weight, 1e-12)))
                for tr in st_daily_or_trades if tr["exit_time"] >= T_START]
        if not rows:
            return pd.Series(dtype=float)
        return pd.DataFrame(rows, columns=["d", "p"]).groupby("d")["p"].sum()
    return st_daily_or_trades

def dcorr_full(a, b):
    if a is None or b is None or not len(a) or not len(b):
        return NAN
    lo = min(int(a.index.min()), int(b.index.min()))
    hi = max(int(a.index.max()), int(b.index.max()))
    idx = np.arange(lo, hi + D1, D1, dtype="int64")
    x, y = a.reindex(idx).fillna(0.0), b.reindex(idx).fillna(0.0)
    if x.std() <= 1e-12 or y.std() <= 1e-12:
        return NAN
    return float(x.corr(y))

# ---------------------------------------------------------------------------
# idea sources
# ---------------------------------------------------------------------------
def import_plain(fname, modname):
    _need(fname, IN_COLAB_DIR)
    return __import__(modname)

def import_exec(fname, modname):
    """Load a batch file whose last line calls main(): run everything except that call."""
    p = _need(fname, IN_COLAB_DIR)
    src = Path(p).read_text()
    src = re.sub(r"(?m)^main\(\)\s*$", "pass", src)
    src = re.sub(r"(?m)^if __name__ == .__main__.:\s*\n\s+main\(\)\s*$", "pass", src)
    mod = types.ModuleType(modname)
    mod.__file__ = str(p)
    sys.modules[modname] = mod
    exec(compile(src, str(p), "exec"), mod.__dict__)
    return mod

def src_b16(D):
    b16 = import_plain("batch16.py", "batch16")
    BT, ET = b16.Ctx("btc", D["btc"]["df"], D["btc"]["fund"]), b16.Ctx("eth", D["eth"]["df"], D["eth"]["fund"])
    D["_b16"] = (b16, BT, ET)
    out = {}
    for num, name, tfn, fn, kind, start in b16.IDEAS:
        key = f"B16#{num:02d}"
        try:
            tb = [t for t in b16.run_idea(fn, BT, ET, False, start)["trades"] if t.get("asset") == "btc"]
            if kind == "x":
                te = None
            else:
                te = [t for t in b16.run_idea(fn, ET, BT, False, start)["trades"] if t.get("asset") == "eth"]
            out[key] = dict(name=f"{name} ({tfn})", btc=clean(tb), eth=(clean(te) if te is not None else None),
                            start=start or START)
        except Exception as ex:
            print(f"    {key} ERROR {type(ex).__name__}: {ex}", flush=True)
    return out

def q3_trades(D, asset):
    b16, BT, ET = D["_b16"]
    A = BT if asset == "btc" else ET
    Dd = A.d; c = Dd["c"]
    ap = Dd["atr"] / c
    comp = b16.prank(ap, 180) <= 0.10
    armed = b16.rmax(comp.astype(float), 10) > 0
    hh, ll = b16.sh1(b16.rmax(Dd["h"], 7)), b16.sh1(b16.rmin(Dd["l"], 7))
    sig = np.where(armed & (c > hh), 1, np.where(armed & (c < ll), -1, 0))
    r = b16.sim(Dd, sig, stop_atr=2.0, lvlL=b16.rmin(Dd["l"], 15), lvlS=b16.rmax(Dd["h"], 15), maker=False)
    return clean(r["trades"])

def src_b17(D):
    b17 = import_plain("batch17.py", "batch17")
    Bb, Be = b17.Base(D["btc"]["df"]), b17.Base(D["eth"]["df"])
    out = {}
    for key, desc, fn in b17.IDEAS:
        if fn is None:
            continue
        try:
            out[f"B17:{key}"] = dict(name=desc, btc=clean(fn(Bb)), eth=clean(fn(Be)), start=START)
        except Exception as ex:
            print(f"    B17:{key} ERROR {type(ex).__name__}: {ex}", flush=True)
    return out

def src_b15(D):
    b15 = import_plain("batch15.py", "batch15")
    bd, ed = D["btc"]["df"], D["eth"]["df"]
    bf, ef = D["btc"]["fund"], D["eth"]["fund"]
    specs = [
        ("B15_01", "ExpiryPin", "2017-01-01", lambda d, f, o: b15.build_b15_01(d)),
        ("B15_02", "FundZ7d", "2019-01-01", lambda d, f, o: b15.build_b15_02(d, f)),
        ("B15_03", "PostShock", "2017-01-01", lambda d, f, o: b15.build_b15_03(d)),
        ("B15_04", "AsiaSweep", "2017-01-01", lambda d, f, o: b15.build_b15_04(d)),
        ("B15_05", "CorrDecoup", "2017-01-01", lambda d, f, o: b15.build_b15_05(d, o)),
        ("B15_06", "HiChopKC", "2017-01-01", lambda d, f, o: b15.build_b15_06(d)),
        ("B15_07", "TurnOfMonth", "2017-01-01", lambda d, f, o: b15.build_b15_07(d)),
        ("B15_08", "FundFlip", "2019-01-01", lambda d, f, o: b15.build_b15_08(d, f)),
        ("B15_09", "BlowoffShort", "2017-01-01", lambda d, f, o: b15.build_b15_09(d)),
        ("B15_10", "CrashLong", "2017-01-01", lambda d, f, o: b15.build_b15_10(d)),
        ("B15_11", "SunVacFade", "2017-01-01", lambda d, f, o: b15.build_b15_11(d)),
        ("B15_12", "RatioBB", "2017-01-01", lambda d, f, o: b15.build_b15_12(d, o)),
        ("B15_13", "Consec6Bar", "2017-01-01", lambda d, f, o: b15.build_b15_13(d)),
        ("B15_14", "VWAP48Fade", "2017-01-01", lambda d, f, o: b15.build_b15_14(d)),
        ("B15_15", "LiqNegFund", "2019-01-01", lambda d, f, o: b15.build_b15_15(d, f)),
    ]
    out = {}
    for key, nm, st, fn in specs:
        try:
            tb = [t for t in fn(bd, bf, ed) if t["exit_time"] >= ms(st)]
            te = [t for t in fn(ed, ef, bd) if t["exit_time"] >= ms(st)]
            out[key] = dict(name=nm, btc=clean(tb), eth=clean(te), start=st)
        except Exception as ex:
            print(f"    {key} ERROR {type(ex).__name__}: {ex}", flush=True)
    return out

def src_b14(D):
    b14 = import_exec("batch14z.py", "batch14z")
    ctx = {"btc": None, "eth": None, "fund": {}, "fund_start": {}}
    for a in ("btc", "eth"):
        df1 = D[a]["df"]
        ctx[a] = {"df": df1, "1h": b14.base_of(df1, H1), "4h": b14.base_of(b14._complete(df1, H4, 6), H4),
                  "1d": b14.base_of(b14._complete(df1, D1, 24), D1)}
        f = D[a]["fund"]
        ctx["fund"][a] = f
        ctx["fund_start"][a] = (pd.Timestamp(int(f["time"].min()), unit="ms", tz="UTC").strftime("%Y-%m-%d")
                                if f is not None and len(f) else None)
    out = {}
    for spec in b14.IDEAS:
        key = f"B14#{spec['num']:02d}"
        if spec.get("skip") or spec.get("btc_only") or spec.get("trade_ctx") not in (None, "btc"):
            continue
        try:
            res = {}
            for a in ("btc", "eth"):
                if spec.get("needs_fund") and ctx["fund"].get(a) is None:
                    res[a] = []
                    continue
                st = ctx["fund_start"].get(a) if spec["start"] == "fund" else spec["start"]
                sigs, _w = spec["fn"](ctx, a, flip=False)
                trs, _tk = b14.execute(sigs, ctx[a][spec["walk"]], key)
                trs = [oslib._std_trade(t, src=key) for t in trs]
                res[a] = [t for t in trs if st is None or t["exit_time"] >= ms(st)]
            st0 = ctx["fund_start"].get("btc") if spec["start"] == "fund" else spec["start"]
            out[key] = dict(name=spec["title"], btc=clean(res["btc"]), eth=clean(res["eth"]), start=st0 or START)
        except Exception as ex:
            print(f"    {key} ERROR {type(ex).__name__}: {ex}", flush=True)
    return out

def src_b13(D):
    b13 = import_exec("batch13c.py", "batch13c")
    P = {a: b13.prep(a, D[a]["df"], D[a]["fund"]) for a in ("btc", "eth")}
    r6 = {a: P[a]["f4"]["r6"] for a in ("btc", "eth")}
    fmaps = {a: P[a]["fmap"] for a in ("btc", "eth")}
    specs = {a: b13.build_specs(P[a], r6, fmaps) for a in ("btc", "eth")}
    def conv(arr, taken):
        out = []
        for row, tk in zip(arr, taken):
            t_in, t_out, gross, R, pnl, sd = row[:6]
            out.append(dict(entry_time=int(t_in), exit_time=int(t_out), R=float(R), risk=float(tk[1]), side=int(sd)))
        return out
    out = {}
    eth_by = {sp["id"]: sp for sp in specs["eth"]}
    for sp in specs["btc"]:
        key = f"B13:{sp['id']}"
        if not sp["ok"]:
            continue
        try:
            tr, tk = b13.run_seq(P["btc"], sp)
            te = None
            se = eth_by.get(sp["id"])
            if se is not None and se["ok"]:
                tre, tke = b13.run_seq(P["eth"], se)
                te = conv(tre, tke)
            out[key] = dict(name=sp["label"], btc=clean(conv(tr, tk)), eth=(clean(te) if te is not None else None),
                            start=START)
        except Exception as ex:
            print(f"    {key} ERROR {type(ex).__name__}: {ex}", flush=True)
    return out

SOURCES = (("batch16", src_b16), ("batch17", src_b17), ("batch15", src_b15), ("batch14z", src_b14),
           ("batch13c", src_b13))

# ---------------------------------------------------------------------------
# standalone idea stats (1R units, 2017+ by exit)
# ---------------------------------------------------------------------------
def solo(trs, start, end_ms):
    w = [t for t in (trs or []) if t["exit_time"] >= T_START]
    R = np.array([t["R"] for t in w], dtype=float)
    x = np.array([t["exit_time"] for t in w], dtype="int64")
    t0 = max(T_START, ms(start) if start else T_START)
    yrs = max(0.25, (end_ms - t0) / (365.25 * D1))
    loss = -R[R < 0].mean() if (R < 0).any() else NAN
    return dict(n=len(R), pf=pf_of(R), pf1=pf_of(R[x < T_SPLIT]), pf2=pf_of(R[x >= T_SPLIT]),
                n1=int((x < T_SPLIT).sum()), n2=int((x >= T_SPLIT).sum()), totR=float(R.sum()) if len(R) else 0.0,
                tpy=len(R) / yrs, avgR=float(R.mean()) if len(R) else NAN, loss=loss,
                stop=float(np.median([t["risk"] for t in w])) if w else NAN)

# ---------------------------------------------------------------------------
# placebo: random entries, same side / hold (1h bars) / stop distance, BTC 1h bars
# ---------------------------------------------------------------------------
def placebo_sets(trs, bars, rng, n_runs):
    t, o, h, l, c = bars
    n = len(t)
    i0 = int(np.searchsorted(t, T_START))
    runs = [[] for _ in range(n_runs)]
    for tr in trs:
        if tr["entry_time"] < T_START:
            continue
        hold = int(max(1, round((tr["exit_time"] - tr["entry_time"]) / H1)))
        hold = min(hold, max(1, n - i0 - 2))
        hi = max(i0 + 1, n - hold - 1)
        ei = rng.integers(i0, hi, size=n_runs)
        idx = np.minimum(ei[:, None] + np.arange(hold + 1)[None, :], n - 1)
        fill = o[ei]
        s = tr["side"] if tr["side"] in (1, -1) else 1
        risk = tr["risk"]
        stp = fill * (1.0 - s * risk)
        hit = (l[idx] <= stp[:, None]) if s > 0 else (h[idx] >= stp[:, None])
        anyh = hit.any(axis=1)
        first = np.where(anyh, hit.argmax(axis=1), hold)
        jj = idx[np.arange(n_runs), first]
        sx = np.minimum(stp, o[jj]) if s > 0 else np.maximum(stp, o[jj])
        ex = np.where(anyh, sx, c[jj])
        R = (s * (ex / fill - 1.0) - 2.0 * COST) / risk
        for k in range(n_runs):
            if np.isfinite(R[k]):
                runs[k].append(dict(entry_time=int(t[ei[k]]), exit_time=int(t[jj[k]]), R=float(R[k]), risk=risk, side=s))
    for k in range(n_runs):
        runs[k].sort(key=lambda d: (d["entry_time"], d["exit_time"]))
    return runs

def placebo_pct(base_units, adds, bars, real_mar, seed, n_runs=N_PLC):
    """adds: list of (name, weight, trades). Returns percentile of real MAR vs random-entry adds."""
    if not np.isfinite(real_mar):
        return NAN
    rng = np.random.default_rng(seed)
    sets = [placebo_sets(trs, bars, rng, n_runs) for _nm, _w, trs in adds]
    mars = []
    for k in range(n_runs):
        units = list(base_units) + [(nm, w, sets[j][k]) for j, (nm, w, _t) in enumerate(adds)]
        mars.append(run_path(pack(units))["mar"])
    mars = np.array([m for m in mars if np.isfinite(m)])
    if not len(mars):
        return NAN
    return 100.0 * float(np.mean(mars < real_mar))

# ---------------------------------------------------------------------------
HDR = (f"  {'idea':<10} {'risk':>5} {'n+':>5} {'ret%':>9} {'CAGR%':>7} {'maxDD%':>7} {'MAR':>5} {'MAR1':>5} "
       f"{'MAR2':>5} {'yrB':>4} {'ETHret%':>8} {'ETHdd%':>7} {'ETHMAR':>6} {'yrE':>4} {'corr':>5} {'tr/yr':>5} "
       f"{'plc':>4}  verdict")

def line(tag, risk, n_add, b, e, corr, tpy, plc, verd):
    return (f"  {tag:<10} {('base' if risk is None else f'{100*risk:.2f}'):>5} {n_add:>5} {fr(b['st']['ret']):>9} "
            f"{fr(b['st']['cagr']):>7} {fr(b['st']['dd']):>7} {f2(b['st']['mar']):>5} {f2(b['h1']['mar']):>5} "
            f"{f2(b['h2']['mar']):>5} {str(b['beats'])+'/7':>4} {fr(e['st']['ret']) if e else '   n/a':>8} "
            f"{fr(e['st']['dd']) if e else '   n/a':>7} {f2(e['st']['mar']) if e else 'n/a':>6} "
            f"{(str(e['beats'])+'/7') if e else 'n/a':>4} {f2(corr):>5} {f2(tpy,0):>5} {f2(plc,0):>4}  {verd}")

def eval_add(ctx, adds_b, adds_e):
    """adds_*: list of (name, weight, trades). Returns enriched BTC/ETH and the BTC taken count of adds."""
    ub = ctx["btc"]["units"] + adds_b
    stb = run_path(pack(ub))
    b = enrich(stb, ctx["btc"]["base_st"])
    nb = int(stb["taken_by_unit"][len(ctx["btc"]["units"]):].sum()) if len(stb["taken_by_unit"]) else 0
    e = None
    if adds_e is not None:
        ue = ctx["eth"]["units"] + adds_e
        e = enrich(run_path(pack(ue)), ctx["eth"]["base_st"])
    return b, e, nb

def main(smoke=False):
    global N_PLC, N_MIN, N_MIN_RELAX
    D = {}
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        n = int(os.environ.get("NM_SMOKE_N", str(24 * 1500)))
        b1 = synthetic_1h(n=n, seed=9, start="2016-09-01")
        e1 = synthetic_1h(n=n, seed=21, start="2016-09-01", px0=300.0)
        rng = np.random.default_rng(0)
        for a, df in (("btc", b1), ("eth", e1)):
            tt = df["time"].to_numpy()[::8]
            D[a] = dict(df=df, fund=pd.DataFrame({"time": tt, "funding": 0.0001 + rng.normal(0, 0.0002, len(tt))}))
        N_PLC = int(os.environ.get("NM_SMOKE_PLC", "8"))
        N_MIN, N_MIN_RELAX = 10, 5
    else:
        for a in ("btc", "eth"):
            df = load(a, "1h")
            try:
                fd = funding(a, "binance")
            except Exception as ex:
                print(f"  funding {a} failed ({type(ex).__name__}); funding ideas skipped", flush=True)
                fd = None
            D[a] = dict(df=df, fund=fd)
    end_ms = int(D["btc"]["df"]["time"].iloc[-1])

    # ---- 1) ideas
    print("\n=== 1) DISCOVERY: re-running past ideas (BTC-traded, 2017+) ===", flush=True)
    IDEAS = {}
    for nm, fn in SOURCES:
        t1 = time.time()
        try:
            got = fn(D)
            IDEAS.update(got)
            print(f"  {nm}: {len(got)} ideas ({time.time()-t1:.0f}s)", flush=True)
        except Exception as ex:
            print(f"  {nm} SOURCE ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=3)

    # ---- basket
    ctx = {}
    for a in ("btc", "eth"):
        print(f"  building {a.upper()} live basket ...", flush=True)
        eng = engines(D[a]["df"], fund=D[a]["fund"])
        units = [(nm, BASE_RISK.get(nm, 0.01), clean(trs)) for nm, trs in eng.items()]
        try:
            units.append(("Q3", BASE_RISK["Q3"], q3_trades(D, a)))
        except Exception as ex:
            print(f"    Q3 {a} ERROR {type(ex).__name__}: {ex} (basket runs without Q3)", flush=True)
        st = run_path(pack(units))
        st_static = run_path(pack(units), use_cut=False)
        ctx[a] = dict(units=units, base_st=st, base_en=enrich(st, st), bars=(
            D[a]["df"]["time"].to_numpy("int64"), D[a]["df"]["open"].to_numpy(float), D[a]["df"]["high"].to_numpy(float),
            D[a]["df"]["low"].to_numpy(float), D[a]["df"]["close"].to_numpy(float)))
        print("    " + " ".join(f"{u[0]} {sum(1 for t in u[2] if t['entry_time'] >= T_START)}" for u in units), flush=True)
        print(f"    baseline (cut30, maxOpen 4): ret {fr(st['ret']).strip()}% CAGR {fr(st['cagr']).strip()}% "
              f"maxDD {fr(st['dd']).strip()}% MAR {f2(st['mar'])} | without cut30: ret {fr(st_static['ret']).strip()}% "
              f"MAR {f2(st_static['mar'])}", flush=True)
    bb, be = ctx["btc"]["base_en"], ctx["eth"]["base_en"]
    base_daily = bb["st"]["daily"]
    FIND.append(f"Baseline BTC (live mix + Q3, cut30, maxOpen 4): ret {fr(bb['st']['ret']).strip()}% "
                f"CAGR {fr(bb['st']['cagr']).strip()}% maxDD {fr(bb['st']['dd']).strip()}% MAR {f2(bb['st']['mar'])}; "
                f"ETH ret {fr(be['st']['ret']).strip()}% MAR {f2(be['st']['mar'])}.")

    # ---- standalone table + near-miss screen
    print(f"\n  {'idea':<10} {'name':<44} {'n':>5} {'tr/yr':>5} {'PF':>5} {'PF17-20':>7} {'PF21-26':>7} "
          f"{'ETH PF':>6} {'ETH n':>5}  pick", flush=True)
    SOLO = {}
    for key in sorted(IDEAS):
        I = IDEAS[key]
        s = solo(I["btc"], I["start"], end_ms)
        se = solo(I["eth"], I["start"], end_ms) if I["eth"] is not None else None
        SOLO[key] = (s, se)

    def eligible(key, nmin):
        s, se = SOLO[key]
        if key in LIVE_NAMES:
            return False
        eth_ok = se is None or se["n"] < 10 or (np.isfinite(se["pf"]) and se["pf"] >= 0.9)
        return s["n"] >= nmin and np.isfinite(s["pf"]) and s["pf"] >= 1.05 and eth_ok
    pool = [k for k in SOLO if eligible(k, N_MIN)]
    nmin_used = N_MIN
    if len(pool) < 6:
        pool = [k for k in SOLO if eligible(k, N_MIN_RELAX)]
        nmin_used = N_MIN_RELAX
    def edge(k):
        s = SOLO[k][0]
        lo = s["loss"] if np.isfinite(s["loss"]) else 1.0
        return s["tpy"] * max(0.0, (s["pf"] if np.isfinite(s["pf"]) else 1.0) - 1.0) * lo
    pool.sort(key=edge, reverse=True)
    pool = pool[:MAX_CAND]
    for k in PINNED:
        if k in IDEAS and k not in pool:
            pool.append(k)
    for key in sorted(IDEAS):
        s, se = SOLO[key]
        pick = "LIVE" if key in LIVE_NAMES else ("CAND" + (" (pinned)" if key in PINNED else "") if key in pool else "")
        print(f"  {key:<10} {IDEAS[key]['name'][:44]:<44} {s['n']:>5} {f2(s['tpy'],0):>5} {f2(s['pf']):>5} "
              f"{f2(s['pf1']):>7} {f2(s['pf2']):>7} {f2(se['pf']) if se else 'n/a':>6} {se['n'] if se else 'n/a':>5}  {pick}",
              flush=True)
        rec(section="1", idea=key, name=IDEAS[key]["name"], n=s["n"], tpy=s["tpy"], pf=s["pf"], pf_17_20=s["pf1"],
            pf_21_26=s["pf2"], eth_pf=(se["pf"] if se else NAN), eth_n=(se["n"] if se else NAN),
            candidate=int(key in pool))
    print(f"  near-miss pool: {len(pool)} ideas (n >= {nmin_used}, PF >= 1.05, ETH PF >= 0.9 or n/a; "
          f"+ pinned {', '.join(PINNED)})  ({time.time()-T0:.0f}s)", flush=True)

    # ---- 2) basket add
    print("\n=== 2) ADD EACH NEAR-MISS TO THE LIVE BASKET (BTC headline; ETH basket for the ETH gate) ===", flush=True)
    print("  n+ = candidate trades actually taken (after cut30 / maxOpen 4). MAR1 = 2017-20, MAR2 = 2021-26.", flush=True)
    print(HDR, flush=True)
    print(line("BASELINE", None, 0, bb, be, NAN, NAN, NAN, "baseline"), flush=True)
    RES = {}
    for key in pool:
        I = IDEAS[key]
        s, se = SOLO[key]
        corr = dcorr_full(daily_full(I["btc"], 0.01, is_trades=True), base_daily)
        RES[key] = dict(levels={}, corr=corr, tpy=s["tpy"])
        for w in RISKS:
            try:
                b, e, nb = eval_add(ctx, [(key, w, I["btc"])], [(key, w, I["eth"])] if I["eth"] is not None else None)
                fails = gate_fails(b, e, bb, be)
                if I["eth"] is None and "yrsETH" in fails:
                    fails.remove("yrsETH")   # ETH test n/a for this idea
                RES[key]["levels"][w] = dict(b=b, e=e, nb=nb, fails=fails, plc=NAN)
            except Exception as ex:
                print(f"  {key} {w} ERROR {type(ex).__name__}: {ex}", flush=True)
                traceback.print_exc(limit=2)
        # best passing risk -> placebo
        ok = [w for w, L in RES[key]["levels"].items() if not L["fails"]]
        best = max(ok, key=lambda w: RES[key]["levels"][w]["b"]["st"]["cagr"]) if ok else None
        RES[key]["best"] = best
        if best is not None:
            L = RES[key]["levels"][best]
            L["plc"] = placebo_pct(ctx["btc"]["units"], [(key, best, I["btc"])], ctx["btc"]["bars"],
                                   L["b"]["st"]["mar"], SEED + sum(ord(ch) for ch in key))
            if not (np.isfinite(L["plc"]) and L["plc"] >= 80):
                L["fails"] = L["fails"] + ["placebo"]
        for w, L in RES[key]["levels"].items():
            if not L["fails"]:
                verd = "ADD_SMALL" if w == best else "pass, not best risk"
            else:
                verd = "NO (" + ",".join(L["fails"]) + ")"
            print(line(key, w, L["nb"], L["b"], L["e"], corr, s["tpy"], L["plc"], verd), flush=True)
            b, e = L["b"], L["e"]
            rec(section="2", idea=key, risk=w, n_taken=L["nb"], ret=b["st"]["ret"], cagr=b["st"]["cagr"], dd=b["st"]["dd"],
                mar=b["st"]["mar"], mar_17_20=b["h1"]["mar"], mar_21_26=b["h2"]["mar"], yrs_btc=b["beats"],
                eth_ret=(e["st"]["ret"] if e else NAN), eth_dd=(e["st"]["dd"] if e else NAN),
                eth_mar=(e["st"]["mar"] if e else NAN), yrs_eth=(e["beats"] if e else NAN), corr=corr,
                tpy=s["tpy"], placebo=L["plc"], verdict=verd)
        print(f"  ({time.time()-T0:.0f}s)", flush=True)

    passers = [k for k in pool if RES[k].get("best") is not None and not RES[k]["levels"][RES[k]["best"]]["fails"]]

    # ---- 3) best combined set
    print("\n=== 3) BEST COMBINED SET (greedy on BTC CAGR, each passer at its best risk) ===", flush=True)
    chosen = []
    combo = None
    if passers:
        cur_cagr = bb["st"]["cagr"]
        left = list(passers)
        while left:
            best_k, best_r = None, None
            for k in left:
                trial = chosen + [k]
                ab = [(x, RES[x]["best"], IDEAS[x]["btc"]) for x in trial]
                ae = [(x, RES[x]["best"], IDEAS[x]["eth"]) for x in trial if IDEAS[x]["eth"] is not None]
                b, e, nb = eval_add(ctx, ab, ae)
                if gate_fails(b, e, bb, be):
                    continue
                if b["st"]["cagr"] > cur_cagr + 1e-9 and (best_r is None or b["st"]["cagr"] > best_r[0]["st"]["cagr"]):
                    best_k, best_r = k, (b, e, nb)
            if best_k is None:
                break
            chosen.append(best_k)
            left.remove(best_k)
            cur_cagr = best_r[0]["st"]["cagr"]
            combo = best_r
            print(f"  + {best_k} at {100*RES[best_k]['best']:.2f}% -> BTC CAGR {fr(cur_cagr).strip()}% "
                  f"maxDD {fr(best_r[0]['st']['dd']).strip()}% MAR {f2(best_r[0]['st']['mar'])}", flush=True)
    combo_plc, combo_verd = NAN, "n/a"
    if combo is not None and len(chosen) >= 1:
        b, e, nb = combo
        ab = [(x, RES[x]["best"], IDEAS[x]["btc"]) for x in chosen]
        combo_plc = placebo_pct(ctx["btc"]["units"], ab, ctx["btc"]["bars"], b["st"]["mar"], SEED + 999)
        fails = gate_fails(b, e, bb, be) + ([] if (np.isfinite(combo_plc) and combo_plc >= 80) else ["placebo"])
        combo_verd = "ADD_SMALL" if not fails else "NO (" + ",".join(fails) + ")"
        cs = pd.Series(dtype=float)
        for x in chosen:
            cs = cs.add(daily_full(IDEAS[x]["btc"], RES[x]["best"], True), fill_value=0.0)
        corr = dcorr_full(cs, base_daily)
        tpy = sum(RES[x]["tpy"] for x in chosen)
        print(HDR, flush=True)
        print(line("BASELINE", None, 0, bb, be, NAN, NAN, NAN, "baseline"), flush=True)
        print(line("COMBO", None, nb, b, e, corr, tpy, combo_plc, combo_verd).replace(" base ", "  mix "), flush=True)
        print("  COMBO = " + " + ".join(f"{x} {100*RES[x]['best']:.2f}%" for x in chosen), flush=True)
        rec(section="3", idea="COMBO:" + "+".join(chosen), risk=NAN, n_taken=nb, ret=b["st"]["ret"], cagr=b["st"]["cagr"],
            dd=b["st"]["dd"], mar=b["st"]["mar"], mar_17_20=b["h1"]["mar"], mar_21_26=b["h2"]["mar"], yrs_btc=b["beats"],
            eth_ret=(e["st"]["ret"] if e else NAN), eth_mar=(e["st"]["mar"] if e else NAN),
            yrs_eth=(e["beats"] if e else NAN), corr=corr, tpy=tpy, placebo=combo_plc, verdict=combo_verd)
        FIND.append(f"Best combined set {' + '.join(chosen)}: BTC ret {fr(b['st']['ret']).strip()}% vs "
                    f"{fr(bb['st']['ret']).strip()}%, MAR {f2(b['st']['mar'])} vs {f2(bb['st']['mar'])}, maxDD "
                    f"{fr(b['st']['dd']).strip()}% vs {fr(bb['st']['dd']).strip()}%, placebo {f2(combo_plc,0)} -> {combo_verd}.")
    else:
        print("  no passers -> no combined set", flush=True)

    # ---- summary
    print("\n=== SUMMARY (best risk per idea; 0.50% shown when none passes) ===", flush=True)
    print(f"  {'idea':<10} {'name':<36} {'soloPF':>6} {'n':>5} {'tr/yr':>5} {'risk':>5} {'dRet%':>8} {'dCAGR':>6} "
          f"{'dDD':>6} {'dMAR':>6} {'yrB':>4} {'yrE':>4} {'corr':>5} {'plc':>4}  verdict", flush=True)
    for key in pool:
        s = SOLO[key][0]
        w = RES[key].get("best") or (0.005 if 0.005 in RES[key]["levels"] else None)
        if w is None:
            continue
        L = RES[key]["levels"][w]
        b, e = L["b"], L["e"]
        verd = "ADD_SMALL" if (RES[key].get("best") == w and not L["fails"]) else "NO (" + ",".join(L["fails"]) + ")"
        print(f"  {key:<10} {IDEAS[key]['name'][:36]:<36} {f2(s['pf']):>6} {s['n']:>5} {f2(s['tpy'],0):>5} "
              f"{100*w:>5.2f} {fr(b['st']['ret']-bb['st']['ret']):>8} {100*(b['st']['cagr']-bb['st']['cagr']):>6.1f} "
              f"{100*(b['st']['dd']-bb['st']['dd']):>6.1f} {f2(b['st']['mar']-bb['st']['mar']):>6} {str(b['beats'])+'/7':>4} "
              f"{(str(e['beats'])+'/7') if e else 'n/a':>4} {f2(RES[key]['corr']):>5} {f2(L['plc'],0):>4}  {verd}", flush=True)

    print("\n=== VERDICTS ===", flush=True)
    for key in pool:
        w = RES[key].get("best")
        if w is not None and not RES[key]["levels"][w]["fails"]:
            L = RES[key]["levels"][w]
            print(f"  {key}: ADD_SMALL at {100*w:.2f}% (BTC CAGR {fr(L['b']['st']['cagr']).strip()}% vs "
                  f"{fr(bb['st']['cagr']).strip()}%, maxDD {fr(L['b']['st']['dd']).strip()}%, placebo {f2(L['plc'],0)})", flush=True)
        else:
            L = RES[key]["levels"].get(w if w is not None else 0.005)
            why = ",".join(L["fails"]) if L else "error"
            print(f"  {key}: NO ({why})", flush=True)
    combo_txt = " + ".join(f"{x} {100*RES[x]['best']:.2f}%" for x in chosen)
    print(f"  COMBO: {combo_verd}" + (f" = {combo_txt}" if chosen else ""), flush=True)
    print("  ADD_SMALL: MAR >= baseline both halves, maxDD <= 3 pts worse, >= 4/7 years BTC, >= 3/7 ETH, placebo >= 80.", flush=True)

    print("\n=== FINDINGS ===", flush=True)
    FIND.append(f"{len(passers)} of {len(pool)} near-miss ideas pass ADD_SMALL: {', '.join(passers) if passers else 'none'}.")
    for f in FIND:
        print("  - " + f, flush=True)
    out_dir = Path("/content") if Path("/content").exists() else Path(".")
    out = out_dir / ("nearmiss_smoke.csv" if smoke else "nearmiss.csv")
    pd.DataFrame(ROWS).to_csv(out, index=False)
    print(f"\nSaved {out} ({len(ROWS)} rows). Total {time.time()-T0:.0f}s", flush=True)

if __name__ == "__main__":
    _smoke = ("--smoke" in sys.argv) or (not in_colab() and os.environ.get("OSLIB_ALLOW_REAL") != "1")
    main(smoke=_smoke)
