# ===== SPECIALISTS BATCH 2 — MARKET-STATE ENGINE (COIL / QUAKE / RIDE / EXHAUST / CHOP) + gated systems + ETH check — paste this WHOLE cell into ONE Colab cell =====
# (or:  !wget -q -O specialists_batch2.py https://osom-boba.pages.dev/colab/specialists_batch2.py   then   %run specialists_batch2.py)
#
# PART A  Market-state engine. Every CLOSED UTC day gets one state (pre-declared rules, first match wins):
#   QUAKE   "earthquake -> tsunami coming": a shock day in the last 3 days (incl. today):
#           true range >= 2.5x ATR20 (prior days), OR range >= 1.8x ATR20 with volume z-score >= 2.5,
#           OR a single wick >= 1.5x ATR20. Direction = colour of the latest shock day.
#   EXHAUST "get out": a strong run (close moved >= 5x ATR20 over 15 days, seen in the last 3 days) AND one of:
#           stretch >= 3.5x ATR20 from SMA20 | blow-off wick against the run (wick >= 50% of a >= 1.5x ATR day) |
#           range contraction after expansion (3-day mean TR < 0.5x the 10 days before) |
#           BTC only, 2020+: 7-day funding z-score >= +2 after an up-run (<= -2 after a down-run).
#           Direction = direction of the run being exhausted (EXHAUST-up = get out of longs).
#   RIDE    "ride it, don't close early": 10-day efficiency ratio >= 0.40, ATR14 above its value 5 days ago,
#           close on the trend side of SMA20, and a close beyond the prior 20-day box within the last 5 days.
#   COIL    "too quiet, expansion coming, stay flat": >= 3 of 4 compression tests vs the past year
#           [ATR14% pct <= 25, 7-day range pct <= 20, Bollinger width pct <= 20, 7d/90d volume <= 0.8]
#           AND 10-day efficiency < 0.35.
#   CHOP    everything else.
#   Scored HONESTLY on what came NEXT: forward 1/3/7-day |move| and 7d realised vol vs the all-days baseline
#   ("after COIL the next 7d move is X x normal"), forward 7d range vs the past 7d range (expansion), direction hit
#   rates, MFE/MAE in ATR, and how K8 / V7 / S5 / B1 trades entered in each state did. Placebo: 200 circular shifts
#   of the state labels (keeps clustering, breaks timing) -> a lift is REAL only if it sits outside the placebo 5-95% band.
# PART B  Use the states: K8 gated (entries only in RIDE same-direction / QUAKE / fresh breakout), K8 gated+flat
#   (also exits when the state turns CHOP or COIL), K8-ride (plain entries; RIDE blocks the opposite-flip exit,
#   EXHAUST against the trade exits). S5 and B1 gated to COIL/QUAKE/RIDE. Overlay basket K8 + S5 + B1 + V7
#   (each trade 1% risk of its own sleeve, basket = sum of sleeve daily returns), ungated vs gated.
# PART C  ETH check (same settings, no retune): S5, B1, K8, K8-gated (+ gated S5/B1). ETH has no funding input.
# Same costs/rules as batch 1: signal at a closed bar -> next 1h open, 0.07% fee + 0.05% slip per side, stops on 1h
# path, stop first on same-hour clash, 1% risk per trade, 1x notional cap per system.
import os, io, gzip, time, warnings, math
from pathlib import Path
from urllib.request import urlopen, Request
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore")
pd.set_option("display.width", 230); pd.set_option("display.max_columns", 40); pd.set_option("display.max_rows", 300)

T0 = time.time()
H1 = 3_600_000; D1 = 24 * H1; H4 = 4 * H1; H12 = 12 * H1
FEE, SLIP = 0.0007, 0.0005
COST = FEE + SLIP
RISK = 0.01
MAX_NOTIONAL = 1.0
SITE = "https://osom-boba.pages.dev/colab/"
OUT_DIR = Path("/content") if Path("/content").exists() else Path(".")
BUCKETS = [("2013-16", "2013-01-01", "2017-01-01"), ("2017-20", "2017-01-01", "2021-01-01"),
           ("2021-23", "2021-01-01", "2024-01-01"), ("2024+", "2024-01-01", "2100-01-01"),
           ("2026", "2026-01-01", "2027-01-01")]
HEADLINE_START = "2017-01-01"
STATES = ["QUAKE", "EXHAUST", "RIDE", "COIL", "CHOP"]
SCODE = {s: i for i, s in enumerate(STATES)}
N_PLACEBO = 200
RNG = np.random.default_rng(20261117)

# ---------------------------------------------------------------------------------------------
# DATA
# ---------------------------------------------------------------------------------------------
def _fetch(url):
    with urlopen(Request(url, headers={"User-Agent": "Mozilla/5.0 (colab specialists)"}), timeout=120) as r:
        b = r.read()
    if url.endswith(".gz") and b[:2] == b"\x1f\x8b":
        b = gzip.decompress(b)
    return pd.read_csv(io.BytesIO(b))

