# ===== SPECIALISTS BATCH 4 — COMBINED BASKET (shared equity, risk caps, 1/2/5% risk) + STAGE-SEQUENCE DIRECTION (Wyckoff-style) — paste this WHOLE cell into ONE Colab cell =====
# (or:  !wget -q -O specialists_batch4.py https://osom-boba.pages.dev/colab/specialists_batch4.py   then   %run specialists_batch4.py)
#
# PART A  Sleeves (batch 1-3 definitions, unchanged): K8 plain | BRA = B oco-rearm (stop=other box side, 3xATR trail) |
#         B1G = B1-gate | S5 | (variants: BOCO = B oco no re-arm, STR = A straddle).
#         Baskets: each sleeve alone, K8+BRA, K8+BRA+B1G, K8+BRA+B1G+S5 ("ALL4"), ALL4 with BOCO or STR instead of BRA.
#         One SHARED account: each trade risks r% of equity at entry (size = r% / stop distance, notional cap 3x =
#         3x isolated), P&L booked at exit. "uncapped" = every trade taken; "capped" = max 4 open trades (so max
#         4r% open risk). Risk levels 1% / 2% / 5% (5% / M=4 = the earlier locked plan).
#         Dedupe: a BRA/BOCO/STR trade and a B1G trade in the SAME direction within 48h = same coil breakout ->
#         keep only the first. Liquidation check at 3x isolated (liq ~ 32.8% adverse move): largest stop distance,
#         worst realised adverse move, and peak margin use (sum of notional/3 vs equity; >100% = could not be opened).
#         Reports: ret, maxDD, MAR, monthly win%, worst month, longest DD (days), worst losing streak, P&L in K8+V7
#         losing weeks, sleeve correlation matrix, B1G-vs-bracket overlap.
# PART B  Stage sequence -> direction. For every COIL box (batch-3 box: 7-day high/low at the coil day; window 10 days),
#         pre-declared leans (+1 bull / -1 bear / 0 none), all from data closed before the lean is used:
#           R30 / R60 / R90   sign of the 30/60/90-day return before the box (momentum-coded)
#           SMA200            close above (+1) / below (-1) the 200-day SMA
#           DD1Y              within 10% of the 1-year high (+1) / more than 30% below it (-1)
#           CLV               coil-day close in the top 40% of the box (+1) / bottom 40% (-1)
#           VOLASYM           1h up-bar volume / down-bar volume inside the box > 1.1 (+1) / < 0.9 (-1)
#           FUND (BTC 2020+)  mean funding over the box days, z vs prior 90d: > +0.5 (+1) / < -0.5 (-1)
#           SWEEP             first side wicked in the window; if a 1h close is back inside within 24h -> lean the
#                             OTHER way (sweep low + reclaim = bull). Known only after the reclaim.
#           VOTE  (pre-declared Wyckoff view) = sign of [-R90, CLV, VOLASYM, -FUND, SWEEP]
#           VOTE0 (tradeable at the coil close) = sign of [-R90, CLV, VOLASYM, -FUND]
#         Outcome = side of the box the window-END close sits on (inside -> excluded); also shown: side of the FIRST
#         1h close outside the box. Momentum-coded hit% >= 55 = continuation works, <= 45 = reversal works.
#         REAL = outside the 5-95% band of 200 label shuffles AND same side of 55/45 in both blocks
#         (early = 2013-20 BTC / 2017-20 ETH, late = 2021+). Exact two-sided binomial p-values printed.
#         Trading test: BRA full bracket vs ONE-SIDED (only the VOTE0 side's stop-entry, no re-arm; VOTE0 = 0 -> skip)
#         vs TILT (full bracket, VOTE0-side trades at 1.5x size).
# Costs 0.07% fee + 0.05% slip per side; 1h path; stop first; next-open fills; closed data only.
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 * (px / ent - 1), rp)); 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; rp = pend_stop / o; frac = min(MAX_NOTIONAL, RISK / rp)
            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", "move", "risk"])}

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

# ---------------------------------------------------------------------------------------------
# BATCH 3 — COIL BOX machinery
# ---------------------------------------------------------------------------------------------
P0 = dict(N=7, M=10, K=12, x=0.25, k=1.5)
TCOLS = ["t_in", "t_out", "side", "ret", "kind", "move", "risk"]
MAX_HOLD = 30 * 24
STOPS = ["opp", "mid", "atr"]; EXITS = ["trail3", "tp1", "tp2", "tp3", "exh"]

def coil_setups(D, P, placebo=False, heights=None):
    st = D["state"].values; n = len(D); out = []; last = -10**9
    hi = D.high.values; lo = D.low.values; cl = D.close.values; at = D["atr"].values; li = D["last_i"].values
    N_, M_ = int(P["N"]), int(P["M"])
    for d in range(N_, n):
        if d - last < M_: continue
        ok = (st[d] == "COIL") if not placebo else (st[d] not in ("COIL", "WARMUP"))
        if not ok or not np.isfinite(at[d]): continue
        i0 = li[d] + 1
        if i0 >= N - 2: continue
        if placebo:
            hp = heights[RNG.integers(0, len(heights))]
            bh, bl = cl[d] * (1 + hp / 2), cl[d] * (1 - hp / 2)
        else:
            bh, bl = hi[d - N_ + 1:d + 1].max(), lo[d - N_ + 1:d + 1].min()
        out.append(dict(d=d, i0=i0, i1=min(N - 1, i0 + M_ * 24), bh=bh, bl=bl, A=at[d], t=T[i0]))
        last = d
    return out