def _norm(df):
    cols = {c.lower().strip(): c for c in df.columns}
    def pick(*names):
        for n in names:
            if n in cols: return cols[n]
        return None
    tc = pick("time", "timestamp_ms", "timestamp", "open_time", "open_time_utc", "date", "datetime", "unix", "ts")
    o, h, l, c = pick("open"), pick("high"), pick("low"), pick("close", "adj close", "price")
    v = pick("volume", "volume_btc", "vol", "volume btc", "volume_base", "volume usd", "volume_usd")
    if None in (tc, o, h, l, c): return None
    t = df[tc]
    if pd.api.types.is_numeric_dtype(t):
        t = pd.to_numeric(t).astype("float64")
        mx = t.max()
        ms = np.where(mx > 1e17, t / 1e6, np.where(mx > 1e14, t / 1e3, np.where(mx > 1e11, t, t * 1e3)))
        tms = ms.astype("int64")
    else:
        tms = (pd.to_datetime(t, utc=True, errors="coerce").astype("datetime64[ns, UTC]").astype("int64") // 1_000_000).values
    out = pd.DataFrame({"time": tms, "open": pd.to_numeric(df[o], errors="coerce"), "high": pd.to_numeric(df[h], errors="coerce"),
                        "low": pd.to_numeric(df[l], errors="coerce"), "close": pd.to_numeric(df[c], errors="coerce"),
                        "volume": pd.to_numeric(df[v], errors="coerce") if v else 0.0,
                        "source": df[cols["source"]].astype(str).values if "source" in cols else "csv"})
    out = out.dropna(subset=["time", "open", "high", "low", "close"])
    out = out[(out.high > 0) & (out.low > 0)].sort_values("time").drop_duplicates("time").reset_index(drop=True)
    out["volume"] = out["volume"].fillna(0.0)
    return out if len(out) > 100 else None

def _bar_ms(df):
    return int(pd.Series(np.diff(df["time"].values)).median())

def _starts_before(d, day):
    return d["time"].iloc[0] <= pd.Timestamp(day, tz="UTC").value // 1_000_000

def load_asset(kind):
    """kind 'btc' or 'eth'. 1h data required."""
    env = os.environ.get("OSOM_DATA_FILE" if kind == "btc" else "OSOM_ETH_FILE")
    if env: return _norm(pd.read_csv(env)), env
    cands = sorted(Path("/content").glob("*.csv*")) if Path("/content").exists() else []
    for p in [p for p in cands if f"{kind}_1h_full" in p.name] + \
             [p for p in [Path(f"/workspace/specdata/{kind}_1h_full.csv.gz")] if p.exists()]:
        d = _norm(pd.read_csv(p))
        if d is not None: return d, str(p)
    def is_mine(p):
        n = p.name.lower()
        if "funding" in n or "summary" in n or "daily" in n: return False
        return ("eth" in n) if kind == "eth" else ("eth" not in n)
    short = []
    for p in cands:
        if not is_mine(p) or f"{kind}_1h_full" in p.name: continue
        try: d = _norm(pd.read_csv(p))
        except Exception: d = None
        if d is None or _bar_ms(d) > H1: continue
        if _starts_before(d, "2015-01-01" if kind == "btc" else "2018-01-01"): return d, str(p)
        short.append((p, d))
    url = SITE + f"{kind}_1h_full.csv.gz"
    try:
        print(f"Downloading {url} ...")
        d = _norm(_fetch(url))
        if d is not None: return d, url
    except Exception as e:
        print(f"  hosted {kind} failed: {e}")
    if short:
        p, d = max(short, key=lambda x: len(x[1])); print(f"  using shorter local file {p}"); return d, str(p)
    return None, None

def load_funding():
    cands = []
    if Path("/content").exists():
        cands = [p for p in sorted(Path("/content").glob("*.csv*")) if "funding" in p.name.lower() and "eth" not in p.name.lower()]
    frames = []
    for p in cands:
        try: frames.append(pd.read_csv(p))
        except Exception: pass
    try:
        frames.append(_fetch(SITE + "btc_funding_8h.csv"))
    except Exception as e:
        print(f"  hosted funding failed: {e}")
    out = []
    for f in frames:
        cl = {c.lower(): c for c in f.columns}
        tc = next((cl[c] for c in ("time", "timestamp_ms", "calc_time", "fundingtime", "funding_time") if c in cl), None)
        fc = next((cl[c] for c in ("funding", "funding_rate", "last_funding_rate", "fundingrate") if c in cl), None)
        if tc is None or fc is None: continue
        t = pd.to_numeric(f[tc], errors="coerce")
        out.append(pd.DataFrame({"time": (t // H1 * H1), "funding": pd.to_numeric(f[fc], errors="coerce")}).dropna())
    if not out: return None
    fd = pd.concat(out).drop_duplicates("time", keep="last").sort_values("time")
    return fd

def wilder(x, n):
    return pd.Series(x).ewm(alpha=1.0 / n, adjust=False).mean().values

def atr(h, l, c, n=14):
    pc = np.r_[np.nan, c[:-1]]
    tr = np.nanmax(np.vstack([h - l, np.abs(h - pc), np.abs(l - pc)]), axis=0)
    return wilder(tr, n)

def adx(h, l, c, n=14):
    up = np.r_[0, np.diff(h)]; dn = np.r_[0, -np.diff(l)]
    pdm = np.where((up > dn) & (up > 0), up, 0.0); mdm = np.where((dn > up) & (dn > 0), dn, 0.0)
    a = atr(h, l, c, n)
    pdi = 100 * wilder(pdm, n) / a; mdi = 100 * wilder(mdm, n) / a
    dx = 100 * np.abs(pdi - mdi) / np.maximum(pdi + mdi, 1e-12)
    return wilder(dx, n), pdi, mdi

# ---------------------------------------------------------------------------------------------
# asset context (module globals so the engine stays fast and simple)
# ---------------------------------------------------------------------------------------------
def set_asset(d):
    global df, N, O, Hh, L, C, V, T, BAR, BPD
    df = d.reset_index(drop=True); N = len(df); BAR = H1; BPD = 24
    O, Hh, L, C, V = (df[k].values.astype("float64") for k in ("open", "high", "low", "close", "volume"))
    T = df["time"].values.astype("int64")

def resample(period):
    g = T // period
    r = pd.DataFrame({"g": g, "open": O, "high": Hh, "low": L, "close": C, "volume": V})
    a = r.groupby("g").agg(open=("open", "first"), high=("high", "max"), low=("low", "min"), close=("close", "last"), volume=("volume", "sum"))
    a["last_i"] = pd.Series(np.arange(N)).groupby(g).max().values
    a["time"] = a.index.values * period
    return a.reset_index()

def to_base(htf, values, period):
    last_closed_g = (T + BAR) // period - 1
    return pd.Series(np.asarray(values, dtype="float64"), index=htf["g"].values).reindex(last_closed_g).values

def sig_to_base(htf, sig):
    out = np.zeros(N, dtype="int8"); idx = htf["last_i"].values; s = np.asarray(sig); m = s != 0
    out[idx[m]] = s[m]; return out

def at_base(htf, values):
    out = np.full(N, np.nan); out[htf["last_i"].values] = np.asarray(values, dtype="float64"); return out

# ---------------------------------------------------------------------------------------------
# ENGINE (same as batch 1 + soft/hard exits). soft exits (opposite flip, exitL/S) can be blocked by holdL/holdS
# (RIDE = don't close early); hard exits (hardL/S, stop, target, max_hold) always fire.
# ---------------------------------------------------------------------------------------------
def run(name, sig, stop_dist, tp_dist=None, max_hold=None, chand_atr=None, chand_mult=None,
        exitL=None, exitS=None, hardL=None, hardS=None, holdL=None, holdS=None, flip=True,
        trail_start=None, trail_drop=None, allow=None):
    eq = 1.0; pos = 0; frac = 0.0; ent = 0.0; stp = np.nan; tp = np.nan; ebar = 0; ext = 0.0; best = 0.0
    eq_ent = 1.0; t_in = 0; i_in = 0
    pend = 0; pend_stop = np.nan; pend_tp = np.nan; pend_exit = False
    curve = np.empty(N); trades = []
    def close_at(px, i):
        nonlocal eq, pos
        eq = eq_ent * (1 + frac * (pos * (px / ent - 1) - 2 * COST))
        trades.append((t_in, T[i], pos, eq / eq_ent - 1, i_in)); pos = 0
    for i in range(N):
        o, h, l, c = O[i], Hh[i], L[i], C[i]
        if pos != 0 and pend_exit: close_at(o, i)
        pend_exit = False
        if pend != 0 and pos == 0 and np.isfinite(pend_stop) and pend_stop > 0:
            pos = pend; ent = o; frac = min(MAX_NOTIONAL, RISK / (pend_stop / o))
            stp = o - pos * pend_stop; tp = o + pos * pend_tp if np.isfinite(pend_tp) else np.nan
            eq_ent = eq; t_in = T[i]; i_in = i; ebar = i; ext = o; best = o
        pend = 0
        if pos != 0:
            hit = None
            if pos > 0:
                if l <= stp: hit = min(o, stp)
                elif np.isfinite(tp) and h >= tp: hit = max(o, tp)
            else:
                if h >= stp: hit = max(o, stp)
                elif np.isfinite(tp) and l <= tp: hit = min(o, tp)
            if hit is not None: close_at(hit, i)
        s = sig[i]; ok = (allow is None) or bool(allow[i])
        if pos != 0:
            curve[i] = eq_ent * (1 + frac * (pos * (c / ent - 1) - COST))
            ext = max(ext, h) if pos > 0 else min(ext, l)
            if chand_atr is not None and np.isfinite(chand_atr[i]):
                ns = ext - pos * chand_mult * chand_atr[i]
                stp = max(stp, ns) if pos > 0 else min(stp, ns)
            best = max(best, c) if pos > 0 else min(best, c)
            hold = (pos > 0 and holdL is not None and bool(holdL[i])) or (pos < 0 and holdS is not None and bool(holdS[i]))
            soft = (pos > 0 and exitL is not None and bool(exitL[i])) or (pos < 0 and exitS is not None and bool(exitS[i]))
            soft |= (flip and s == -pos)
            hard = (max_hold is not None and i - ebar >= max_hold)
            hard |= (pos > 0 and hardL is not None and bool(hardL[i])) or (pos < 0 and hardS is not None and bool(hardS[i]))
            if trail_start is not None and pos * (best / ent - 1) >= trail_start and abs(best - c) / best >= trail_drop \
                    and pos * (c - best) < 0:
                hard = True
            ex = hard or (soft and not hold)
            if ex and flip and s == -pos and ok:
                pend = s; pend_stop = stop_dist[i]; pend_tp = tp_dist[i] if tp_dist is not None else np.nan
            pend_exit = ex
        else:
            curve[i] = eq
            if s != 0 and ok:
                pend = s; pend_stop = stop_dist[i]; pend_tp = tp_dist[i] if tp_dist is not None else np.nan
    if pos != 0:
        close_at(C[-1], N - 1); curve[-1] = eq
    return {"name": name, "curve": curve, "trades": pd.DataFrame(trades, columns=["t_in", "t_out", "side", "ret", "i_in"])}

def ms(s): return pd.Timestamp(s).value // 1_000_000

def stats(res, a=None, b=None):
    tr = res["trades"]; cv = res["curve"]
    a_ms = ms(a) if a else T[0]; b_ms = ms(b) if b else T[-1] + 1
    t = tr[(tr.t_out >= a_ms) & (tr.t_out < b_ms)]
    m = (T >= a_ms) & (T < b_ms)
    if m.sum() < 2: return dict(tr=0, win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan)
    seg = cv[m]
    seg = seg / seg[0] if seg[0] > 0 else seg
    # include the bar before the window as the base so the first bar's move counts
    first = np.argmax(m)
    if first > 0: seg = cv[m] / cv[first - 1]
    peak = np.maximum.accumulate(seg); dd = (seg / peak - 1).min()
    g = t.ret[t.ret > 0].sum(); ls = -t.ret[t.ret < 0].sum()
    return dict(tr=len(t), win=100 * (t.ret > 0).mean() if len(t) else np.nan,
                pf=(g / ls if ls > 0 else (np.inf if g > 0 else np.nan)), ret=100 * (seg[-1] - 1), dd=100 * dd)

def daily_ret(res):
    cv = pd.Series(res["curve"], index=T // D1)
    d = cv.groupby(level=0).last()
    return d.pct_change().fillna(0.0)

def fmt(x, nd=1):
    return "-" if x is None or (isinstance(x, float) and not np.isfinite(x)) else f"{x:.{nd}f}"

def period_row(r, label=None):
    h = stats(r, HEADLINE_START)
    row = {"tr17+": h["tr"], "win%": fmt(h["win"], 0), "PF17+": fmt(h["pf"], 2), "ret17+": fmt(h["ret"]), "dd17+": fmt(h["dd"])}
    for b, a_, z in BUCKETS:
        st = stats(r, a_, z); row[b] = f"{fmt(st['ret'])}/{fmt(st['dd'])}/{st['tr']}/{fmt(st['pf'],2)}"
    return row

# ---------------------------------------------------------------------------------------------
# indicators / systems for one asset
# ---------------------------------------------------------------------------------------------
def build_day(fund=None):
    D = resample(D1); D["dt"] = pd.to_datetime(D["time"], unit="ms"); D["year"] = D.dt.dt.year
    D["atr"] = atr(D.high.values, D.low.values, D.close.values, 20)
    D["atr14"] = atr(D.high.values, D.low.values, D.close.values, 14)
    if fund is not None:
        f = fund.copy(); f["g"] = f["time"] // D1
        fd = f.groupby("g").funding.sum()
        s7 = fd.rolling(7, min_periods=5).sum()
        z = (s7 - s7.rolling(90, min_periods=60).mean()) / s7.rolling(90, min_periods=60).std()
        D["fz"] = z.reindex(D["g"].values).values
    else:
        D["fz"] = np.nan
    return D

def market_states(D):
    h, l, c, o, v = D.high.values, D.low.values, D.close.values, D.open.values, D.volume.values
    n = len(D)
    a20p = pd.Series(D["atr"]).shift(1).values; a14 = D["atr14"].values
    pc = np.r_[np.nan, c[:-1]]
    tr = np.nanmax(np.vstack([h - l, np.abs(h - pc), np.abs(l - pc)]), axis=0)
    rk = lambda x: pd.Series(x).rolling(365, min_periods=200).rank(pct=True).values
    atrp_pct = rk(a14 / c)
    rng7_pct = rk((pd.Series(h).rolling(7).max() - pd.Series(l).rolling(7).min()).values / c)
    sma20 = pd.Series(c).rolling(20).mean().values
    bbw_pct = rk(pd.Series(c).rolling(20).std().values / sma20)
    er10 = (np.abs(pd.Series(c).diff(10)) / pd.Series(c).diff().abs().rolling(10).sum()).values
    lv = pd.Series(np.log(np.maximum(v, 1e-9)))
    vz = ((lv - lv.rolling(60, min_periods=30).mean().shift(1)) / lv.rolling(60, min_periods=30).std().shift(1)).values
    vz = np.where(v > 0, vz, np.nan)
    voldry = (pd.Series(v).rolling(7).mean() / pd.Series(v).rolling(90, min_periods=60).mean()).values
    wick_up = h - np.maximum(o, c); wick_dn = np.minimum(o, c) - l
    # QUAKE
    shock = (tr >= 2.5 * a20p) | ((tr >= 1.8 * a20p) & (vz >= 2.5)) | (np.maximum(wick_up, wick_dn) >= 1.5 * a20p)
    sdir = np.sign(c - o); sdir = np.where(sdir == 0, np.sign(c - pc), sdir)
    quake = np.zeros(n, bool); qdir = np.zeros(n)
    last = -99; ld = 0
    for i in range(n):
        if shock[i]: last, ld = i, sdir[i]
        if i - last <= 2: quake[i] = True; qdir[i] = ld
    # RIDE
    hi20 = pd.Series(h).rolling(20).max().shift(1).values; lo20 = pd.Series(l).rolling(20).min().shift(1).values
    brk_up5 = pd.Series(c > hi20).rolling(5).max().fillna(0).values > 0
    brk_dn5 = pd.Series(c < lo20).rolling(5).max().fillna(0).values > 0
    a_up = a14 > np.r_[np.full(5, np.nan), a14[:-5]]
    ride_up = (er10 >= 0.40) & a_up & (c > sma20) & brk_up5
    ride_dn = (er10 >= 0.40) & a_up & (c < sma20) & brk_dn5
    # EXHAUST
    run15 = c - np.r_[np.full(15, np.nan), c[:-15]]
    upr = pd.Series(run15 >= 5 * a20p).rolling(3).max().fillna(0).values > 0
    dnr = pd.Series(run15 <= -5 * a20p).rolling(3).max().fillna(0).values > 0
    rng = h - l
    tr3 = pd.Series(tr).rolling(3).mean().values; tr10p = pd.Series(tr).shift(3).rolling(10).mean().values
    contr = tr3 < 0.5 * tr10p
    fz = D["fz"].values
    ex_up = upr & (((c - sma20) >= 3.5 * a20p) | ((wick_up >= 0.5 * rng) & (rng >= 1.5 * a20p)) | contr | (fz >= 2))
    ex_dn = dnr & (((sma20 - c) >= 3.5 * a20p) | ((wick_dn >= 0.5 * rng) & (rng >= 1.5 * a20p)) | contr | (fz <= -2))
    # COIL
    cnt = (atrp_pct <= 0.25).astype(int) + (rng7_pct <= 0.20).astype(int) + (bbw_pct <= 0.20).astype(int) + (voldry <= 0.8).astype(int)
    coil = (cnt >= 3) & (er10 < 0.35)
    st = np.full(n, "CHOP", dtype=object); sd = np.zeros(n)
    st[coil] = "COIL"
    st[ride_up | ride_dn] = "RIDE"; sd[ride_up] = 1; sd[ride_dn & ~ride_up] = -1
    exm = ex_up | ex_dn
    st[exm] = "EXHAUST"; sd[ex_up] = 1; sd[ex_dn & ~ex_up] = -1
    st[quake] = "QUAKE"; sd[quake] = qdir[quake]
    warm = ~np.isfinite(atrp_pct) | ~np.isfinite(a20p)
    st[warm] = "WARMUP"; sd[warm] = 0
    rpct = pd.Series((hi20 - lo20) / pc).rolling(365, min_periods=200).rank(pct=True).values
    brk = (rpct <= 0.30) & ((c > hi20) | (c < lo20))
    brk3 = brk | np.r_[False, brk[:-1]] | np.r_[False, False, brk[:-2]]
    D["state"] = st; D["sdir"] = sd; D["brk3"] = brk3
    return D

def k8_system(D):
    lp = np.log(C); g12 = T // H12; last_of_g = np.r_[g12[1:] != g12[:-1], True]
    q = 1e-4; lv, sl = lp[0], 0.0; p00, p01, p11 = 1e-2, 0.0, 1e-2
    innov = []; Rv = 1e-3; slope_tmp = np.zeros(N)
    for i in range(N):
        lv_p = lv + sl; sl_p = sl
        a00 = p00 + 2 * p01 + p11 + q; a01 = p01 + p11; a11 = p11 + q
        S = a00 + Rv; v = lp[i] - lv_p; lim = 3 * math.sqrt(S); vc = max(-lim, min(lim, v))
        k0 = a00 / S; k1 = a01 / S
        n_lv = lv_p + k0 * vc; n_sl = sl_p + k1 * vc; slope_tmp[i] = n_sl
        if last_of_g[i]:
            lv, sl = n_lv, n_sl; p00, p01, p11 = (1 - k0) * a00, (1 - k0) * a01, a11 - k1 * a01
            innov.append(v * v)
            if len(innov) > 100: innov.pop(0)
            if len(innov) >= 10: Rv = max(float(np.mean(innov)), 1e-8)
    sgn = np.sign(slope_tmp)
    same8 = pd.Series(sgn).rolling(8).apply(lambda x: x[0] if np.all(x == x[0]) else 0, raw=True).fillna(0).values
    k8dir = pd.Series(np.where(same8 != 0, same8, np.nan)).ffill().fillna(0).values
    chg = np.r_[False, k8dir[1:] != k8dir[:-1]] & (k8dir != 0)
    k8sig = np.zeros(N, "int8"); k8sig[chg] = k8dir[chg].astype("int8")
    H12B = resample(H12); atr12 = to_base(H12B, atr(H12B.high.values, H12B.low.values, H12B.close.values, 14), H12)
    dadx, dpdi, dmdi = adx(D.high.values, D.low.values, D.close.values, 14)
    b_adx, b_pdi, b_mdi = (to_base(D, x, D1) for x in (dadx, dpdi, dmdi))
    blkL = (b_adx > 25) & (b_mdi > b_pdi); blkS = (b_adx > 25) & (b_pdi > b_mdi)
    return dict(dir=k8dir, sig=k8sig, chg=chg, stop=np.fmin(6 * atr12, 0.07 * C), blkL=blkL, blkS=blkS)

def k8_allow(K, sig):
    return ~((sig > 0) & K["blkL"]) & ~((sig < 0) & K["blkS"])

def v7_system(D):
    tp_ = (Hh + L + C) / 3; vv = np.maximum(V, 1e-9)
    vw = lambda n: (pd.Series(tp_ * vv).rolling(n).sum() / pd.Series(vv).rolling(n).sum()).values
    s24 = (C - vw(24)) / C; s168 = (C - vw(168)) / C
    p24 = pd.Series(s24).rolling(500, min_periods=300).rank(pct=True).values * 100
    p168 = pd.Series(s168).rolling(500, min_periods=300).rank(pct=True).values * 100
    p24p = np.r_[np.nan, p24[:-1]]
    lo168 = pd.Series(p168 <= 20).rolling(6).max().fillna(0).values > 0
    hi168 = pd.Series(p168 >= 80).rolling(6).max().fillna(0).values > 0
    longv = (p24p < 10) & (p24 >= 10) & lo168; shortv = (p24p > 90) & (p24 <= 90) & hi168
    hh = pd.Series(Hh).rolling(200).max().values; ll = pd.Series(L).rolling(200).min().values
    posr = (C - ll) / np.maximum(hh - ll, 1e-9); mid = (posr >= 0.35) & (posr <= 0.65)
    s200 = D.close.rolling(200).mean().values
    bear = to_base(D, ((D.close.values < s200) & (s200 < np.r_[np.full(20, np.nan), s200[:-20]])).astype(float), D1) == 1
    sig = np.zeros(N, "int8"); sig[longv & ~mid & ~bear] = 1; sig[shortv & ~mid] = -1
    return sig

def s5_b1(D):
    dh, dl, dc = D.high.values, D.low.values, D.close.values
    datr = D["atr"].values; datr_prior = pd.Series(datr).shift(1).values; b_datr = to_base(D, datr, D1)
    pc = np.r_[np.nan, dc[:-1]]
    tr = np.nanmax(np.vstack([dh - dl, np.abs(dh - pc), np.abs(dl - pc)]), axis=0)
    posc = (dc - dl) / np.maximum(dh - dl, 1e-9); big = tr >= 2.2 * datr_prior
    s = np.zeros(len(D), "int8"); s[big & (posc >= 0.85)] = 1; s[big & (posc <= 0.15)] = -1
    sd = np.maximum(np.where(s > 0, dc - dl, dh - dc), datr)
    S5 = dict(sig=sig_to_base(D, s), stop_dist=at_base(D, sd), chand_atr=b_datr, chand_mult=3.0, max_hold=15 * 24)
    n = 7
    rngb = (pd.Series(dh).rolling(n).max() - pd.Series(dl).rolling(n).min()) / pd.Series(dc)
    pct = rngb.rolling(365, min_periods=200).rank(pct=True).shift(1).values
    hi = pd.Series(dh).rolling(n).max().shift(1).values; lo = pd.Series(dl).rolling(n).min().shift(1).values
    s = np.zeros(len(D), "int8"); s[(pct <= 0.20) & (dc > hi)] = 1; s[(pct <= 0.20) & (dc < lo)] = -1
    sd = np.maximum(np.where(s > 0, dc - lo, hi - dc), datr)
    B1 = dict(sig=sig_to_base(D, s), stop_dist=at_base(D, sd), chand_atr=b_datr, chand_mult=3.0, max_hold=30 * 24)
    return S5, B1

def state_arrays(D):
    code = np.array([SCODE.get(s, -1) for s in D["state"].values], dtype=float)
    stb = to_base(D, code, D1); sdb = to_base(D, D["sdir"].values, D1)
    brkb = to_base(D, D["brk3"].values.astype(float), D1) == 1
    return stb, sdb, brkb

def systems(D, with_v7=True):
    """Builds plain + state-gated systems for the current asset. Returns dict of results."""
    R = {}
    stb, sdb, brkb = state_arrays(D)
    isS = lambda s: stb == SCODE[s]
    K = k8_system(D)
    plain_exitL, plain_exitS = K["dir"] < 0, K["dir"] > 0
    R["K8"] = run("K8", K["sig"], K["stop"], exitL=plain_exitL, exitS=plain_exitS, allow=k8_allow(K, K["sig"]))
    # gated: allowed when RIDE in K8's direction, any QUAKE, or a fresh low-vol box breakout (last 3 days)
    okg = (isS("RIDE") & (sdb == K["dir"])) | isS("QUAKE") | brkb
    opens = okg & ~np.r_[False, okg[:-1]]
    gsig = np.where(okg & (K["chg"] | opens) & (K["dir"] != 0), K["dir"], 0).astype("int8")
    R["K8-gate"] = run("K8-gate", gsig, K["stop"], exitL=plain_exitL, exitS=plain_exitS, allow=k8_allow(K, gsig))
    cc = isS("CHOP") | isS("COIL")
    R["K8-gate+flat"] = run("K8-gate+flat", gsig, K["stop"], exitL=plain_exitL, exitS=plain_exitS, hardL=cc, hardS=cc,
                            allow=k8_allow(K, gsig))
    rideL = isS("RIDE") & (sdb > 0); rideS = isS("RIDE") & (sdb < 0)
    exhL = isS("EXHAUST") & (sdb > 0); exhS = isS("EXHAUST") & (sdb < 0)
    R["K8-ride"] = run("K8-ride", K["sig"], K["stop"], exitL=plain_exitL, exitS=plain_exitS, holdL=rideL, holdS=rideS,
                       hardL=exhL, hardS=exhS, allow=k8_allow(K, K["sig"]))
    S5, B1 = s5_b1(D)
    gate_sb = isS("COIL") | isS("QUAKE") | isS("RIDE")
    for nm, P in (("S5", S5), ("B1", B1)):
        R[nm] = run(nm, P["sig"], P["stop_dist"], chand_atr=P["chand_atr"], chand_mult=3.0, max_hold=P["max_hold"])
        R[nm + "-gate"] = run(nm + "-gate", P["sig"], P["stop_dist"], chand_atr=P["chand_atr"], chand_mult=3.0,
                              max_hold=P["max_hold"], allow=gate_sb)
    if with_v7:
        R["V7"] = run("V7", v7_system(D), 0.10 * C, trail_start=0.20, trail_drop=0.15)
    return R, stb, sdb

# ---------------------------------------------------------------------------------------------
# LOAD
# ---------------------------------------------------------------------------------------------
btc, SRC = load_asset("btc")
if btc is None or _bar_ms(btc) > H1:
    raise SystemExit("Batch 2 needs BTC 1h data (hosted btc_1h_full.csv.gz). Daily-only data is not enough for K8/V7.")
FUND = load_funding()
print(f"\nBTC DATA: {SRC} | {len(btc):,} rows | {pd.to_datetime(btc.time.iloc[0], unit='ms')} -> {pd.to_datetime(btc.time.iloc[-1], unit='ms')} UTC")
btc["dt"] = pd.to_datetime(btc["time"], unit="ms")
print(btc.groupby("source").agg(first=("dt", "min"), last=("dt", "max"), rows=("time", "size")).sort_values("first").to_string())
if FUND is not None:
    print(f"BTC funding: {len(FUND):,} rows {pd.to_datetime(FUND.time.iloc[0], unit='ms').date()} -> {pd.to_datetime(FUND.time.iloc[-1], unit='ms').date()} (used only in EXHAUST, 2020+)")
else:
    print("BTC funding: not available -> EXHAUST funding trigger skipped")

set_asset(btc)
DAY = market_states(build_day(FUND))
t_b = time.time()
RES, STB, SDB = systems(DAY)
print(f"(BTC systems built in {time.time()-t_b:.0f}s)")

# ---------------------------------------------------------------------------------------------
# PART A — STATE MAP + HONEST FORWARD SCORING
# ---------------------------------------------------------------------------------------------
D = DAY[DAY.state != "WARMUP"].reset_index(drop=True)
c, h, l = D.close.values, D.high.values, D.low.values
nD = len(D)
def fwd(k):
    out = np.full(nD, np.nan); out[:-k] = c[k:] / c[:-k] - 1; return out
F1, F3, F7 = (np.abs(fwd(k)) for k in (1, 3, 7))
R7 = fwd(7)
lr = np.r_[np.nan, np.diff(np.log(c))]
FV7 = pd.Series(lr).rolling(7).std().shift(-7).values
fh7 = pd.Series(h[::-1]).rolling(7).max().values[::-1]; fh7 = np.r_[fh7[1:], np.nan]
fl7 = pd.Series(l[::-1]).rolling(7).min().values[::-1]; fl7 = np.r_[fl7[1:], np.nan]
FR7 = (fh7 - fl7) / c
PR7 = (pd.Series(h).rolling(7).max().values - pd.Series(l).rolling(7).min().values) / c
EXP7 = FR7 / PR7
A14 = D["atr14"].values
MFE = np.where(D.sdir.values >= 0, (fh7 - c), (c - fl7)) / A14
MAE = np.where(D.sdir.values >= 0, (c - fl7), (fh7 - c)) / A14
ST = D.state.values; SD = D.sdir.values; YR = D.year.values
TMS = D.time.values

print("\n=== A1. STATE MAP — % of days per year ===")
ct = pd.crosstab(D.year, D.state, normalize="index").reindex(columns=STATES).fillna(0) * 100
ct["days"] = D.groupby("year").size()
print(ct.round(0).astype(int).to_string())

def lift_block(mask_period, label):
    rows = []
    base = {k: np.nanmean(x[mask_period]) for k, x in (("1d", F1), ("3d", F3), ("7d", F7), ("vol7", FV7), ("exp7", EXP7))}
    for s in STATES:
        m = mask_period & (ST == s)
        if m.sum() < 5:
            rows.append({"state": s, "days": int(m.sum())}); continue
        r = {"state": s, "days": int(m.sum())}
        for k, x in (("1d", F1), ("3d", F3), ("7d", F7), ("vol7", FV7), ("exp7", EXP7)):
            r[f"{k} x"] = round(np.nanmean(x[m]) / base[k], 2)
        dm = m & (SD != 0) & np.isfinite(R7)
        if dm.sum() >= 5:
            r["dir7 hit%"] = round(100 * np.mean(np.sign(R7[dm]) == SD[dm]), 0)
            r["MFE7 atr"] = round(np.nanmean(MFE[dm]), 2); r["MAE7 atr"] = round(np.nanmean(MAE[dm]), 2)
        rows.append(r)
    out = pd.DataFrame(rows).set_index("state")
    print(f"\n-- {label}: baseline |move| 1d {100*base['1d']:.2f}%  3d {100*base['3d']:.2f}%  7d {100*base['7d']:.2f}% ; "
          f"'x' = state mean / all-days mean in this period; exp7 = next-7d range / past-7d range")
    print(out.to_string())
    return out

print("\n=== A2. LIFT TABLE — what happened NEXT after each state (closed-day labels, no lookahead) ===")
print("dir7 hit% = % of days the next-7d move went the state's direction (QUAKE: shock colour, RIDE: trend, EXHAUST: the run;")
print("for EXHAUST a LOW hit% means it reversed = 'get out' worked). MFE/MAE = best/worst excursion next 7d in ATR14, in that direction.")
LIFT = {}
for b, a_, z in BUCKETS:
    m = (TMS >= ms(a_)) & (TMS < ms(z))
    if m.sum() > 50: LIFT[b] = lift_block(m, b)
mH = TMS >= ms(HEADLINE_START)
LIFT["2017+"] = lift_block(mH, "2017+ (headline)")

print("\n=== A3. PLACEBO — 200 circular shifts of the state labels (2017+). REAL = real lift outside the placebo 5-95% band ===")
pl = []
idxH = np.where(mH)[0]
for s in STATES:
    m = ST[idxH] == s
    if m.sum() < 10: continue
    for nm, x in (("7d |move|", F7[idxH]), ("exp7", EXP7[idxH]), ("vol7", FV7[idxH])):
        base = np.nanmean(x); real = np.nanmean(x[m]) / base
        sims = []
        for _ in range(N_PLACEBO):
            k = RNG.integers(60, len(m) - 60); sims.append(np.nanmean(x[np.roll(m, k)]) / base)
        lo, md, hi = np.percentile(sims, [5, 50, 95])
        pl.append({"state": s, "metric": nm, "real x": round(real, 2), "placebo 5%": round(lo, 2), "median": round(md, 2),
                   "95%": round(hi, 2), "verdict": "REAL" if (real < lo or real > hi) else "noise"})
    dm = (ST[idxH] == s) & (SD[idxH] != 0) & np.isfinite(R7[idxH])
    if dm.sum() >= 10:
        rr = R7[idxH]; sdh = SD[idxH]
        real = np.mean(np.sign(rr[dm]) == sdh[dm]) * 100
        sims = []
        for _ in range(N_PLACEBO):
            k = RNG.integers(60, len(dm) - 60); m2 = np.roll(dm, k); d2 = np.roll(sdh, k)
            sims.append(np.mean(np.sign(rr[m2]) == d2[m2]) * 100)
        lo, md, hi = np.percentile(sims, [5, 50, 95])
        pl.append({"state": s, "metric": "dir7 hit%", "real x": round(real, 1), "placebo 5%": round(lo, 1), "median": round(md, 1),
                   "95%": round(hi, 1), "verdict": "REAL" if (real < lo or real > hi) else "noise"})
PL = pd.DataFrame(pl); print(PL.to_string(index=False))

print("\n=== A4. PLAIN-ENGLISH LIFT (2017+) ===")
L17 = LIFT["2017+"]
for s in STATES:
    if s not in L17.index or "7d x" not in L17.columns or not np.isfinite(L17.loc[s].get("7d x", np.nan)): continue
    r = L17.loc[s]
    real = PL[(PL.state == s) & (PL.metric == "7d |move|")]
    tag = real.verdict.iloc[0] if len(real) else "?"
    extra = f", next-7d range vs past-7d {r['exp7 x']:.2f}x normal"
    if "dir7 hit%" in r and np.isfinite(r.get("dir7 hit%", np.nan)):
        extra += f", went the state's direction {r['dir7 hit%']:.0f}% of the time"
    print(f"  After {s:<7} the next-7d move is {r['7d x']:.2f}x normal ({tag}){extra}.  [{int(r['days'])} days]")

print("\n=== A5. TRADES BY ENTRY STATE (BTC 2017+, state at the signal bar) — trades / win% / avg % / sum % of equity ===")
rows = []
for nm in ("K8", "V7", "S5", "B1"):
    tr = RES[nm]["trades"]; tr = tr[tr.t_in >= ms(HEADLINE_START)]
    sidx = np.clip(tr.i_in.values - 1, 0, N - 1)
    codes = STB[sidx]
    r = {"system": nm}
    for s in STATES:
        t = tr.ret.values[codes == SCODE[s]]
        r[s] = f"{len(t)}/{fmt(100*np.mean(t>0) if len(t) else np.nan,0)}/{fmt(100*np.mean(t) if len(t) else np.nan,2)}/{fmt(100*np.sum(t) if len(t) else np.nan,1)}"
    rows.append(r)
print(pd.DataFrame(rows).set_index("system").to_string())

# ---------------------------------------------------------------------------------------------
# PART B — gated systems + overlay basket
# ---------------------------------------------------------------------------------------------
print("\n=== B1. BTC SYSTEMS, plain vs state-gated — ret% / maxDD% / trades / PF per period (1% risk, 1x cap) ===")
print(pd.DataFrame({k: period_row(v) for k, v in RES.items()}).T.to_string())

DR = {k: daily_ret(v) for k, v in RES.items()}
def basket(names):
    x = sum(DR[n] for n in names); return x
def curve_stats(dr, a=None, b=None):
    x = dr[(dr.index >= (ms(a) // D1 if a else -1)) & (dr.index < (ms(b) // D1 if b else 10**9))]
    if len(x) < 2: return np.nan, np.nan
    eq = (1 + x).cumprod(); dd = (eq / eq.cummax() - 1).min()
    return 100 * (eq.iloc[-1] - 1), 100 * dd
BASKETS = {"basket plain (K8+S5+B1+V7)": ["K8", "S5", "B1", "V7"],
           "basket gated (K8-gate+S5-gate+B1-gate+V7)": ["K8-gate", "S5-gate", "B1-gate", "V7"],
           "basket mixed (K8-gate+S5+B1+V7)": ["K8-gate", "S5", "B1", "V7"],
           "basket K8-ride (K8-ride+S5+B1+V7)": ["K8-ride", "S5", "B1", "V7"]}
base_kv = (DR["K8"] + DR["V7"]) / 2
idx = base_kv.index[base_kv.index >= ms(HEADLINE_START) // D1]
wk = idx // 7; bw = base_kv.reindex(idx).groupby(wk).sum(); losew = bw[bw < 0].index
rows = []
for nm, members in BASKETS.items():
    dr = basket(members); r = {"basket": nm}
    rt, dd = curve_stats(dr, HEADLINE_START); r["ret17+"] = fmt(rt); r["dd17+"] = fmt(dd); r["MAR"] = fmt(rt / abs(dd) if dd else np.nan, 1)
    for b, a_, z in BUCKETS:
        rt, dd = curve_stats(dr, a_, z); r[b] = f"{fmt(rt)}/{fmt(dd)}"
    sw = dr.reindex(idx).fillna(0).groupby(wk).sum()
    r["P&L K8V7-lose-wk%"] = fmt(100 * sw.reindex(losew).sum()); r["pos lose-wk%"] = fmt(100 * (sw.reindex(losew) > 0).mean(), 0)
    rows.append(r)
print(f"\n=== B2. OVERLAY BASKET (sum of sleeve daily returns, each trade 1% risk) — ret%/maxDD% per period; "
      f"K8+V7 losing weeks 2017+: {len(losew)} of {len(bw)} ===")
BK = pd.DataFrame(rows).set_index("basket"); print(BK.to_string())

print("\n=== B3. Per-system P&L in K8+V7 losing weeks (2017+) and correlation to K8+V7 ===")
rows = []
for nm, d in DR.items():
    dd_ = d.reindex(idx).fillna(0); sw = dd_.groupby(wk).sum()
    rows.append({"system": nm, "corrK8V7": round(dd_.corr(base_kv.reindex(idx)), 2), "P&L lose-wk%": round(100 * sw.reindex(losew).sum(), 1),
                 "pos lose-wk%": round(100 * (sw.reindex(losew) > 0).mean(), 0), "P&L other-wk%": round(100 * sw.drop(losew).sum(), 1)})
LW = pd.DataFrame(rows).set_index("system"); print(LW.to_string())

# ---------------------------------------------------------------------------------------------
# PART C — ETH, same settings
# ---------------------------------------------------------------------------------------------
ETH_RES = {}
eth, ESRC = load_asset("eth")
if eth is not None and _bar_ms(eth) <= H1:
    eth["dt"] = pd.to_datetime(eth["time"], unit="ms")
    print(f"\nETH DATA: {ESRC} | {len(eth):,} rows")
    print(eth.groupby("source").agg(first=("dt", "min"), last=("dt", "max"), rows=("time", "size")).sort_values("first").to_string())
    btc_ctx = (df, N, O, Hh, L, C, V, T)
    set_asset(eth)
    EDAY = market_states(build_day(None))
    ETH_RES, _, _ = systems(EDAY, with_v7=False)
    print("\n=== C. ETH (same settings, no retune) — ret% / maxDD% / trades / PF; ETH starts 2017-08 ===")
    print(pd.DataFrame({k: period_row(v) for k, v in ETH_RES.items()}).T.drop(columns=["2013-16"]).to_string())
    ETH_ST = {k: stats(v, HEADLINE_START) for k, v in ETH_RES.items()}
    df, N, O, Hh, L, C, V, T = btc_ctx
else:
    print("\nETH data not available -> Part C skipped")
    ETH_ST = {}

# ---------------------------------------------------------------------------------------------
# RANKED SUMMARY + VERDICTS (pre-declared)
#  Standalone KEEP: BTC PF17+ >= 1.3, >= 30 trades, positive in >= 3 of 4 blocks (13-16, 17-20, 21-23, 24+),
#                   ETH PF >= 1.1. MAYBE: PF17+ >= 1.1 and >= 2 of the other 3. else DROP.
#  Gate verdict (for a -gate / -ride variant vs its plain parent): HELPS if BTC 2017+ MAR (ret/|DD|) is higher AND
#                   MAR is higher in >= 2 of 3 blocks (17-20, 21-23, 24+) AND ETH return is not lower; else NO.
# ---------------------------------------------------------------------------------------------
def mar(r, a, b):
    s = stats(r, a, b); return s["ret"] / abs(s["dd"]) if s["dd"] and np.isfinite(s["dd"]) and s["dd"] != 0 else np.nan
rows = []
for nm, r in RES.items():
    h = stats(r, HEADLINE_START)
    blocks = [stats(r, a_, z)["ret"] for b, a_, z in BUCKETS[:4]]
    nblk = sum(1 for x in blocks if np.isfinite(x) and x > 0)
    e = ETH_ST.get(nm)
    epf = e["pf"] if e else np.nan
    t = [np.isfinite(h["pf"]) and h["pf"] >= 1.3, h["tr"] >= 30, nblk >= 3, np.isfinite(epf) and epf >= 1.1]
    v = "KEEP" if all(t) else ("MAYBE" if (np.isfinite(h["pf"]) and h["pf"] >= 1.1 and sum(t[1:]) >= 2) else "DROP")
    parent = nm.split("-")[0] if "-" in nm else None
    gv = ""
    if parent and parent in RES:
        m_new, m_old = mar(r, HEADLINE_START, None), mar(RES[parent], HEADLINE_START, None)
        nb = sum(1 for b, a_, z in BUCKETS[1:4] if np.nan_to_num(mar(r, a_, z), nan=-9) > np.nan_to_num(mar(RES[parent], a_, z), nan=-9))
        eth_ok = True
        if nm in ETH_ST and parent in ETH_ST:
            eth_ok = np.nan_to_num(ETH_ST[nm]["ret"], nan=-1e9) >= np.nan_to_num(ETH_ST[parent]["ret"], nan=-1e9)
        gv = "HELPS" if (np.nan_to_num(m_new, nan=-9) > np.nan_to_num(m_old, nan=-9) and nb >= 2 and eth_ok) else "NO"
    rows.append({"system": nm, "verdict": v, "gate vs plain": gv, "PF17+": round(h["pf"], 2) if np.isfinite(h["pf"]) else np.nan,
                 "ret17+%": round(h["ret"], 1), "dd17+%": round(h["dd"], 1), "MAR": round(mar(r, HEADLINE_START, None), 2),
                 "trades": h["tr"], "blocks+": f"{nblk}/4", "ETH PF": round(epf, 2) if np.isfinite(epf) else np.nan,
                 "ETH ret%": round(e["ret"], 1) if e else np.nan,
                 "lose-wk%": LW.loc[nm, "P&L lose-wk%"] if nm in LW.index else np.nan})
SM = pd.DataFrame(rows)
SM["k"] = SM.verdict.map({"KEEP": 0, "MAYBE": 1, "DROP": 2})
SM = SM.sort_values(["k", "MAR"], ascending=[True, False]).drop(columns="k").set_index("system")
print("\n=== RANKED SUMMARY (BTC 2017+ headline; ETH same settings) ===")
print(SM.to_string())
print("\nVERDICTS:")
for nm, r in SM.iterrows():
    g = f"; gate vs plain: {r['gate vs plain']}" if r["gate vs plain"] else ""
    print(f"  {nm:<13} {r['verdict']:<5} PF {r['PF17+']}, ret {r['ret17+%']}%, DD {r['dd17+%']}%, MAR {r['MAR']}, "
          f"ETH PF {r['ETH PF']}, K8+V7 losing weeks {r['lose-wk%']}%{g}")
st_ok = PL[PL.verdict == "REAL"]
print("\nSTATE VERDICTS (2017+, placebo-checked):")
for s in STATES:
    x = st_ok[st_ok.state == s]
    print(f"  {s:<7} " + ("; ".join(f"{m} {rx}x REAL" if 'hit' not in m else f"{m} {rx} REAL" for m, rx in zip(x.metric, x["real x"]))
                          if len(x) else "no lift beyond placebo -> do not trade on it alone"))
SM.to_csv(OUT_DIR / "specialists_batch2_summary.csv"); PL.to_csv(OUT_DIR / "specialists_batch2_placebo.csv", index=False)
print(f"\nWrote {OUT_DIR/'specialists_batch2_summary.csv'} and specialists_batch2_placebo.csv | total runtime {time.time()-T0:.0f}s")