def sim_leg(i0, side, entry, stop, tp=np.nan, trail=None, exh=None, fill_bar_stopentry=False, chand=None):
    """Walk 1h bars from i0 (entry bar). Returns (exit_i, exit_px, kind, frac, stop0)."""
    stop0 = stop; risk = abs(entry - stop) / entry
    if risk <= 0: return None
    frac = min(MAX_NOTIONAL, RISK / risk); ext = entry
    end = min(N - 1, i0 + MAX_HOLD)
    for i in range(i0, end + 1):
        o, h, l, c = O[i], Hh[i], L[i], C[i]
        first = (i == i0)
        if side > 0:
            if l <= stop:
                return i, (stop if first else min(o, stop)), ("stop" if stop == stop0 else "trail"), frac, stop0
            if np.isfinite(tp) and h >= tp and not (first and fill_bar_stopentry):
                return i, (tp if first else max(o, tp)), "tp", frac, stop0
        else:
            if h >= stop:
                return i, (stop if first else max(o, stop)), ("stop" if stop == stop0 else "trail"), frac, stop0
            if np.isfinite(tp) and l <= tp and not (first and fill_bar_stopentry):
                return i, (tp if first else min(o, tp)), "tp", frac, stop0
        if trail is not None and np.isfinite(chand[i]):
            ext = max(ext, h) if side > 0 else min(ext, l)
            ns = ext - side * trail * chand[i]
            stop = max(stop, ns) if side > 0 else min(stop, ns)
        if exh is not None and exh[i] and i + 1 <= N - 1:
            return i + 1, O[i + 1], "exh", frac, stop0
        if i == end:
            return i, c, "time", frac, stop0
    return end, C[end], "time", frac, stop0

def booked(i_in, i_out, side, entry, px, frac, tag="", stop0=np.nan):
    return (T[i_in], T[i_out], side, frac * (side * (px / entry - 1) - 2 * COST), tag, side * (px / entry - 1), abs(entry - stop0) / entry)

def exit_args(ex, box_h, side, entry, ctx):
    tp = np.nan; trail = None; exh = None
    if ex == "trail3": trail = 3.0
    elif ex in ("tp1", "tp2", "tp3"): tp = entry + side * int(ex[-1]) * box_h
    elif ex == "2box": tp = entry + side * 2 * box_h
    elif ex == "exh": exh = ctx["exhL"] if side > 0 else ctx["exhS"]
    return tp, trail, exh

def sys_straddle(S, stop_v, ex, ctx, P):
    tr = []; dbl = 0; n = 0
    for s in S:
        i0 = s["i0"]; e = O[i0]; bh, bl, A = s["bh"], s["bl"], s["A"]; H = bh - bl
        legs = []
        for side in (1, -1):
            if stop_v == "opp": stp = bl if side > 0 else bh
            elif stop_v == "mid": stp = e - side * H / 2
            else: stp = e - side * P["k"] * A
            if side * (e - stp) <= 0: stp = e - side * max(H / 2, 0.5 * A)
            tp, trail, exh = exit_args(ex, H, side, e, ctx)
            r = sim_leg(i0, side, e, stp, tp, trail, exh, chand=ctx["chand"])
            if r is None: continue
            j, px, kind, frac, s0 = r
            legs.append(booked(i0, j, side, e, px, frac, kind, s0))
        if len(legs) == 2:
            n += 1; dbl += int(legs[0][3] < 0 and legs[1][3] < 0)
        tr += legs
    return tr, (100 * dbl / n if n else np.nan)

def first_touch(i, bh, bl):
    up = Hh[i] >= bh; dn = L[i] <= bl
    if up and dn: return 1 if (bh - O[i]) <= (O[i] - bl) else -1
    return 1 if up else (-1 if dn else 0)

def sys_oco(S, stop_v, ex, ctx, P, rearm=False):
    tr = []; dbl = 0; n2 = 0
    for s in S:
        bh, bl, A = s["bh"], s["bl"], s["A"]; H = bh - bl; i = s["i0"]; i1 = s["i1"]
        side = 0
        while i <= i1:
            side = first_touch(i, bh, bl)
            if side: break
            i += 1
        if not side: continue
        res = []
        for attempt in range(2 if rearm else 1):
            e = max(O[i], bh) if side > 0 else min(O[i], bl)
            if attempt == 1: e = max(e_prev_px, bh) if side > 0 else min(e_prev_px, bl)
            if stop_v == "opp": stp = bl if side > 0 else bh
            elif stop_v == "mid": stp = (bh + bl) / 2
            else: stp = e - side * P["k"] * A
            if side * (e - stp) <= 0: stp = e - side * 0.5 * A
            tp, trail, exh = exit_args(ex, H, side, e, ctx)
            r = sim_leg(i, side, e, stp, tp, trail, exh, fill_bar_stopentry=True, chand=ctx["chand"])
            if r is None: break
            j, px, kind, frac, s0 = r
            res.append(booked(i, j, side, e, px, frac, kind, s0))
            if not (rearm and kind == "stop" and j <= i1): break
            # opposite stop-entry becomes live from the stop bar
            side = -side; k = j; e_prev_px = px; found = False
            while k <= i1:
                if (side > 0 and Hh[k] >= bh) or (side < 0 and L[k] <= bl): found = True; break
                k += 1
            if not found: break
            if k > j: e_prev_px = O[k]
            i = k
        if rearm and len(res) == 2:
            n2 += 1; dbl += int(res[0][3] < 0 and res[1][3] < 0)
        tr += res
    return tr, (100 * dbl / n2 if n2 else np.nan)

def sys_fade(S, ex, ctx, P):
    tr = []; K = int(round(P["K"])); x = P["x"]
    for s in S:
        bh, bl, A = s["bh"], s["bl"], s["A"]; H = bh - bl; i = s["i0"]; i1 = s["i1"]; b = -1; side = 0
        while i <= i1:
            if C[i] > bh or Hh[i] >= bh + x * A: side = 1; b = i; break
            if C[i] < bl or L[i] <= bl - x * A: side = -1; b = i; break
            i += 1
        if b < 0: continue
        ext = Hh[b] if side > 0 else L[b]
        for j in range(b, min(b + K, N - 2) + 1):
            ext = max(ext, Hh[j]) if side > 0 else min(ext, L[j])
            if bl < C[j] < bh:
                e = O[j + 1]; sd = -side
                stp = ext + side * 0.1 * A
                if sd * (e - stp) <= 0: break
                if ex == "opp": tp = bl if sd < 0 else bh
                else: tp, _, _ = exit_args(ex, H, sd, e, ctx)
                if np.isfinite(tp) and sd * (tp - e) <= 0: tp = np.nan
                trail = 3.0 if ex == "trail3" else None
                r = sim_leg(j + 1, sd, e, stp, tp, trail, None, chand=ctx["chand"])
                if r is not None:
                    jj, px, kind, frac, s0 = r; tr.append(booked(j + 1, jj, sd, e, px, frac, kind, s0))
                break
    return tr, np.nan

def sys_dsweep(S, ex, ctx, P):
    tr = []
    for s in S:
        bh, bl, A = s["bh"], s["bl"], s["A"]; H = bh - bl; i = s["i0"]; i1 = s["i1"]
        s1 = 0
        while i <= i1:
            s1 = first_touch(i, bh, bl)
            if s1: break
            i += 1
        if not s1: continue
        b = -1
        for j in range(i, i1 + 1):
            if (s1 > 0 and L[j] <= bl) or (s1 < 0 and Hh[j] >= bh): b = j; break
        if b < 0: continue
        ext2 = L[b] if s1 > 0 else Hh[b]
        for j in range(b, i1 + 1):
            ext2 = min(ext2, L[j]) if s1 > 0 else max(ext2, Hh[j])
            if j > b and ((s1 > 0 and C[j] > bh) or (s1 < 0 and C[j] < bl)) and j + 1 < N:
                e = O[j + 1]; stp = ext2 - s1 * 0.1 * A
                if s1 * (e - stp) <= 0: break
                tp, trail, exh = exit_args(ex, H, s1, e, ctx)
                r = sim_leg(j + 1, s1, e, stp, tp, trail, exh, chand=ctx["chand"])
                if r is not None:
                    jj, px, kind, frac, s0 = r; tr.append(booked(j + 1, jj, s1, e, px, frac, kind, s0))
                break
    return tr, np.nan

def classify(S):
    out = []
    for s in S:
        bh, bl = s["bh"], s["bl"]; i0, i1 = s["i0"], s["i1"]
        s1 = 0; a = -1
        for i in range(i0, i1 + 1):
            s1 = first_touch(i, bh, bl)
            if s1: a = i; break
        if not s1: out.append("no break"); continue
        both = False
        for j in range(a, i1 + 1):
            if (s1 > 0 and L[j] <= bl) or (s1 < 0 and Hh[j] >= bh):
                if j > a or (Hh[j] >= bh and L[j] <= bl): both = True; break
        fc = C[i1]
        if not both:
            out.append("clean run" if (s1 > 0 and fc > bh) or (s1 < 0 and fc < bl) else "fakeout")
        else:
            if (s1 > 0 and fc > bh) or (s1 < 0 and fc < bl): out.append("both->1st side")
            elif (s1 > 0 and fc < bl) or (s1 < 0 and fc > bh): out.append("both->2nd side")
            else: out.append("both->inside")
    return out

PAT_COLS = ["no break", "clean run", "fakeout", "both->1st side", "both->2nd side", "both->inside"]

def tstats(tr, a=None, b=None):
    """trade list -> stats; equity booked at exits (realised), compounding."""
    if not len(tr): return dict(tr=0, win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan)
    t = pd.DataFrame(tr, columns=TCOLS).sort_values("t_out")
    if a: t = t[t.t_out >= ms(a)]
    if b: t = t[t.t_out < ms(b)]
    if not len(t): return dict(tr=0, win=np.nan, pf=np.nan, ret=0.0, dd=0.0)
    eq = np.cumprod(1 + t.ret.values); pk = np.maximum.accumulate(np.r_[1.0, eq])[1:]
    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(), pf=(g / ls if ls > 0 else (np.inf if g > 0 else np.nan)),
                ret=100 * (eq[-1] - 1), dd=100 * min(0.0, (eq / pk - 1).min()))

def tdaily(tr):
    if not len(tr): return pd.Series(dtype=float)
    t = pd.DataFrame(tr, columns=TCOLS)
    return t.groupby(t.t_out // D1).ret.sum()

def trow(tr, extra=None):
    h = tstats(tr, 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 = tstats(tr, a_, z); row[b] = f"{fmt(st['ret'])}/{fmt(st['dd'])}/{st['tr']}/{fmt(st['pf'],2)}"
    if extra is not None: row["dbl-loss%"] = fmt(extra, 0)
    return row

def engine_trades(res):
    t = res["trades"]; return [(a, b, c, d, "", m, r) for a, b, c, d, m, r in zip(t.t_in, t.t_out, t.side, t.ret, t.move, t.risk)]

def run_asset(D, P, with_grid=True):
    """All batch-3 systems for the current asset. Returns dict name -> (trades, dbl%)."""
    stb, sdb, _ = state_arrays(D)
    ctx = dict(chand=to_base(D, D["atr"].values, D1),
               exhL=(stb == SCODE["EXHAUST"]) & (sdb > 0), exhS=(stb == SCODE["EXHAUST"]) & (sdb < 0))
    S = coil_setups(D, P)
    R = {}
    R["A straddle"] = sys_straddle(S, "opp", "trail3", ctx, P)
    R["B oco"] = sys_oco(S, "opp", "trail3", ctx, P)
    R["B oco-rearm"] = sys_oco(S, "opp", "trail3", ctx, P, rearm=True)
    R["D fade"] = sys_fade(S, "opp", ctx, P)
    R["E dsweep"] = sys_dsweep(S, "trail3", ctx, P)
    G = {}
    if with_grid:
        for sv in STOPS:
            for ex in EXITS:
                G[("A", sv, ex)] = sys_straddle(S, sv, ex, ctx, P)
                G[("B", sv, ex)] = sys_oco(S, sv, ex, ctx, P)
            G[("B-rearm", sv, "trail3")] = sys_oco(S, sv, "trail3", ctx, P, rearm=True)
        for K in (6, 12, 24):
            for ex in ("opp", "2box", "trail3"):
                G[("D", f"K{K}", ex)] = sys_fade(S, ex, ctx, dict(P, K=K))
        for ex in ("trail3", "tp1", "tp2"):
            G[("E", "-", ex)] = sys_dsweep(S, ex, ctx, P)
    return R, G, S
# ---------------------------------------------------------------------------------------------
# BATCH 4 additions
# ---------------------------------------------------------------------------------------------
LEV = 3.0
LIQ_MOVE = 1.0 / LEV - 0.005     # ~32.8% adverse move liquidates a 3x isolated position (0.5% maintenance)

def sys_oco(S, stop_v, ex, ctx, P, rearm=False, pred=None, mode=None):
    """batch-3 OCO; pred = list of leans aligned with S. mode 'one' = only the predicted side, no re-arm;
    mode 'tilt' = full bracket, predicted-side trades x1.5 size."""
    tr = []; dbl = 0; n2 = 0
    for si, s in enumerate(S):
        bh, bl, A = s["bh"], s["bl"], s["A"]; H = bh - bl; i = s["i0"]; i1 = s["i1"]
        pv = pred[si] if pred is not None else 0
        if mode == "one" and pv == 0: continue
        side = 0
        while i <= i1:
            if mode == "one":
                side = pv if ((pv > 0 and Hh[i] >= bh) or (pv < 0 and L[i] <= bl)) else 0
            else:
                side = first_touch(i, bh, bl)
            if side: break
            i += 1
        if not side: continue
        res = []; e_prev_px = np.nan
        for attempt in range(2 if (rearm and mode != "one") else 1):
            e = max(O[i], bh) if side > 0 else min(O[i], bl)
            if attempt == 1: e = max(e_prev_px, bh) if side > 0 else min(e_prev_px, bl)
            if stop_v == "opp": stp = bl if side > 0 else bh
            elif stop_v == "mid": stp = (bh + bl) / 2
            else: stp = e - side * P["k"] * A
            if side * (e - stp) <= 0: stp = e - side * 0.5 * A
            tp, trail, exh = exit_args(ex, H, side, e, ctx)
            r = sim_leg(i, side, e, stp, tp, trail, exh, fill_bar_stopentry=True, chand=ctx["chand"])
            if r is None: break
            j, px, kind, frac, s0 = r
            b = booked(i, j, side, e, px, frac, kind, s0)
            if mode == "tilt" and side == pv: b = (b[0], b[1], b[2], b[3] * 1.5, b[4], b[5], b[6] / 1.5)
            res.append(b)
            if not (rearm and mode != "one" and kind == "stop" and j <= i1): break
            side = -side; k = j; e_prev_px = px; found = False
            while k <= i1:
                if (side > 0 and Hh[k] >= bh) or (side < 0 and L[k] <= bl): found = True; break
                k += 1
            if not found: break
            if k > j: e_prev_px = O[k]
            i = k
        if rearm and len(res) == 2:
            n2 += 1; dbl += int(res[0][3] < 0 and res[1][3] < 0)
        tr += res
    return tr, (100 * dbl / n2 if n2 else np.nan)

def sleeves_for_asset(D, with_v7=False):
    stb, sdb, _ = state_arrays(D)
    k8 = k8_system(D)
    out = {}
    out["K8"] = engine_trades(run("K8", k8["sig"], k8["stop"], exitL=k8["dir"] < 0, exitS=k8["dir"] > 0, allow=k8_allow(k8, k8["sig"])))
    S5P, B1P = s5_b1(D)
    gate = (stb == SCODE["COIL"]) | (stb == SCODE["QUAKE"]) | (stb == SCODE["RIDE"])
    out["B1G"] = engine_trades(run("B1G", B1P["sig"], B1P["stop_dist"], chand_atr=B1P["chand_atr"], chand_mult=3.0, max_hold=B1P["max_hold"], allow=gate))
    out["S5"] = engine_trades(run("S5", S5P["sig"], S5P["stop_dist"], chand_atr=S5P["chand_atr"], chand_mult=3.0, max_hold=S5P["max_hold"]))
    ctx = dict(chand=to_base(D, D["atr"].values, D1),
               exhL=(stb == SCODE["EXHAUST"]) & (sdb > 0), exhS=(stb == SCODE["EXHAUST"]) & (sdb < 0))
    S = coil_setups(D, P0)
    out["BRA"] = sys_oco(S, "opp", "trail3", ctx, P0, rearm=True)[0]
    out["BOCO"] = sys_oco(S, "opp", "trail3", ctx, P0)[0]
    out["STR"] = sys_straddle(S, "opp", "trail3", ctx, P0)[0]
    extra = {}
    if with_v7:
        extra["K8R"] = run("K8", k8["sig"], k8["stop"], exitL=k8["dir"] < 0, exitS=k8["dir"] > 0, allow=k8_allow(k8, k8["sig"]))
        extra["V7R"] = run("V7", v7_system(D), 0.10 * C, trail_start=0.20, trail_drop=0.15)
    return out, S, ctx, extra

BASKETS = {"K8": ["K8"], "BRA": ["BRA"], "B1G": ["B1G"], "S5": ["S5"], "BOCO": ["BOCO"], "STR": ["STR"],
           "K8+BRA": ["K8", "BRA"], "K8+BRA+B1G": ["K8", "BRA", "B1G"], "ALL4 (K8+BRA+B1G+S5)": ["K8", "BRA", "B1G", "S5"],
           "ALL4 w/ BOCO": ["K8", "BOCO", "B1G", "S5"], "ALL4 w/ STR": ["K8", "STR", "B1G", "S5"],
           "K8+BRA+B1G (no dedupe)": ["K8", "BRA", "B1G"]}
NODEDUPE = {"K8+BRA+B1G (no dedupe)"}
BRACKETS = {"BRA", "BOCO", "STR"}

def shared(SL, names, risk=0.01, cap_n=None, dedupe=True):
    """shared-equity sim. Returns dict with daily equity (realised), taken trades, risk diagnostics."""
    ev = []
    for nm in names:
        for t in SL[nm]:
            if not np.isfinite(t[6]) or t[6] <= 0: continue
            ev.append((t[0], t[1], t[2], t[5], t[6], nm))
    ev.sort(key=lambda x: (x[0], x[1]))
    eq = 1.0; open_ = []; book = []; taken = []; recent = []; maxmargin = 0.0; worst_adv = 0.0; max_stop = 0.0
    def close_until(tm):
        nonlocal eq, open_
        keep = []
        for o in sorted(open_, key=lambda z: z[0]):
            if o[0] <= tm:
                eq += o[1]; book.append((o[0], o[1], eq))
            else: keep.append(o)
        open_ = keep
    for (ti, to, side, mv, rp, nm) in ev:
        close_until(ti)
        if cap_n is not None and len(open_) >= cap_n: continue
        if dedupe:
            dup = False
            for (rt, rs, rn) in recent:
                if rs == side and abs(ti - rt) <= 48 * H1 and ((rn in BRACKETS and nm == "B1G") or (rn == "B1G" and nm in BRACKETS)):
                    dup = True; break
            if dup: continue
        frac = min(LEV, risk / rp)
        pnl = eq * frac * (mv - 2 * COST)
        open_.append((to, pnl, frac, eq)); taken.append((ti, to, side, pnl / eq, nm, rp, mv))
        recent = [r for r in recent if ti - r[0] <= 48 * H1] + [(ti, side, nm)]
        maxmargin = max(maxmargin, sum(o[2] * o[3] for o in open_) / LEV / eq)
        max_stop = max(max_stop, rp); worst_adv = max(worst_adv, -mv)
    close_until(10**18)
    if not book: return None
    b = pd.DataFrame(book, columns=["t", "pnl", "eq"])
    day = (b.t // D1)
    eqd = b.groupby(day).eq.last()
    full = pd.Series(np.nan, index=np.arange(int(T[0] // D1), int(T[-1] // D1) + 1))
    full.loc[eqd.index] = eqd.values; full = full.ffill().fillna(1.0)
    return dict(eq=full, taken=taken, maxmargin=maxmargin, max_stop=max_stop, worst_adv=worst_adv)

def eq_metrics(res, a=None, b=None):
    if res is None: return {}
    e = res["eq"]; lo = ms(a) // D1 if a else e.index[0]; hi = ms(b) // D1 if b else e.index[-1] + 1
    prev = e[e.index < lo]; base = prev.iloc[-1] if len(prev) else 1.0
    x = e[(e.index >= lo) & (e.index < hi)]
    if len(x) < 2: return {}
    rel = x / base; ret = 100 * (rel.iloc[-1] - 1)
    pk = np.maximum.accumulate(np.r_[1.0, rel.values])[1:]; dd = 100 * (rel.values / pk - 1).min()
    # longest drawdown duration (days)
    longest = cur = 0
    for v, p in zip(rel.values, pk):
        cur = cur + 1 if v < p - 1e-12 else 0; longest = max(longest, cur)
    _dt = pd.to_datetime(x.index * D1, unit="ms")
    mo = pd.Series(rel.values).groupby((_dt.year * 12 + _dt.month).values).last()
    mr = mo.pct_change(); mr.iloc[0] = mo.iloc[0] - 1; mr = mr[mr.abs() > 1e-12]
    tk = [t for t in res["taken"] if (a is None or t[1] >= ms(a)) and (b is None or t[1] < ms(b))]
    tk.sort(key=lambda z: z[1]); streak = cs = 0
    for t in tk:
        cs = cs + 1 if t[3] < 0 else 0; streak = max(streak, cs)
    return dict(ret=ret, dd=dd, mar=(ret / abs(dd) if dd < 0 else np.nan), mwin=100 * (mr > 0).mean() if len(mr) else np.nan,
                worstm=100 * mr.min() if len(mr) else np.nan, ddays=longest, streak=streak, n=len(tk))

def lose_week_eq(res):
    if res is None: return np.nan
    d = res["eq"].pct_change().fillna(0).reindex(IDX).fillna(0)
    return round(100 * d.groupby(WK).sum().reindex(LOSEW).sum(), 1)

def basket_table(SL, risk, cap, label, with_lw=True):
    rows = []
    for bn, names in BASKETS.items():
        if any(n not in SL for n in names): continue
        r = shared(SL, names, risk, cap, dedupe=bn not in NODEDUPE); m = eq_metrics(r, HEADLINE_START)
        if not m: continue
        row = {"basket": bn, "trades": m["n"], "ret17+%": round(m["ret"], 1), "maxDD%": round(m["dd"], 1),
               "MAR": round(m["mar"], 2) if np.isfinite(m["mar"]) else np.nan, "mon win%": round(m["mwin"], 0),
               "worst mon%": round(m["worstm"], 1), "longest DD d": m["ddays"], "lose streak": m["streak"]}
        for b, a_, z in BUCKETS:
            mm = eq_metrics(r, a_, z); row[b] = f"{fmt(mm.get('ret'))}/{fmt(mm.get('dd'))}" if mm else "-"
        if with_lw: row["K8V7 lose-wk%"] = lose_week_eq(r)
        rows.append(row)
    print(f"\n--- {label} ---"); t = pd.DataFrame(rows).set_index("basket"); print(t.to_string()); return t

# ---------------------------------------------------------------------------------------------
# PART B helpers
# ---------------------------------------------------------------------------------------------
def binom_p(k, n):
    if n == 0: return np.nan
    pk = [math.comb(n, i) * 0.5 ** n for i in range(n + 1)]; obs = pk[k]
    return min(1.0, sum(p for p in pk if p <= obs + 1e-15))

def box_features(D, S, fund=None):
    c = D.close.values; hi = D.high.values; lo = D.low.values
    s200 = pd.Series(c).rolling(200).mean().values; hi1y = pd.Series(hi).rolling(365, min_periods=200).max().values
    fdaily = None
    if fund is not None:
        f = fund.copy(); f["g"] = f["time"] // D1; fdaily = f.groupby("g").funding.mean()
    rows = []
    for s in S:
        d = s["d"]; bh, bl = s["bh"], s["bl"]; i0, i1 = s["i0"], s["i1"]; N_ = int(P0["N"])
        r = {"t": s["t"]}
        for k in (30, 60, 90):
            r[f"R{k}"] = int(np.sign(c[d] / c[d - k] - 1)) if d - k >= 0 else 0
        r["SMA200"] = int(np.sign(c[d] - s200[d])) if np.isfinite(s200[d]) else 0
        dd = c[d] / hi1y[d] - 1 if np.isfinite(hi1y[d]) else np.nan
        r["DD1Y"] = 1 if (np.isfinite(dd) and dd > -0.10) else (-1 if (np.isfinite(dd) and dd < -0.30) else 0)
        clv = (c[d] - bl) / (bh - bl) if bh > bl else 0.5
        r["CLV"] = 1 if clv >= 0.6 else (-1 if clv <= 0.4 else 0)
        a0 = max(0, i0 - N_ * 24); seg = slice(a0, i0)
        up = V[seg][C[seg] > O[seg]].sum(); dn = V[seg][C[seg] < O[seg]].sum()
        ratio = up / dn if dn > 0 else np.nan
        r["VOLASYM"] = 1 if (np.isfinite(ratio) and ratio > 1.1) else (-1 if (np.isfinite(ratio) and ratio < 0.9) else 0)
        r["FUND"] = 0
        if fdaily is not None:
            g = int(s["t"] // D1) - 1
            box = fdaily.reindex(range(g - N_ + 1, g + 1)).dropna(); prior = fdaily.reindex(range(g - N_ - 90 + 1, g - N_ + 1)).dropna()
            if len(box) >= 3 and len(prior) >= 60 and prior.std() > 0:
                z = (box.mean() - prior.mean()) / prior.std()
                r["FUND"] = 1 if z > 0.5 else (-1 if z < -0.5 else 0)
        # sweep + reclaim
        sw = 0
        for i in range(i0, i1 + 1):
            s1 = first_touch(i, bh, bl)
            if s1:
                for j in range(i, min(i + 24, i1) + 1):
                    if bl < C[j] < bh: sw = -s1; break
                break
        r["SWEEP"] = sw
        v = -r["R90"] + r["CLV"] + r["VOLASYM"] - r["FUND"]
        r["VOTE0"] = int(np.sign(v)); r["VOTE"] = int(np.sign(v + sw))
        fc = C[i1]; r["OUT_END"] = 1 if fc > bh else (-1 if fc < bl else 0)
        of = 0
        for i in range(i0, i1 + 1):
            if C[i] > bh: of = 1; break
            if C[i] < bl: of = -1; break
        r["OUT_FIRST"] = of
        rows.append(r)
    return pd.DataFrame(rows)

FEATS = ["R30", "R60", "R90", "SMA200", "DD1Y", "CLV", "VOLASYM", "FUND", "SWEEP", "VOTE", "VOTE0"]

def score_features(F, label, early_end):
    rows = []
    if F is None or not len(F): return pd.DataFrame()
    for f in FEATS:
        x = F[(F[f] != 0) & (F.OUT_END != 0)]
        if len(x) < 8: rows.append({"asset": label, "feature": f, "n": len(x)}); continue
        hit = (x[f] == x.OUT_END).values; k = int(hit.sum()); n = len(hit)
        e = x[x.t < ms(early_end)]; l_ = x[x.t >= ms("2021-01-01")]
        he = 100 * (e[f] == e.OUT_END).mean() if len(e) else np.nan; hl = 100 * (l_[f] == l_.OUT_END).mean() if len(l_) else np.nan
        sims = []
        lab = x.OUT_END.values; lean = x[f].values
        for _ in range(N_PLACEBO): sims.append(100 * np.mean(lean == RNG.permutation(lab)))
        lo, hi = np.percentile(sims, [5, 95]); h = 100 * k / n
        xf = F[(F[f] != 0) & (F.OUT_FIRST != 0)]
        hf = 100 * (xf[f] == xf.OUT_FIRST).mean() if len(xf) else np.nan
        real = ""
        if (h > hi) and he >= 55 and hl >= 55: real = "REAL (continuation)"
        elif (h < lo) and he <= 45 and hl <= 45: real = "REAL (reversal)"
        rows.append({"asset": label, "feature": f, "n": n, "hit% (end)": round(h, 1), "binom p": round(binom_p(k, n), 3),
                     "placebo 5-95": f"{lo:.0f}-{hi:.0f}", "early hit% (n)": f"{fmt(he,0)} ({len(e)})", "2021+ hit% (n)": f"{fmt(hl,0)} ({len(l_)})",
                     "hit% first-close": round(hf, 1) if np.isfinite(hf) else np.nan, "verdict": real or "noise"})
    return pd.DataFrame(rows)

# ---------------------------------------------------------------------------------------------
# LOAD + RUN
# ---------------------------------------------------------------------------------------------
btc, SRC = load_asset("btc")
if btc is None or _bar_ms(btc) > H1:
    raise SystemExit("Batch 4 needs BTC 1h data (hosted btc_1h_full.csv.gz).")
FUND = load_funding()
btc["dt"] = pd.to_datetime(btc["time"], unit="ms")
print(f"\nBTC DATA: {SRC} | {len(btc):,} rows")
print(btc.groupby("source").agg(first=("dt", "min"), last=("dt", "max"), rows=("time", "size")).sort_values("first").to_string())
set_asset(btc)
DAY = market_states(build_day(FUND))
t_b = time.time()
SL, SETUPS, CTX, EX = sleeves_for_asset(DAY, with_v7=True)
base_kv = (daily_ret(EX["K8R"]) + daily_ret(EX["V7R"])) / 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
FB = box_features(DAY, SETUPS, FUND)
pred0 = FB["VOTE0"].tolist() if len(FB) else []
BT = {"BRA full": SL["BRA"],
      "BRA one-sided": sys_oco(SETUPS, "opp", "trail3", CTX, P0, rearm=True, pred=pred0, mode="one")[0],
      "BRA tilt": sys_oco(SETUPS, "opp", "trail3", CTX, P0, rearm=True, pred=pred0, mode="tilt")[0]}
BTC_CTX = (df, N, O, Hh, L, C, V, T)
print(f"(BTC built in {time.time()-t_b:.0f}s) | COIL boxes {len(SETUPS)}")

ESL = {}; FE = None; ET = {}
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"ETH DATA: {ESRC} | {len(eth):,} rows")
    set_asset(eth)
    EDAY = market_states(build_day(None))
    ESL, ESET, ECTX, _ = sleeves_for_asset(EDAY)
    FE = box_features(EDAY, ESET, None)
    ep = FE["VOTE0"].tolist() if len(FE) else []
    ET = {"BRA full": ESL["BRA"],
          "BRA one-sided": sys_oco(ESET, "opp", "trail3", ECTX, P0, rearm=True, pred=ep, mode="one")[0],
          "BRA tilt": sys_oco(ESET, "opp", "trail3", ECTX, P0, rearm=True, pred=ep, mode="tilt")[0]}
    ETH_T = (df, N, O, Hh, L, C, V, T)
    df, N, O, Hh, L, C, V, T = BTC_CTX
else:
    print("ETH data not available -> ETH parts skipped")

# ---------------------------------------------------------------------------------------------
# PART A REPORTS
# ---------------------------------------------------------------------------------------------
print(f"\n=================== PART A — COMBINED BASKET (BTC; K8+V7 losing weeks 2017+: {len(LOSEW)}) ===================")
print("ret/DD per period cells = ret% / maxDD% (realised equity, period restarts from its own start).")
A_UN = basket_table(SL, 0.01, None, "BTC 1% risk/trade, UNCAPPED shared equity")
A_CP = basket_table(SL, 0.01, 4, "BTC 1% risk/trade, CAPPED (max 4 open = 4% open risk)")

print("\n--- RISK LEVELS (capped, max 4 open) + 3x isolated liquidation check — 2017+ ---")
rows = []
for bn in ["K8+BRA+B1G", "ALL4 (K8+BRA+B1G+S5)", "K8+BRA", "BRA"]:
    for rk in (0.01, 0.02, 0.05):
        r = shared(SL, BASKETS[bn], rk, 4); m = eq_metrics(r, HEADLINE_START); m13 = eq_metrics(r, "2013-01-01", "2017-01-01")
        if not m: continue
        rows.append({"basket": bn, "risk": f"{rk*100:.0f}%", "ret17+%": round(m["ret"], 1), "maxDD%": round(m["dd"], 1),
                     "MAR": round(m["mar"], 2) if np.isfinite(m["mar"]) else np.nan, "worst mon%": round(m["worstm"], 1),
                     "lose streak": m["streak"], "longest DD d": m["ddays"], "13-16 ret/DD": f"{fmt(m13.get('ret'))}/{fmt(m13.get('dd'))}" if m13 else "-",
                     "max stop dist%": round(100 * r["max_stop"], 1), "worst adverse%": round(100 * r["worst_adv"], 1),
                     "liq dist%": round(100 * LIQ_MOVE, 1), "peak margin%": round(100 * r["maxmargin"], 0),
                     "liq-safe": "yes" if (r["max_stop"] < 0.5 * LIQ_MOVE and r["worst_adv"] < LIQ_MOVE and r["maxmargin"] <= 1.0) else "CHECK"})
RK = pd.DataFrame(rows); print(RK.to_string(index=False))
print("liq-safe = every stop < half the liquidation distance, no realised adverse move reached liquidation, peak margin <= 100%.")

print("\n--- Sleeve correlation (daily realised returns, 1% standalone, 2017+) ---")
def sdaily(tr):
    if not len(tr): return pd.Series(0.0, index=IDX)
    t = pd.DataFrame(tr, columns=TCOLS); return t.groupby(t.t_out // D1).ret.sum().reindex(IDX).fillna(0)
CM = pd.DataFrame({k: sdaily(v) for k, v in SL.items()}); CM["K8+V7"] = base_kv.reindex(IDX).fillna(0)
print(CM.corr().round(2).to_string())

print("\n--- B1-gate vs bracket overlap (BTC, all years) ---")
b1d = pd.DataFrame(SL["B1G"], columns=TCOLS); brd = pd.DataFrame(SL["BRA"], columns=TCOLS)
sh = same = 0
for _, t in b1d.iterrows():
    m = brd[(brd.t_in - t.t_in).abs() <= D1]
    if len(m): sh += 1; same += int((m.side == t.side).any())
print(f"B1G trades {len(b1d)} | with a bracket entry within +/-1 day: {sh} ({100*sh/max(1,len(b1d)):.0f}%) | same direction: {same} "
      f"({100*same/max(1,len(b1d)):.0f}%) -> deduped in baskets (same direction within 48h, first one kept)")

if ESL:
    set_asset(eth)   # ETH arrays for any lookups (basket sim itself only uses trade lists)
    IDX_B, WK_B, LW_B = IDX, WK, LOSEW
    print("\n=================== PART A — ETH (same settings; ETH starts 2017-08) ===================")
    E_CP = basket_table(ESL, 0.01, 4, "ETH 1% risk/trade, CAPPED (max 4 open)", with_lw=False)
    rows = []
    for bn in ["K8+BRA+B1G", "ALL4 (K8+BRA+B1G+S5)"]:
        for rk in (0.01, 0.02, 0.05):
            r = shared(ESL, BASKETS[bn], rk, 4); m = eq_metrics(r, HEADLINE_START)
            if m: rows.append({"basket": bn, "risk": f"{rk*100:.0f}%", "ret17+%": round(m["ret"], 1), "maxDD%": round(m["dd"], 1),
                               "MAR": round(m["mar"], 2) if np.isfinite(m["mar"]) else np.nan, "lose streak": m["streak"],
                               "max stop%": round(100 * r["max_stop"], 1), "peak margin%": round(100 * r["maxmargin"], 0)})
    print(pd.DataFrame(rows).to_string(index=False))
    df, N, O, Hh, L, C, V, T = BTC_CTX
else:
    E_CP = pd.DataFrame()

# ---------------------------------------------------------------------------------------------
# PART B REPORTS
# ---------------------------------------------------------------------------------------------
print("\n=================== PART B — STAGE SEQUENCE -> DIRECTION ===================")
print("hit% = % of boxes (lean != 0, window ended outside the box) where the lean matched the side price ended on.")
print("Momentum-coded: >= 55 = continuation, <= 45 = reversal (e.g. R90 at 40% = 'after a fall, it breaks UP' 60%).")
SB = score_features(FB, "BTC", "2021-01-01")
SE = score_features(FE, "ETH", "2021-01-01") if FE is not None else pd.DataFrame()
SC = pd.concat([SB, SE]); print(SC.to_string(index=False))
if len(FB):
    ob = FB.OUT_END.value_counts().to_dict()
    print(f"BTC boxes {len(FB)}: window-end outcome up {ob.get(1,0)} / down {ob.get(-1,0)} / inside {ob.get(0,0)}")
if FE is not None and len(FE):
    oe = FE.OUT_END.value_counts().to_dict()
    print(f"ETH boxes {len(FE)}: window-end outcome up {oe.get(1,0)} / down {oe.get(-1,0)} / inside {oe.get(0,0)}")

print("\n--- Using VOTE0 (known at the coil close) in the bracket — 1% risk, realised equity ---")
rows = []
for nm in BT:
    for asset, src in (("BTC", BT), ("ETH", ET)):
        if nm not in src: continue
        h = tstats(src[nm], HEADLINE_START); e = tstats(src[nm], "2013-01-01", "2017-01-01")
        rows.append({"system": nm, "asset": asset, "trades17+": h["tr"], "win%": fmt(h["win"], 0), "PF17+": fmt(h["pf"], 2),
                     "ret17+%": fmt(h["ret"]), "dd17+%": fmt(h["dd"]),
                     "MAR": fmt(h["ret"] / abs(h["dd"]) if h["dd"] and np.isfinite(h["dd"]) and h["dd"] < 0 else np.nan, 2),
                     "2013-16 PF/ret": f"{fmt(e['pf'],2)}/{fmt(e['ret'])}" if asset == "BTC" else "-"})
VT = pd.DataFrame(rows); print(VT.to_string(index=False))

# ---------------------------------------------------------------------------------------------
# VERDICTS (pre-declared)
#  Basket KEEP: capped-1% 2017+ MAR above EVERY member's capped-1% MAR alone, positive in >= 3 of 4 blocks
#               (13-16, 17-20, 21-23, 24+), and ETH capped-1% 2017+ return > 0.
#  Risk level : OK if capped 2017+ maxDD > -35%, 2013-16 maxDD > -35%, and liq-safe = yes; else TOO HOT.
#  Feature    : REAL rule in the header. Vote trading: HELPS if MAR 2017+ beats 'BRA full' on BTC AND ETH.
# ---------------------------------------------------------------------------------------------
print("\n=================== RANKED SUMMARY + VERDICTS ===================")
rows = []
for bn, names in BASKETS.items():
    if len(names) < 2 or bn not in A_CP.index: continue
    r = A_CP.loc[bn]
    mem = [A_CP.loc[n, "MAR"] for n in names if n in A_CP.index]
    nblk = sum(1 for b, _, _ in BUCKETS[:4] if str(r[b]).split("/")[0] not in ("-", "") and float(str(r[b]).split("/")[0]) > 0)
    eth_ret = E_CP.loc[bn, "ret17+%"] if (len(E_CP) and bn in E_CP.index) else np.nan
    ok = (np.isfinite(r["MAR"]) and all(np.isfinite(x) and r["MAR"] > x for x in mem) and nblk >= 3 and np.isfinite(eth_ret) and eth_ret > 0)
    rows.append({"basket (capped 1%)": bn, "verdict": "KEEP" if ok else ("MAYBE" if (np.isfinite(r["MAR"]) and r["MAR"] > 0 and nblk >= 3) else "DROP"),
                 "MAR": r["MAR"], "best member MAR": max(mem) if mem else np.nan, "ret17+%": r["ret17+%"], "maxDD%": r["maxDD%"],
                 "blocks+": f"{nblk}/4", "ETH ret%": eth_ret, "K8V7 lose-wk%": r.get("K8V7 lose-wk%", np.nan)})
SMB = pd.DataFrame(rows)
if len(SMB):
    SMB["_k"] = SMB.verdict.map({"KEEP": 0, "MAYBE": 1, "DROP": 2})
    SMB = SMB.sort_values(["_k", "MAR"], ascending=[True, False]).drop(columns="_k")
print(SMB.to_string(index=False))
print("\nRisk level verdicts:")
for _, r in RK.iterrows():
    m13 = str(r["13-16 ret/DD"]).split("/")
    dd13 = float(m13[1]) if len(m13) == 2 and m13[1] not in ("-", "") else np.nan
    ok = r["maxDD%"] > -35 and (not np.isfinite(dd13) or dd13 > -35) and r["liq-safe"] == "yes"
    print(f"  {r['basket']:<22} {r['risk']:>3}: {'OK' if ok else 'TOO HOT'}  (ret {r['ret17+%']}%, DD {r['maxDD%']}%, 2013-16 {r['13-16 ret/DD']}, "
          f"losing streak {r['lose streak']}, peak margin {r['peak margin%']}%, liq-safe {r['liq-safe']})")
print("\nFeature verdicts (REAL needs placebo + both blocks):")
for _, r in SC.iterrows():
    if "verdict" in r and isinstance(r.get("verdict"), str):
        print(f"  {r['asset']} {r['feature']:<8} {r['verdict']:<20} hit {r.get('hit% (end)')}% n={r['n']} p={r.get('binom p')}")
if len(VT):
    def vmar(sysn, asset):
        x = VT[(VT.system == sysn) & (VT.asset == asset)]
        return float(x.MAR.iloc[0]) if len(x) and x.MAR.iloc[0] != "-" else np.nan
    for nm in ("BRA one-sided", "BRA tilt"):
        hb = vmar(nm, "BTC") > vmar("BRA full", "BTC"); he = vmar(nm, "ETH") > vmar("BRA full", "ETH")
        print(f"  {nm:<14}: {'HELPS' if (hb and he) else 'NO'} (MAR BTC {vmar(nm,'BTC')} vs {vmar('BRA full','BTC')}, ETH {vmar(nm,'ETH')} vs {vmar('BRA full','ETH')})")
SMB.to_csv(OUT_DIR / "specialists_batch4_baskets.csv", index=False); SC.to_csv(OUT_DIR / "specialists_batch4_features.csv", index=False)
print(f"\nWrote specialists_batch4_baskets.csv and specialists_batch4_features.csv to {OUT_DIR} | total runtime {time.time()-T0:.0f}s")
