# ===== zai20.py - z.ai idea list: 6 regime forecasters as overlays + 4 new engines, vs the live basket with cut30 =====
# Colab:  !wget -q -O zai20.py https://osom-boba.pages.dev/colab/zai20.py
#         %run zai20.py
# Box (synthetic smoke only):  python3 zai20.py --smoke
#
# Basket = oslib.engines() (K8 C1 C2 COCO B1G S5 V7 R0 MOM30 D34) + Q3 (port of live q3.mjs), live risk
# (K8 2%; COCO B1G S5 3%; others 1%), costs 0.12%/side inside the engines, maxOpen 4, compounded on exit
# time, cut30 on (pause an engine for the week while its last-30 PF < 1.0, set each UTC Monday) = BASELINE.
# Families: TREND K8 MOM30 D34 Q3 | FADE C1 C2 V7 | BRK COCO B1G S5 R0.
# Section A: next-4-week PF of each family by forecaster state (state read the day before; shadow trades).
# Section B: forecaster overlays (x0.5 on the named family/side while the state is bad) on top of the baseline.
#   KEEP_LIVE = MAR > baseline in both halves (2017-20 / 2021-26; a half where the overlay never acts is
#   skipped), beats baseline in >= 5/7 years BTC and >= 4/7 ETH (scaled to the years it acts),
#   placebo (state labels shuffled in 28-day blocks, 200 runs) >= 90, maxDD not worse by more than 3 pts.
# Section C: new engines B1 carry, B4 COT, B5 MVRV<1, B3 kimchi: standalone stats + ADD_SMALL at 0.5% risk.
#   ADD_SMALL = MAR >= baseline in both halves, maxDD not worse by more than 3 pts, beats baseline >= 4/7 yrs BTC.
# Ex-ante: every state uses data through the prior UTC day (MVRV 2 days, FRED dollar index 7 days).
import os, sys, time, json, io, zipfile, subprocess, traceback, heapq, math
from pathlib import Path
from urllib.request import urlopen, Request

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

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

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

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

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

NAN = np.nan
LIVE = dict(oslib.LIVE_RISK); LIVE["Q3"] = 0.01
FAM = {"TREND": ("K8", "MOM30", "D34", "Q3"), "FADE": ("C1", "C2", "V7"), "BRK": ("COCO", "B1G", "S5", "R0")}
START, SPLIT, END = "2017-01-01", "2021-01-01", "2027-01-01"
MAX_OPEN = 4
N_PLC = 200
SEED = 20261123
YEARS = list(range(2020, 2027))
MON0 = -3 * D1
W1MS = 7 * D1
ADD_RISK = 0.005
B1_RREF = 0.02   # B1 carry: R = net return / 2% (assumed tail per unit notional), so 0.5% risk = 25% notional
CACHE = Path("/content") if Path("/content").exists() else Path("./zai20_smoke_cache")
CACHE.mkdir(parents=True, exist_ok=True)
UA_WEB = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"
ROWS, VERD, NOTES = [], [], []

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

T_START, T_SPLIT, T_END = ms(START), ms(SPLIT), ms(END)

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

def pc(x, nd=1):
    return "n/a" if x is None or not np.isfinite(x) else f"{100*x:.{nd}f}"

def rec(section, asset, subset, metric, value):
    try:
        v = float(value)
    except Exception:
        v = NAN
    ROWS.append(dict(section=section, asset=asset, subset=subset, metric=metric, value=v))

def note(s):
    NOTES.append(s)
    print("  NOTE: " + s, flush=True)

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

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

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

# ---------------------------------------------------------------------------
# downloads (all wrapped; cached to /content)
# ---------------------------------------------------------------------------
def http_bytes(url, timeout=60, ua=UA_WEB, tries=3):
    last = None
    for k in range(tries):
        try:
            with urlopen(Request(url, headers={"User-Agent": ua, "Accept": "*/*"}), timeout=timeout) as r:
                return r.read()
        except Exception as ex:
            last = ex
            code = getattr(ex, "code", None)
            if code in (400, 401, 403, 404, 451):
                break
            time.sleep(1.5 * (k + 1))
    raise last

def http_json(url, timeout=60):
    return json.loads(http_bytes(url, timeout=timeout).decode("utf-8"))

def cache_fresh(p, hours=20):
    return p.exists() and p.stat().st_size > 50 and (time.time() - p.stat().st_mtime) < hours * 3600

def day_series(days, vals):
    s = pd.Series(np.asarray(vals, dtype=float), index=np.asarray(days, dtype="int64"))
    s = s[np.isfinite(s.values)]
    return s.groupby(level=0).last().sort_index()

def save_series(p, s):
    pd.DataFrame({"day": s.index.astype("int64"), "value": s.values}).to_csv(p, index=False)

def read_series(p):
    d = pd.read_csv(p)
    return day_series(d["day"].to_numpy(), d["value"].to_numpy())

def cached_series(name, fetch_fn, hours=20):
    p = CACHE / f"zai20_{name}.csv"
    if cache_fresh(p, hours):
        try:
            return read_series(p)
        except Exception:
            pass
    try:
        s = fetch_fn()
        if s is None or not len(s):
            raise RuntimeError("no rows")
        save_series(p, s)
        return s
    except Exception as ex:
        if p.exists():
            print(f"  {name}: download failed ({type(ex).__name__}: {str(ex)[:80]}); using the cached copy", flush=True)
            return read_series(p)
        print(f"  {name}: download FAILED ({type(ex).__name__}: {str(ex)[:120]})", flush=True)
        return None

def _days_from_dt(idx):
    try:
        d = pd.to_datetime(pd.Index(idx), utc=True, errors="coerce", format="ISO8601")
    except Exception:
        d = pd.to_datetime(pd.Index(idx), utc=True, errors="coerce")
    d = pd.DatetimeIndex(d).tz_convert(None)
    v = d.values.astype("datetime64[D]").astype("int64")
    return np.where(d.isna(), -10**9, v).astype("int64")

def yf_close(ticker):
    import yfinance as yf
    d = yf.download(ticker, start="2014-01-01", progress=False, auto_adjust=False, threads=False)
    if d is None or not len(d):
        raise RuntimeError("yfinance returned nothing")
    c = d["Close"]
    if isinstance(c, pd.DataFrame):
        c = c.iloc[:, 0]
    c = c.dropna()
    return day_series(_days_from_dt(c.index), c.to_numpy(dtype=float))

def fred_csv(sid):
    b = http_bytes("https://fred.stlouisfed.org/graph/fredgraph.csv?id=" + sid, timeout=150)
    d = pd.read_csv(io.BytesIO(b))
    dc = d.columns[0]
    v = pd.to_numeric(d[d.columns[1]], errors="coerce")
    return day_series(_days_from_dt(d[dc]), v.to_numpy(dtype=float))

def coinmetrics_mvrv(asset):
    url = ("https://community-api.coinmetrics.io/v4/timeseries/asset-metrics?assets=" + asset +
           "&metrics=CapMVRVCur&frequency=1d&start_time=2012-01-01&page_size=10000&paging_from=start")
    rows, k = [], 0
    while url and k < 20:
        j = http_json(url)
        rows += j.get("data", [])
        url = j.get("next_page_url")
        k += 1
        time.sleep(0.3)
    if not rows:
        raise RuntimeError("coinmetrics returned no rows")
    d = pd.DataFrame(rows)
    return day_series(_days_from_dt(d["time"]), pd.to_numeric(d["CapMVRVCur"], errors="coerce").to_numpy(dtype=float))

def upbit_daily(market):
    rows, to, k = [], None, 0
    while k < 60:
        url = "https://api.upbit.com/v1/candles/days?market=" + market + "&count=200"
        if to:
            url += "&to=" + to
        try:
            j = http_json(url, timeout=30)
        except Exception as ex:
            if getattr(ex, "code", None) == 429:
                time.sleep(2.0); continue
            raise
        if not j:
            break
        rows += j
        first = min(r["candle_date_time_utc"] for r in j)
        to = first.replace(" ", "T") + "Z"
        k += 1
        if len(j) < 200:
            break
        time.sleep(0.25)
    if not rows:
        raise RuntimeError("upbit returned no rows")
    d = pd.DataFrame(rows)
    return day_series(_days_from_dt(d["candle_date_time_utc"]), pd.to_numeric(d["trade_price"], errors="coerce").to_numpy(dtype=float))

def cot_tff(code):
    """CFTC Traders in Financial Futures (futures only), yearly zips 2018+. Returns DataFrame day, net (lev funds)."""
    frames = []
    yr_now = pd.Timestamp.utcnow().year
    for y in range(2018, yr_now + 1):
        p = CACHE / f"zai20_cot_{y}.zip"
        if not (p.exists() and p.stat().st_size > 1000 and (y < yr_now or cache_fresh(p, 20))):
            try:
                b = http_bytes(f"https://www.cftc.gov/files/dea/history/fut_fin_txt_{y}.zip", timeout=90)
                p.write_bytes(b)
            except Exception as ex:
                print(f"  COT {y}: download failed ({type(ex).__name__}: {str(ex)[:80]})", flush=True)
                if not p.exists():
                    continue
        try:
            with zipfile.ZipFile(p) as z:
                nm = [n for n in z.namelist() if n.lower().endswith(".txt") or n.lower().endswith(".csv")][0]
                d = pd.read_csv(z.open(nm), low_memory=False)
            frames.append(d)
        except Exception as ex:
            print(f"  COT {y}: parse failed ({type(ex).__name__})", flush=True)
    if not frames:
        raise RuntimeError("no COT files")
    d = pd.concat(frames, ignore_index=True)
    cols = {c.lower().strip(): c for c in d.columns}
    def col(*keys):
        for c_l, c in cols.items():
            if all(k in c_l for k in keys):
                return c
        raise KeyError(keys)
    cc = col("contract_market_code")
    dc = col("report_date_as_yyyy")
    lc, sc = col("lev_money_positions_long_all"), col("lev_money_positions_short_all")
    d = d[d[cc].astype(str).str.strip() == str(code)]
    if not len(d):
        raise RuntimeError(f"no rows for code {code}")
    out = pd.DataFrame({"day": _days_from_dt(d[dc]),
                        "net": pd.to_numeric(d[lc], errors="coerce").to_numpy(float) - pd.to_numeric(d[sc], errors="coerce").to_numpy(float)})
    return out.dropna().drop_duplicates("day").sort_values("day").reset_index(drop=True)

def _binance_funding_direct(symbol, start_ms, end_ms):
    rows, t = [], start_ms
    for _ in range(40):
        url = f"https://fapi.binance.com/fapi/v1/fundingRate?symbol={symbol}&startTime={t}&limit=1000"
        j = http_json(url, timeout=30)
        if not j:
            break
        rows += [(int(r["fundingTime"]), float(r["fundingRate"])) for r in j]
        t = int(j[-1]["fundingTime"]) + 1
        if len(j) < 1000 or t >= end_ms:
            break
        time.sleep(0.3)
    return pd.DataFrame(rows, columns=["time", "funding"])

def _bitmex_funding(symbol, end_ms):
    rows, start = [], 0
    for _ in range(40):
        url = (f"https://www.bitmex.com/api/v1/funding?symbol={symbol}&count=500&start={start}&reverse=false"
               "&startTime=2016-01-01")
        j = http_json(url, timeout=30)
        if not j:
            break
        for r in j:
            tt = int(pd.Timestamp(r["timestamp"]).value // 1_000_000)
            if tt < end_ms:
                rows.append((tt, float(r["fundingRate"])))
        start += len(j)
        if len(j) < 500 or int(pd.Timestamp(j[-1]["timestamp"]).value // 1_000_000) >= end_ms:
            break
        time.sleep(2.2)
    return pd.DataFrame(rows, columns=["time", "funding"])

def funding_full(asset, hosted):
    """Payments (time, rate): hosted Binance series, extended back with Binance fapi (2019-09+) and BitMEX (2016+)."""
    p = CACHE / f"zai20_funding_ext_{asset}.csv"
    parts = []
    h = hosted if hosted is not None and len(hosted) else pd.DataFrame(columns=["time", "funding"])
    h = h[["time", "funding"]].copy() if len(h) else h
    first = int(h["time"].min()) if len(h) else ms("2027-01-01")
    ext = None
    if cache_fresh(p, 24 * 7):
        try:
            ext = pd.read_csv(p)
        except Exception:
            ext = None
    if ext is None:
        got = []
        sym = "BTCUSDT" if asset == "btc" else "ETHUSDT"
        try:
            b = _binance_funding_direct(sym, ms("2019-09-01"), first)
            b = b[b["time"] < first]
            if len(b):
                got.append(b); print(f"  funding {asset}: Binance fapi direct {len(b)} rows before the hosted series", flush=True)
        except Exception as ex:
            print(f"  funding {asset}: Binance fapi direct failed ({type(ex).__name__}: {str(ex)[:60]}); hosted only", flush=True)
        first2 = min([first] + [int(g["time"].min()) for g in got if len(g)])
        try:
            bm = _bitmex_funding("XBTUSD" if asset == "btc" else "ETHUSD", first2)
            if len(bm):
                got.append(bm); print(f"  funding {asset}: BitMEX {len(bm)} rows before {pd.Timestamp(first2, unit='ms').date()}", flush=True)
        except Exception as ex:
            print(f"  funding {asset}: BitMEX failed ({type(ex).__name__}: {str(ex)[:60]}); no pre-{pd.Timestamp(first2, unit='ms').date()} funding", flush=True)
        ext = pd.concat(got, ignore_index=True) if got else pd.DataFrame(columns=["time", "funding"])
        try:
            ext.to_csv(p, index=False)
        except Exception:
            pass
    if len(ext):
        parts.append(ext[ext["time"] < first])
    if len(h):
        parts.append(h)
    if not parts:
        return pd.DataFrame(columns=["time", "funding"])
    out = pd.concat(parts, ignore_index=True)
    out["time"] = pd.to_numeric(out["time"]).astype("int64"); out["funding"] = pd.to_numeric(out["funding"], errors="coerce")
    return out.dropna().drop_duplicates("time").sort_values("time").reset_index(drop=True)

# ---------------------------------------------------------------------------
# Q3 (port of live q3.mjs: ATR% <= p10 within 10 days, then 7-day Donchian close breakout, 2xATR stop,
# 15-day trailing low/high, 90-day cap, one position at a time)
# ---------------------------------------------------------------------------
def daily_bars(df1h):
    d = resample_ohlcv(df1h, D1)
    t = d["time"].to_numpy(dtype="int64")
    last = df1h["time"].to_numpy(dtype="int64")[-1]
    if len(t) and last + H1 < t[-1] + D1:
        d = d.iloc[:-1]
    return d.reset_index(drop=True)

def q3_trades(D, W=180, pctv=0.10, arm=10, N=7, trail=15, stopm=2.0, cap=90):
    t = D["time"].to_numpy("int64"); o = D["open"].to_numpy(float); h = D["high"].to_numpy(float)
    l = D["low"].to_numpy(float); c = D["close"].to_numpy(float)
    n = len(c)
    if n < W + 20:
        return []
    A = atr(h, l, c, 14)
    ap = pd.Series(A / c)
    pr = ap.rolling(W, min_periods=W).rank(pct=True).to_numpy()
    comp = np.isfinite(pr) & (pr <= pctv)
    armed = pd.Series(comp.astype(float)).rolling(arm, min_periods=arm).max().to_numpy() > 0
    hh = pd.Series(h).rolling(N, min_periods=N).max().shift(1).to_numpy()
    ll = pd.Series(l).rolling(N, min_periods=N).min().shift(1).to_numpy()
    lvlL = pd.Series(l).rolling(trail, min_periods=trail).min().to_numpy()
    lvlS = pd.Series(h).rolling(trail, min_periods=trail).max().to_numpy()
    sig = np.zeros(n, int)
    sig[armed & (c > hh)] = 1
    sig[armed & (c < ll) & (sig == 0)] = -1
    out, i = [], 0
    while i < n:
        s = sig[i]
        if not s:
            i += 1; continue
        ek = i + 1
        if ek >= n:
            break
        px = o[ek]
        stp0 = px - s * stopm * A[i]
        if not (np.isfinite(stp0) and px > 0 and s * (px - stp0) > 0):
            i += 1; continue
        stp, why, xi, ex = stp0, None, -1, NAN
        for j in range(ek, n):
            if j > ek:
                lv = lvlL[j - 1] if s > 0 else lvlS[j - 1]
                if np.isfinite(lv):
                    stp = max(stp, lv) if s > 0 else min(stp, lv)
            if s > 0:
                if o[j] <= stp: why, xi, ex = "SL", j, o[j]; break
                if l[j] <= stp: why, xi, ex = "SL", j, stp; break
            else:
                if o[j] >= stp: why, xi, ex = "SL", j, o[j]; break
                if h[j] >= stp: why, xi, ex = "SL", j, stp; break
            if j - ek >= cap:
                why, xi, ex = "CAP", j, c[j]; break
        if why is None:
            break
        risk = abs(px - stp0) / px
        ret = s * (ex / px - 1.0) - 2 * COST
        out.append(dict(entry_time=int(t[ek]), exit_time=int(t[xi] + D1 // 2), side=int(s), R=ret / risk, risk=risk, why=why))
        i = max(xi, i + 1)
    return out

# ---------------------------------------------------------------------------
# trades, cut30, maxOpen, compounding (same math as tilt.py)
# ---------------------------------------------------------------------------
def pack(eng, risk_map, day0, nday):
    names = list(eng.keys())
    base = np.array([risk_map.get(nm, 0.01) for nm in names], dtype=float)
    rows = []
    for u, nm in enumerate(names):
        for tr in eng[nm]:
            R, r = tr.get("R", NAN), tr.get("risk", NAN)
            et, xt = tr.get("entry_time", 0), tr.get("exit_time", 0)
            if not (np.isfinite(R) and np.isfinite(r) and r > 0 and et >= T_START and xt >= et):
                continue
            rows.append((int(et), int(xt), float(R), float(r), u, int(tr.get("side", 0))))
    if not rows:
        rows = [(T_START, T_START, 0.0, 1.0, 0, 0)][:0]
    if rows:
        entry, exit, R, risk, unit, side = (np.array(x) for x in zip(*rows))
        o = np.argsort(entry, kind="stable")
        entry, exit, R, risk, unit, side = entry[o], exit[o], R[o], risk[o], unit[o], side[o]
    else:
        entry = exit = np.array([], "int64"); R = risk = np.array([], float); unit = side = np.array([], int)
    fam = np.full(len(R), "", dtype=object)
    for f, mem in FAM.items():
        for nm in mem:
            if nm in names:
                fam[unit == names.index(nm)] = f
    didx = (np.asarray(entry, "int64") // D1) - day0
    didx = np.where((didx >= 0) & (didx < nday), didx, nday)
    return dict(entry=np.asarray(entry, "int64"), exit=np.asarray(exit, "int64"), R=np.asarray(R, float),
                risk=np.asarray(risk, float), unit=np.asarray(unit, int), side=np.asarray(side, int), fam=fam,
                week=week_of(entry), didx=didx.astype(int), names=names, base=base, n=len(R))

def week_grid(P):
    if not P["n"]:
        return np.array([0], dtype="int64")
    w0, w1 = int(P["week"].min()), int(max(P["week"].max(), week_of(P["exit"]).max()))
    return np.arange(w0, w1 + 1, dtype="int64")

def cut30_M(P, W):
    U = len(P["names"])
    M = np.ones((len(W), U))
    starts = week_start(W)
    for u in range(U):
        m = P["unit"] == u
        xt, R = P["exit"][m], P["R"][m]
        o = np.argsort(xt, kind="stable"); xt, R = xt[o], R[o]
        if len(xt) < 30:
            continue
        ii = np.searchsorted(xt, starts, "left")
        for k, i1 in enumerate(ii):
            if i1 >= 30 and pf_of(R[i1 - 30:i1]) < 1.0:
                M[k, u] = 0.0
    return M

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

def empty_stats():
    return dict(ret=NAN, cagr=NAN, dd=NAN, mar=NAN, pf=NAN, n=0, daily=pd.Series(dtype=float))

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

def window_stats(daily, t0, t1):
    if daily is None or not len(daily):
        return empty_stats()
    sl = daily[(daily.index >= t0) & (daily.index < t1)]
    return stats_from(sl.index.to_numpy(), sl.to_numpy()) if len(sl) else empty_stats()

def run_book(B, mtr=None, take_mask=None):
    P, M, W = B["P"], B["M"], B["W"]
    if P["n"] == 0:
        return empty_stats(), np.zeros(0, bool), np.ones(0)
    wi = np.clip(np.searchsorted(W, P["week"]), 0, len(W) - 1)
    m = M[wi, P["unit"]].copy()
    if mtr is not None:
        m = m * mtr
    take = np.isfinite(m) & (m > 0)
    if take_mask is not None:
        take &= take_mask
    take = apply_maxopen(P["entry"], P["exit"], take)
    pnl = P["R"] * np.minimum(P["base"][P["unit"]] * m, P["risk"])
    st = stats_from(P["exit"][take], pnl[take])
    return st, take, m

def enrich(st):
    yrs = {y: window_stats(st["daily"], ms(f"{y}-01-01"), ms(f"{y+1}-01-01"))["ret"] for y in YEARS}
    return dict(st=st, h1=window_stats(st["daily"], T_START, T_SPLIT), h2=window_stats(st["daily"], T_SPLIT, T_END), yrs=yrs)

def beats(e, b, years=YEARS):
    hit = 0
    for y in years:
        a, c = e["yrs"].get(y, NAN), b["yrs"].get(y, NAN)
        if np.isfinite(a) and np.isfinite(c) and a > c:
            hit += 1
        elif np.isfinite(a) and not np.isfinite(c):
            hit += 1
    return hit

def make_book(eng, risk_map, day0, nday, cut=True):
    P = pack(eng, risk_map, day0, nday)
    W = week_grid(P)
    M = cut30_M(P, W) if cut else np.ones((len(W), len(P["names"])))
    B = dict(P=P, W=W, M=M)
    st, take, _m = run_book(B)
    B["st"], B["en"], B["take"] = st, enrich(st), take
    return B

# ---------------------------------------------------------------------------
# forecaster inputs on a calendar-day grid (value for day d = known at the end of UTC day d)
# ---------------------------------------------------------------------------
def on_grid(s, day0, nday, ffill=0):
    out = np.full(nday, NAN)
    if s is None or not len(s):
        return out
    idx = np.asarray(s.index, "int64") - day0
    ok = (idx >= 0) & (idx < nday)
    out[idx[ok]] = np.asarray(s.values, float)[ok]
    if ffill:
        out = pd.Series(out).ffill(limit=ffill).to_numpy()
    return out

def lag(x, L):
    L = int(L)
    if L <= 0:
        return x.copy()
    return np.r_[np.full(L, NAN), x[:-L]]

def dfa_hurst(logret, win=60, scales=(4, 5, 6, 8, 10, 12, 15, 20, 30)):
    x = np.asarray(logret, float)
    n = len(x)
    out = np.full(n, NAN)
    if n < win:
        return out
    from numpy.lib.stride_tricks import sliding_window_view
    Wv = sliding_window_view(np.nan_to_num(x), win)
    okw = sliding_window_view(np.isfinite(x).astype(int), win).sum(1) == win
    Y = np.cumsum(Wv - Wv.mean(1, keepdims=True), axis=1)
    logF, logs = [], []
    for s in scales:
        k = win // s
        if k < 2:
            continue
        seg = Y[:, :k * s].reshape(len(Y), k, s)
        tt = np.arange(s) - (s - 1) / 2.0
        mu = seg.mean(2, keepdims=True)
        b = ((seg - mu) * tt).sum(2, keepdims=True) / (tt @ tt)
        res = seg - mu - b * tt
        F = np.sqrt((res ** 2).mean((1, 2)))
        logF.append(np.log(np.maximum(F, 1e-300))); logs.append(np.log(s))
    LF = np.vstack(logF); ls = np.array(logs); lsc = ls - ls.mean()
    H = ((LF - LF.mean(0)) * lsc[:, None]).sum(0) / (lsc @ lsc)
    H[~okw] = NAN
    out[win - 1:] = H
    return out

def daily_funding_8h(fd, day0, nday):
    """Per-8h equivalent of each UTC day's funding (sum of the day's payments / 3); NaN if < 2 payments."""
    if fd is None or not len(fd):
        return np.full(nday, NAN)
    d = (fd["time"].to_numpy("int64") // D1)
    g = pd.DataFrame({"d": d, "f": fd["funding"].to_numpy(float)}).groupby("d")["f"].agg(["sum", "count"])
    g = g[g["count"] >= 2]
    return on_grid(pd.Series(g["sum"].to_numpy() / 3.0, index=g.index.to_numpy("int64")), day0, nday)

def build_states(asset, Dg, day0, nday, ext):
    c = Dg["close"].to_numpy(float)
    S, LAG, SRC = {}, {}, {}
    S["er20"] = oslib.er(c, 20); LAG["er20"] = 1; SRC["er20"] = "price"
    lr = np.r_[NAN, np.diff(np.log(c))]
    S["hurst"] = dfa_hurst(lr, 60); LAG["hurst"] = 1; SRC["hurst"] = "price"
    f8 = daily_funding_8h(ext.get("fund_" + asset), day0, nday)
    S["fund7"] = pd.Series(f8).rolling(7, min_periods=5).mean().to_numpy(); LAG["fund7"] = 1; SRC["fund7"] = "funding"
    spx, vix = ext.get("spx"), ext.get("vix")
    if spx is not None and len(spx):
        sd = np.asarray(spx.index, "int64"); sv = np.asarray(spx.values, float)
        sret = np.r_[NAN, sv[1:] / sv[:-1] - 1.0]
        k = sd - day0
        ok = (k >= 1) & (k < nday)
        # crypto return over the same span as the SPX return (prior SPX date close -> this date close)
        cz = np.full(len(sd), NAN)
        kk = np.clip(k, 0, nday - 1)
        cz[ok] = c[kk[ok]]
        cret = np.r_[NAN, cz[1:] / cz[:-1] - 1.0]
        cr = pd.Series(sret).rolling(30, min_periods=25).corr(pd.Series(cret)).to_numpy()
        S["corr30"] = on_grid(pd.Series(cr, index=sd), day0, nday, ffill=5)
    else:
        S["corr30"] = np.full(nday, NAN)
    LAG["corr30"] = 1; SRC["corr30"] = "spx"
    if vix is not None and len(vix):
        v20 = pd.Series(np.asarray(vix.values, float)).rolling(20, min_periods=15).mean().to_numpy()
        S["vix20"] = on_grid(pd.Series(v20, index=np.asarray(vix.index, "int64")), day0, nday, ffill=5)
    else:
        S["vix20"] = np.full(nday, NAN)
    LAG["vix20"] = 1; SRC["vix20"] = "vix"
    dx, dlag = ext.get("dxy"), ext.get("dxy_lag", 1)
    if dx is not None and len(dx):
        dv = np.asarray(dx.values, float); di = np.asarray(dx.index, "int64")
        ma50 = pd.Series(dv).rolling(50, min_periods=40).mean().to_numpy()
        cal = on_grid(pd.Series(dv, index=di), day0 - 40, nday + 40, ffill=7)
        r30 = cal[40:] / lag(cal, 30)[40:] - 1.0
        S["dxy30"] = r30
        S["dxy_below"] = on_grid(pd.Series((dv < ma50).astype(float), index=di).where(np.isfinite(ma50)), day0, nday, ffill=7)
    else:
        S["dxy30"] = np.full(nday, NAN); S["dxy_below"] = np.full(nday, NAN)
    LAG["dxy30"] = LAG["dxy_below"] = dlag; SRC["dxy30"] = SRC["dxy_below"] = "dxy"
    mv = ext.get("mvrv_" + asset)
    if mv is not None and len(mv):
        mvd = on_grid(mv, day0 - 1500, nday + 1500, ffill=3)
        pr = pd.Series(mvd).rolling(1460, min_periods=365).rank(pct=True).to_numpy()
        S["mvrv"] = mvd[1500:1500 + nday]; S["mvrv_pct"] = pr[1500:1500 + nday]
    else:
        S["mvrv"] = np.full(nday, NAN); S["mvrv_pct"] = np.full(nday, NAN)
    LAG["mvrv"] = LAG["mvrv_pct"] = 2; SRC["mvrv"] = SRC["mvrv_pct"] = "mvrv"
    L = {k: lag(v, LAG[k]) for k, v in S.items()}
    return dict(raw=S, lagged=L, lagn=LAG, src=SRC)

# flags: name -> (input, test); test on the raw daily value, then optional hold (days), then lag
FLAGS = {
    "er_chop": ("er20", lambda x: x < 0.15), "er_trend": ("er20", lambda x: x > 0.35),
    "h_mr": ("hurst", lambda x: x < 0.45), "h_trend": ("hurst", lambda x: x > 0.55),
    "f_hot": ("fund7", lambda x: x > 0.0004), "f_neg": ("fund7", lambda x: x < 0.0),
    "c_neg": ("corr30", lambda x: x < 0.0), "vix_hi": ("vix20", lambda x: x > 25.0),
    "usd_rip": ("dxy30", lambda x: x > 0.025),
    "mv_hi": ("mvrv_pct", lambda x: x > 0.90), "mv_lo": ("mvrv_pct", lambda x: x < 0.25),
}

def flag_arr(ST, name, hold=0):
    inp, fn = FLAGS[name]
    x = ST["raw"][inp]
    with np.errstate(invalid="ignore"):
        f = np.where(np.isfinite(x), fn(np.nan_to_num(x, nan=0.0)), False).astype(float)
    if hold and hold > 1:
        f = pd.Series(f).rolling(hold, min_periods=1).max().to_numpy()
    f = lag(f, ST["lagn"][inp])
    return np.r_[np.nan_to_num(f, nan=0.0) > 0, False]

# overlays: rules (flag, families or "ALL", side 0=both/+1 long/-1 short, factor), hold days
OVERLAYS = [
    ("A1_ER", [("er_chop", ("TREND",), 0, 0.5)], 0),
    ("A1_ERx", [("er_chop", ("TREND", "BRK"), 0, 0.5), ("er_trend", ("FADE",), 0, 0.5)], 0),
    ("A1_ER_h7", [("er_chop", ("TREND",), 0, 0.5)], 7),
    ("A2_HURST", [("h_mr", ("TREND",), 0, 0.5)], 0),
    ("A2_HURSTx", [("h_mr", ("TREND",), 0, 0.5), ("h_trend", ("FADE",), 0, 0.5)], 0),
    ("A2_HURST_h14", [("h_mr", ("TREND",), 0, 0.5)], 14),
    ("A4_FUND", [("f_hot", ("TREND",), 1, 0.5), ("f_neg", "ALL", -1, 0.5)], 0),
    ("A4_FUNDhotL", [("f_hot", "ALL", 1, 0.5)], 0),
    ("A4_FUND_h7", [("f_hot", ("TREND",), 1, 0.5), ("f_neg", "ALL", -1, 0.5)], 7),
    ("A9_VIX", [("vix_hi", "ALL", 0, 0.7)], 0),
    ("A9_CORR", [("c_neg", ("TREND",), 0, 0.5)], 0),
    ("A10_DXY", [("usd_rip", ("TREND",), 1, 0.5)], 0),
    ("A10_DXYL", [("usd_rip", "ALL", 1, 0.5)], 0),
    ("A10_DXY_h7", [("usd_rip", ("TREND",), 1, 0.5)], 7),
    ("A11_MVRV", [("mv_hi", ("TREND",), 1, 0.5), ("mv_lo", "ALL", -1, 0.5)], 0),
    ("A11_MVRVhiL", [("mv_hi", "ALL", 1, 0.5)], 0),
]

def ov_flags(ST, rules, hold):
    return {r[0]: flag_arr(ST, r[0], hold) for r in rules}

def ov_mult(P, rules, flags, pidx=None):
    m = np.ones(P["n"])
    for fl, fams, side, fac in rules:
        f = flags[fl]
        if pidx is not None:
            f = np.r_[f[:-1][pidx], False]
        hit = f[P["didx"]]
        sel = hit if fams == "ALL" else (hit & np.isin(P["fam"], list(fams)))
        if side:
            sel = sel & (P["side"] == side)
        m = np.where(sel, m * fac, m)
    return m

def block_perm(nday, rng, blk=28):
    blocks = [np.arange(k, min(k + blk, nday)) for k in range(0, nday, blk)]
    order = rng.permutation(len(blocks))
    return np.concatenate([blocks[k] for k in order])[:nday]

# categorical states for section A
def cats(ST):
    L = ST["lagged"]
    def cut3(x, lo, hi, labels):
        out = np.full(len(x), -1)
        ok = np.isfinite(x)
        out[ok & (x < lo)] = 0; out[ok & (x >= lo) & (x <= hi)] = 1; out[ok & (x > hi)] = 2
        return out, labels
    C = {}
    C["A1 ER20"] = cut3(L["er20"], 0.15, 0.35, ("chop<.15", "mid", "trend>.35"))
    C["A2 Hurst60"] = cut3(L["hurst"], 0.45, 0.55, ("MR<.45", "mid", "trend>.55"))
    C["A4 fund7/8h"] = cut3(L["fund7"], 0.0, 0.0004, ("neg<0", "mid", "hot>.04%"))
    C["A9 corrSPX30"] = cut3(L["corr30"], 0.0, 0.5, ("<0", "mid", ">0.5"))
    v = L["vix20"]; o = np.full(len(v), -1); ok = np.isfinite(v); o[ok] = (v[ok] > 25).astype(int)
    C["A9 VIX20"] = (o, ("<=25", ">25"))
    r, b = L["dxy30"], L["dxy_below"]; o = np.full(len(r), -1)
    ok = np.isfinite(r) & np.isfinite(b)
    o[ok] = 2; o[ok & (b > 0.5)] = 0; o[ok & (r > 0.025)] = 1
    C["A10 DXY"] = (o, ("below50MA", "rip>2.5%", "other"))
    C["A11 MVRVpct"] = cut3(L["mvrv_pct"], 0.25, 0.90, ("<p25", "mid", ">p90"))
    return C

def section_A(asset, B, ST, day0, nday):
    P = B["P"]
    print(f"\n=== A) {asset.upper()} next-4-week PF by state (state = prior day; trades entered in the 4 weeks after each Monday; shadow trades) ===", flush=True)
    print(f"  {'forecaster':<13} {'state':<11} {'wks':>4} {'TREND':>11} {'TREND-L':>11} {'FADE':>11} {'BRK':>11} {'ALL':>11}", flush=True)
    if not P["n"]:
        print("  no trades", flush=True); return
    ent = P["entry"]
    mons = week_start(np.arange(week_of(max(ent.min(), T_START)), week_of(ent.max()) + 1))
    i0s, i1s = np.searchsorted(ent, mons), np.searchsorted(ent, mons + 28 * D1)
    mi = np.clip(mons // D1 - day0, 0, nday - 1)
    famsel = {"TREND": P["fam"] == "TREND", "TREND-L": (P["fam"] == "TREND") & (P["side"] > 0),
              "FADE": P["fam"] == "FADE", "BRK": P["fam"] == "BRK", "ALL": np.ones(P["n"], bool)}
    for fname, (arr, labels) in cats(ST).items():
        st = arr[mi]
        for k, lab in enumerate(labels):
            wk = np.flatnonzero(st == k)
            if not len(wk):
                print(f"  {fname:<13} {lab:<11} {0:>4}", flush=True); continue
            idx = np.concatenate([np.arange(i0s[w], i1s[w]) for w in wk]) if len(wk) else np.array([], int)
            cells = []
            for fk, msk in famsel.items():
                sel = idx[msk[idx]] if len(idx) else idx
                pf = pf_of(P["R"][sel])
                cells.append(f"{f2(pf):>5}({len(np.unique(sel)):>4})")
                rec("A", asset, f"{fname}|{lab}", f"pf_{fk}", pf)
            print(f"  {fname:<13} {lab:<11} {len(wk):>4} " + " ".join(f"{c:>11}" for c in cells), flush=True)
    print("  cells: PF(unique trades). A trade can sit in up to 4 overlapping windows, so PF counts it once per window.", flush=True)

# ---------------------------------------------------------------------------
# B) overlays on the cut30 baseline
# ---------------------------------------------------------------------------
HDR_B = (f"  {'overlay':<14} {'n':>5} {'PF':>5} {'ret%':>9} {'maxDD%':>7} {'MAR':>5} {'MAR1':>5} {'MAR2':>5} "
         f"{'yrB':>5} {'ETH MAR':>7} {'yrE':>5} {'plc':>4} {'acts%':>5}  verdict")

def act_info(P, m):
    ch = np.isfinite(m) & (np.abs(m - 1.0) > 1e-9)
    et = P["entry"][ch]
    halves = (bool(((et >= T_START) & (et < T_SPLIT)).any()), bool((et >= T_SPLIT).any()))
    yrs = [y for y in YEARS if ((et >= ms(f"{y}-01-01")) & (et < ms(f"{y+1}-01-01"))).any()]
    return halves, yrs, (float(ch.mean()) if len(ch) else NAN)

def row_line(name, b, e, base_b, plc, yb, ye, actp, verd):
    s = b["st"]
    return (f"  {name:<14} {s['n']:>5} {f2(s['pf']):>5} {pc(s['ret']):>9} {pc(s['dd']):>7} {f2(s['mar']):>5} "
            f"{f2(b['h1']['mar']):>5} {f2(b['h2']['mar']):>5} {yb:>5} {f2(e['st']['mar']) if e else 'n/a':>7} {ye:>5} "
            f"{f2(plc, 0):>4} {pc(actp, 0):>5}  {verd}")

def section_B(ctx):
    print("\n=== B) FORECASTER OVERLAYS on the live basket WITH cut30 (x0.5 on the named family/side in the bad state) ===", flush=True)
    for a in ctx["assets"]:
        st = ctx[a]["B"]["st"]
        print(f"  {a.upper()} baseline (live + cut30): n {st['n']} PF {f2(st['pf'])} ret {pc(st['ret'])}% maxDD {pc(st['dd'])}% MAR {f2(st['mar'])}"
              f" | MAR 17-20 {f2(ctx[a]['B']['en']['h1']['mar'])} 21-26 {f2(ctx[a]['B']['en']['h2']['mar'])}", flush=True)
    print(HDR_B, flush=True)
    bb = ctx["btc"]["B"]; be = ctx["eth"]["B"] if "eth" in ctx["assets"] else None
    for name, rules, hold in OVERLAYS:
        try:
            res = {}
            for a in ctx["assets"]:
                B, ST = ctx[a]["B"], ctx[a]["ST"]
                fl = ov_flags(ST, rules, hold)
                m = ov_mult(B["P"], rules, fl)
                st, take, _ = run_book(B, m)
                res[a] = dict(en=enrich(st), act=act_info(B["P"], m), fl=fl)
            b = res["btc"]["en"]; e = res["eth"]["en"] if "eth" in res else None
            halves, yrs, actp = res["btc"]["act"]
            P, nday = bb["P"], ctx["btc"]["nday"]
            rng = np.random.default_rng(SEED + sum(ord(ch) for ch in name))
            arr = np.full(ctx["n_plc"], NAN)
            if actp and np.isfinite(actp) and actp > 0:
                for r in range(ctx["n_plc"]):
                    mp = ov_mult(P, rules, res["btc"]["fl"], block_perm(nday, rng))
                    arr[r] = run_book(bb, mp)[0]["mar"]
            fin = arr[np.isfinite(arr)]
            plc = 100.0 * float(np.mean(fin < b["st"]["mar"])) if len(fin) and np.isfinite(b["st"]["mar"]) else NAN
            fails = []
            bh = (bb["en"]["h1"]["mar"], bb["en"]["h2"]["mar"])
            if not any(halves):
                fails.append("inactive")
            for k, (hk, act) in enumerate(zip(("h1", "h2"), halves)):
                if act and not (np.isfinite(b[hk]["mar"]) and np.isfinite(bh[k]) and b[hk]["mar"] > bh[k]):
                    fails.append("half" + str(k + 1))
            hb = beats(b, bb["en"], yrs)
            need_b = math.ceil(5 * len(yrs) / 7) if yrs else 99
            if hb < need_b:
                fails.append("yrsBTC")
            if e is not None:
                yrs_e = res["eth"]["act"][1]
                he = beats(e, be["en"], yrs_e)
                need_e = math.ceil(4 * len(yrs_e) / 7) if yrs_e else 0
                if yrs_e and he < need_e:
                    fails.append("yrsETH")
                ye = f"{he}/{len(yrs_e)}"
            else:
                ye = "n/a"
            if not (np.isfinite(plc) and plc >= 90):
                fails.append("placebo")
            if not (np.isfinite(b["st"]["dd"]) and b["st"]["dd"] >= bb["st"]["dd"] - 0.03):
                fails.append("DD")
            verd = "KEEP_LIVE" if not fails else "NO (" + ",".join(fails) + ")"
            print(row_line(name, b, e, bb["en"], plc, f"{hb}/{len(yrs)}", ye, actp, verd), flush=True)
            for mt, v in (("mar", b["st"]["mar"]), ("ret", b["st"]["ret"]), ("dd", b["st"]["dd"]), ("mar1", b["h1"]["mar"]),
                          ("mar2", b["h2"]["mar"]), ("yrs_btc", hb), ("placebo", plc), ("eth_mar", e["st"]["mar"] if e else NAN),
                          ("keep", 1.0 if verd == "KEEP_LIVE" else 0.0)):
                rec("B", "btc", name, mt, v)
            VERD.append(("overlay", name, verd, f"MAR {f2(b['st']['mar'])} vs {f2(bb['st']['mar'])}, DD {pc(b['st']['dd'])}% vs {pc(bb['st']['dd'])}%, plc {f2(plc,0)}"))
        except Exception as ex:
            print(f"  {name} ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=2)
    print("  MAR1 = 2017-20, MAR2 = 2021-26. yrB/yrE = years beaten / years where the overlay changed a trade. "
          "acts% = share of shadow trades it resized. Placebo: BTC, flags shuffled in 28-day blocks.", flush=True)

# ---------------------------------------------------------------------------
# C) new engines on daily bars (entry at the next UTC day open; costs 0.12%/side)
# ---------------------------------------------------------------------------
def _tr(et, xt, side, entry, exit_px, stop_frac, why):
    risk = max(float(stop_frac), 1e-4)
    ret = side * (exit_px / entry - 1.0) - 2 * COST
    return dict(entry_time=int(et), exit_time=int(xt), side=int(side), R=ret / risk, risk=risk, why=why)

def walk_exit(Dg, ek, side, entry, stop, cond_exit=None, max_days=None):
    """Daily walk from day ek. Stop checked intraday (gap -> open). cond_exit(j) True -> exit at open of j. max_days -> exit at open of ek + max_days. Returns (xi, exit_px, why, exit_time)."""
    t = Dg["time"].to_numpy("int64"); o = Dg["open"].to_numpy(float); h = Dg["high"].to_numpy(float); l = Dg["low"].to_numpy(float)
    n = len(t)
    for j in range(ek, n):
        if j > ek:
            if max_days is not None and j - ek >= max_days:
                return j, o[j], "TIME", t[j]
            if cond_exit is not None and cond_exit(j):
                return j, o[j], "RULE", t[j]
        if side > 0:
            if o[j] <= stop: return j, o[j], "SL", t[j]
            if l[j] <= stop: return j, stop, "SL", t[j] + D1 // 2
        else:
            if o[j] >= stop: return j, o[j], "SL", t[j]
            if h[j] >= stop: return j, stop, "SL", t[j] + D1 // 2
    return None

def eng_B1(Dg, fd, day0, nday):
    """Funding carry: 3d avg funding >= 0.06%/8h -> long spot + short perp from the next day open; exit when 3d avg < 0.02%/8h (next open) or 30 days. PnL = funding paid in the hold - 4 legs x 0.12%."""
    if fd is None or not len(fd):
        return []
    f8 = daily_funding_8h(fd, day0, nday)
    a3 = pd.Series(f8).rolling(3, min_periods=3).mean().to_numpy()
    ft, fr = fd["time"].to_numpy("int64"), fd["funding"].to_numpy(float)
    cs = np.r_[0.0, np.cumsum(fr)]
    t = Dg["time"].to_numpy("int64")
    out, i = [], 0
    while i < nday - 1:
        if not (np.isfinite(a3[i]) and a3[i] >= 0.0006):
            i += 1; continue
        ek = i + 1
        xk = None
        for j in range(ek, min(nday, ek + 30)):
            if np.isfinite(a3[j]) and a3[j] < 0.0002:
                xk = j + 1; break
        if xk is None:
            xk = ek + 30
        if xk >= nday:
            break
        et, xt = t[ek], t[xk]
        i0, i1 = np.searchsorted(ft, et, "right"), np.searchsorted(ft, xt, "left")
        net = float(cs[i1] - cs[i0]) - 4 * COST
        out.append(dict(entry_time=int(et), exit_time=int(xt), side=0, R=net / B1_RREF, risk=B1_RREF, why="carry"))
        i = xk
    return out

def eng_B4(Dg, cot, day0, nday):
    """COT contrarian: lev-funds net < 20th pct of trailing 104 reports AND close > 200d MA -> long at the Monday open after the Friday release; exit when pct > 50 (Monday open), 21 days, or stop 2 x weekly ATR14 (capped 10%)."""
    if cot is None or not len(cot):
        return []
    c = Dg["close"].to_numpy(float); o = Dg["open"].to_numpy(float); t = Dg["time"].to_numpy("int64")
    ma200 = pd.Series(c).rolling(200, min_periods=200).mean().to_numpy()
    pct = pd.Series(cot["net"].to_numpy(float)).rolling(104, min_periods=52).rank(pct=True).to_numpy()
    rd = cot["day"].to_numpy("int64")
    # available from the first Monday on or after report day + 4 (release Friday 15:30 ET)
    avail = rd + 4
    avail = avail + ((0 - ((avail + 3) % 7)) % 7)   # day number d is Monday when (d + 3) % 7 == 0
    pa = np.full(nday, NAN)
    for k in range(len(rd)):
        j = int(avail[k] - day0)
        if 0 <= j < nday and np.isfinite(pct[k]):
            pa[j] = pct[k]
    pa_ff = pd.Series(pa).ffill(limit=13).to_numpy()
    Wb = Dg.assign(w=(Dg["time"] // D1 + 3) // 7).groupby("w").agg(high=("high", "max"), low=("low", "min"), close=("close", "last"))
    watr = atr(Wb["high"].to_numpy(float), Wb["low"].to_numpy(float), Wb["close"].to_numpy(float), 14)
    wmap = dict(zip(Wb.index.to_numpy("int64"), watr))
    is_mon = ((t // D1) + 3) % 7 == 0
    out, i = [], 1
    while i < nday:
        if not (is_mon[i] and np.isfinite(pa[i]) and pa[i] < 0.20 and np.isfinite(ma200[i - 1]) and c[i - 1] > ma200[i - 1]):
            i += 1; continue
        wk = int((t[i] // D1 + 3) // 7) - 1
        wa = wmap.get(wk, NAN)
        if not np.isfinite(wa):
            i += 1; continue
        entry = o[i]
        dist = min(2.0 * wa, 0.10 * entry)
        stop = entry - dist
        r = walk_exit(Dg, i, 1, entry, stop, cond_exit=lambda j: is_mon[j] and np.isfinite(pa[j]) and pa[j] > 0.50, max_days=21)
        if r is None:
            break
        xi, px, why, xt = r
        out.append(_tr(t[i], xt, 1, entry, px, dist / entry, why))
        i = max(xi, i + 1)
    return out

def eng_B5(Dg, mv_lagged, nday):
    """MVRV floor: tranche 1 when MVRV < 1.0, tranche 2 (while 1 is open) when < 0.9; exit MVRV > 1.35, 30 days, or stop 3 x ATR14 (capped 10%). MVRV lagged 2 days (state already lagged: enter at that day's open)."""
    c = Dg["close"].to_numpy(float); o = Dg["open"].to_numpy(float); t = Dg["time"].to_numpy("int64")
    A = atr(Dg["high"].to_numpy(float), Dg["low"].to_numpy(float), c, 14)
    x = mv_lagged
    out = []
    for thr, tag in ((1.0, "T1"), (0.9, "T2")):
        i, t1_busy = 1, None
        while i < nday:
            if not (np.isfinite(x[i]) and x[i] < thr and np.isfinite(A[i - 1])):
                i += 1; continue
            if tag == "T2" and not any(tr["why"].startswith("T1") and tr["entry_time"] <= t[i] < tr["exit_time"] for tr in out if tr["why"].startswith("T1")):
                i += 1; continue
            entry = o[i]
            dist = min(3.0 * A[i - 1], 0.10 * entry)
            r = walk_exit(Dg, i, 1, entry, entry - dist, cond_exit=lambda j: np.isfinite(x[j]) and x[j] > 1.35, max_days=30)
            if r is None:
                break
            xi, px, why, xt = r
            tr = _tr(t[i], xt, 1, entry, px, dist / entry, tag + "_" + why)
            out.append(tr)
            i = max(xi, i + 1)
    return sorted(out, key=lambda d: d["entry_time"])

def eng_B3(Dg, prem, nday):
    """Kimchi fade: premium >= 4% on 2 consecutive days -> short at the next open; exit premium < 1.5% or > 8% (next open), 5 days, or stop 3 x ATR14 (capped 10%)."""
    c = Dg["close"].to_numpy(float); o = Dg["open"].to_numpy(float); t = Dg["time"].to_numpy("int64")
    A = atr(Dg["high"].to_numpy(float), Dg["low"].to_numpy(float), c, 14)
    p = prem
    out, i = [], 1
    while i < nday - 1:
        if not (np.isfinite(p[i]) and np.isfinite(p[i - 1]) and p[i] >= 0.04 and p[i - 1] >= 0.04 and np.isfinite(A[i])):
            i += 1; continue
        ek = i + 1
        entry = o[ek]
        dist = min(3.0 * A[i], 0.10 * entry)
        r = walk_exit(Dg, ek, -1, entry, entry + dist,
                      cond_exit=lambda j: np.isfinite(p[j - 1]) and (p[j - 1] < 0.015 or p[j - 1] > 0.08), max_days=5)
        if r is None:
            break
        xi, px, why, xt = r
        out.append(_tr(t[ek], xt, -1, entry, px, dist / entry, why))
        i = max(xi, ek)
    return out

def eng_stats(trs, B, day0, first_day):
    R = np.array([t["R"] for t in trs], float)
    et = np.array([t["entry_time"] for t in trs], "int64")
    n = len(R)
    yrs = max(0.25, (B["P"]["exit"].max() - max(first_day, T_START)) / (365.25 * D1)) if B["P"]["n"] else NAN
    h1 = pf_of(R[et < T_SPLIT]) if n else NAN
    h2 = pf_of(R[et >= T_SPLIT]) if n else NAN
    pnl = pd.Series([t["R"] * min(ADD_RISK, t["risk"]) for t in trs],
                    index=[week_of(t["exit_time"]) for t in trs], dtype=float).groupby(level=0).sum()
    bd = B["st"]["daily"]
    bw = pd.Series(bd.to_numpy(), index=week_of(bd.index.to_numpy())).groupby(level=0).sum() if len(bd) else pd.Series(dtype=float)
    corr = NAN
    if n >= 5 and len(bw):
        w0 = max(int(bw.index.min()), int(week_of(max(first_day, T_START))))
        idx = np.arange(w0, int(bw.index.max()) + 1)
        a, b = pnl.reindex(idx).fillna(0.0).to_numpy(), bw.reindex(idx).fillna(0.0).to_numpy()
        if a.std() > 0 and b.std() > 0:
            corr = float(np.corrcoef(a, b)[0, 1])
    return dict(n=n, pf=pf_of(R), h1=h1, h1n=int((et < T_SPLIT).sum()), h2=h2, h2n=int((et >= T_SPLIT).sum()),
                tpy=n / yrs if np.isfinite(yrs) else NAN, avgR=float(np.nanmean(R)) if n else NAN, corr=corr)

def section_C(ctx):
    print("\n=== C) NEW ENGINES: standalone (R after costs) + ADD_SMALL at 0.5% risk on the cut30 baseline ===", flush=True)
    print(f"  {'engine':<9} {'asset':<4} {'n':>4} {'PF':>5} {'PF17-20':>9} {'PF21-26':>9} {'tr/yr':>6} {'avgR':>6} {'corrW':>6} | "
          f"{'ADD MAR':>7} {'base':>5} {'MAR1':>5} {'MAR2':>5} {'DD%':>6} {'baseDD':>6} {'yrs':>4}  verdict", flush=True)
    for a in ctx["assets"]:
        c = ctx[a]
        Dg, day0, nday, ext, ST, B = c["Dg"], c["day0"], c["nday"], ctx["ext"], c["ST"], c["B"]
        specs = []
        fd = ext.get("fund_" + a)
        specs.append(("B1_CARRY", lambda: eng_B1(Dg, fd, day0, nday), int(fd["time"].min() // D1) if fd is not None and len(fd) else None))
        cot = ext.get("cot_" + a)
        specs.append(("B4_COT", lambda: eng_B4(Dg, cot, day0, nday), int(cot["day"].min()) + 365 if cot is not None and len(cot) else None))
        mvok = np.isfinite(ST["lagged"]["mvrv"]).any()
        specs.append(("B5_MVRV", lambda: eng_B5(Dg, ST["lagged"]["mvrv"], nday), day0 if mvok else None))
        prem = c.get("prem")
        fp = np.flatnonzero(np.isfinite(prem)) if prem is not None else np.array([], int)
        specs.append(("B3_KIMCHI", lambda: eng_B3(Dg, prem, nday), day0 + int(fp[0]) if len(fp) else None))
        for name, fn, first_day in specs:
            try:
                if first_day is None:
                    print(f"  {name:<9} {a:<4} skipped: data unavailable", flush=True)
                    VERD.append(("engine", f"{name} {a.upper()}", "SKIPPED (no data)", ""))
                    continue
                trs = [t for t in fn() if t["entry_time"] >= T_START]
                es = eng_stats(trs, B, day0, first_day * D1)
                eng2 = dict(c["eng"]); eng2[name] = trs
                rm = dict(LIVE); rm[name] = ADD_RISK
                B2 = make_book(eng2, rm, day0, nday, cut=True)
                b2, bb = B2["en"], B["en"]
                fails = []
                for k, hk in enumerate(("h1", "h2")):
                    act = es["h1n"] > 0 if k == 0 else es["h2n"] > 0
                    if act and not (np.isfinite(b2[hk]["mar"]) and np.isfinite(bb[hk]["mar"]) and b2[hk]["mar"] >= bb[hk]["mar"]):
                        fails.append("half" + str(k + 1))
                if es["n"] == 0:
                    fails.append("no trades")
                if not (np.isfinite(b2["st"]["dd"]) and b2["st"]["dd"] >= bb["st"]["dd"] - 0.03):
                    fails.append("DD")
                hy = beats(b2, bb)
                if hy < 4:
                    fails.append("yrs")
                verd = "ADD_SMALL" if not fails else "NO (" + ",".join(fails) + ")"
                if a != "btc":
                    verd = "info: " + verd
                print(f"  {name:<9} {a:<4} {es['n']:>4} {f2(es['pf']):>5} {f2(es['h1']):>5}({es['h1n']:>2}) {f2(es['h2']):>5}({es['h2n']:>2}) "
                      f"{f2(es['tpy'],1):>6} {f2(es['avgR']):>6} {f2(es['corr']):>6} | {f2(b2['st']['mar']):>7} {f2(bb['st']['mar']):>5} "
                      f"{f2(b2['h1']['mar']):>5} {f2(b2['h2']['mar']):>5} {pc(b2['st']['dd']):>6} {pc(bb['st']['dd']):>6} {hy:>2}/7  {verd}", flush=True)
                for mt, v in (("n", es["n"]), ("pf", es["pf"]), ("pf_h1", es["h1"]), ("pf_h2", es["h2"]), ("tpy", es["tpy"]),
                              ("corrW", es["corr"]), ("add_mar", b2["st"]["mar"]), ("add_dd", b2["st"]["dd"]), ("add_yrs", hy)):
                    rec("C", a, name, mt, v)
                VERD.append(("engine", f"{name} {a.upper()}", verd, f"n {es['n']} PF {f2(es['pf'])} ({f2(es['h1'])}/{f2(es['h2'])}) "
                             f"{f2(es['tpy'],1)}/yr corr {f2(es['corr'])}; basket MAR {f2(b2['st']['mar'])} vs {f2(bb['st']['mar'])}"))
            except Exception as ex:
                print(f"  {name} {a} ERROR {type(ex).__name__}: {ex}", flush=True)
                traceback.print_exc(limit=2)
    print("  PFxx(n) = PF and trade count by entry half. corrW = weekly PnL corr to the baseline basket. "
          "B1 R = net carry / 2% notional (0.5% risk = 25% notional, needs a spot leg). Stops capped at 10% like live.", flush=True)

# ---------------------------------------------------------------------------
# data assembly
# ---------------------------------------------------------------------------
def grid_daily(df1h):
    D = daily_bars(df1h)
    d = (D["time"].to_numpy("int64") // D1)
    day0, day1 = int(d[0]), int(d[-1])
    grid = np.arange(day0, day1 + 1)
    G = D.assign(d=d).set_index("d").reindex(grid)
    cl = G["close"].ffill()
    for k in ("open", "high", "low"):
        G[k] = G[k].fillna(cl)
    G["close"] = cl
    G["volume"] = G["volume"].fillna(0.0)
    G["time"] = grid * D1
    return G.reset_index(drop=True)[["time", "open", "high", "low", "close", "volume"]], day0, len(grid)

def load_ext(hosted_fund):
    ext = {}
    for a in ("btc", "eth"):
        try:
            ext["fund_" + a] = funding_full(a, hosted_fund.get(a))
            fd = ext["fund_" + a]
            print(f"  funding {a}: {len(fd):,} payments from {pd.Timestamp(int(fd['time'].min()), unit='ms').date() if len(fd) else 'n/a'}", flush=True)
        except Exception as ex:
            print(f"  funding {a}: FAILED ({type(ex).__name__}: {ex})", flush=True); ext["fund_" + a] = None
    def yf_or_none(tk):
        try:
            return yf_close(tk)
        except Exception as ex:
            print(f"  yfinance {tk}: {type(ex).__name__}: {str(ex)[:80]}", flush=True)
            return None
    ext["spx"] = cached_series("spx", lambda: yf_or_none("^GSPC"))
    ext["vix"] = cached_series("vix", lambda: yf_or_none("^VIX"))
    dx = cached_series("dxy", lambda: yf_or_none("DX-Y.NYB"))
    ext["dxy_lag"] = 1
    if dx is None or len(dx) < 500:
        dx = cached_series("dxy_fred", lambda: fred_csv("DTWEXBGS"))
        ext["dxy_lag"] = 7
        if dx is not None:
            note("DXY from FRED DTWEXBGS (broad index), lagged 7 days for the weekly release")
    ext["dxy"] = dx
    for a in ("btc", "eth"):
        ext["mvrv_" + a] = cached_series("mvrv_" + a, lambda a=a: coinmetrics_mvrv(a))
    for a, code in (("btc", "133741"), ("eth", "146021")):
        p = CACHE / f"zai20_cotnet_{a}.csv"
        try:
            ext["cot_" + a] = cot_tff(code)
            ext["cot_" + a].to_csv(p, index=False)
        except Exception as ex:
            if p.exists():
                ext["cot_" + a] = pd.read_csv(p); print(f"  COT {a}: using cached copy ({type(ex).__name__})", flush=True)
            else:
                ext["cot_" + a] = None; print(f"  COT {a}: FAILED ({type(ex).__name__}: {str(ex)[:80]})", flush=True)
    for a, mk in (("btc", "KRW-BTC"), ("eth", "KRW-ETH")):
        ext["upbit_" + a] = cached_series("upbit_" + a, lambda mk=mk: upbit_daily(mk))
    krw = cached_series("usdkrw", lambda: yf_or_none("KRW=X"))
    if krw is None or len(krw) < 500:
        krw = cached_series("usdkrw2", lambda: yf_or_none("USDKRW=X"))
    ext["usdkrw"] = krw
    for k in ("spx", "vix", "dxy", "mvrv_btc", "mvrv_eth", "upbit_btc", "upbit_eth", "usdkrw"):
        s = ext.get(k)
        if s is None or not len(s):
            note(f"{k}: no data (dependent tests skipped or neutral)")
        else:
            print(f"  {k}: {len(s):,} days from {pd.Timestamp(int(s.index[0]) * D1, unit='ms').date()}", flush=True)
    for k in ("cot_btc", "cot_eth"):
        s = ext.get(k)
        if s is None or not len(s):
            note(f"{k}: no data")
        else:
            print(f"  {k}: {len(s)} weekly reports from {pd.Timestamp(int(s['day'].min()) * D1, unit='ms').date()}", flush=True)
    return ext

def smoke_ext(raw):
    rng = np.random.default_rng(5)
    ext = {}
    for a in ("btc", "eth"):
        df = raw[a]
        t = np.arange(df["time"].iloc[0], df["time"].iloc[-1], 8 * H1)
        fr = 0.0001 + 0.0004 * np.sin(np.arange(len(t)) / 90.0) + rng.normal(0, 0.0002, len(t))
        ext["fund_" + a] = pd.DataFrame({"time": t.astype("int64"), "funding": fr})
        D = daily_bars(df)
        d = D["time"].to_numpy("int64") // D1; c = D["close"].to_numpy(float)
        sma = pd.Series(c).rolling(365, min_periods=30).mean().bfill().to_numpy()
        ext["mvrv_" + a] = day_series(d, c / sma * 1.1)
        ext["upbit_" + a] = day_series(d, c * 1300.0 * (1 + 0.03 + 0.03 * np.sin(np.arange(len(d)) / 20.0)))
        wk = d[(d + 3) % 7 == 5][::1]
        ext["cot_" + a] = pd.DataFrame({"day": wk, "net": np.cumsum(rng.normal(0, 100, len(wk)))})
    d0, d1 = int(raw["btc"]["time"].iloc[0] // D1) - 400, int(raw["btc"]["time"].iloc[-1] // D1)
    days = np.arange(d0, d1 + 1); bd = days[(days + 3) % 7 < 5]
    ext["spx"] = day_series(bd, 3000 * np.exp(np.cumsum(rng.normal(0.0003, 0.01, len(bd)))))
    ext["vix"] = day_series(bd, 18 + 8 * np.abs(np.sin(np.arange(len(bd)) / 60.0)))
    ext["dxy"] = day_series(bd, 95 * np.exp(np.cumsum(rng.normal(0, 0.004, len(bd))))); ext["dxy_lag"] = 1
    ext["usdkrw"] = day_series(days, np.full(len(days), 1300.0))
    return ext

def main(smoke=False):
    global N_PLC
    print("SKIPPED (short history or deferred): A3 DVOL-VRP, A5 OI trend, A6 BTC dominance, A7 stablecoin supply, A8 ETF flows, "
          "A12 fee stress, B2 basis convergence, B6 stablecoin refuel, B7 ETF absorption, B8 alt-season RV.", flush=True)
    ctx = {"assets": ("btc", "eth"), "n_plc": N_PLC}
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        n = int(os.environ.get("ZAI_SMOKE_N", str(24 * 1500)))
        raw = {"btc": synthetic_1h(n=n, seed=9, start="2017-07-01"), "eth": synthetic_1h(n=n, seed=21, start="2017-07-01", px0=300.0)}
        rawf = {"btc": None, "eth": None}
        ext = smoke_ext(raw)
        ctx["n_plc"] = int(os.environ.get("ZAI_SMOKE_PLC", "20"))
    else:
        raw, rawf = {}, {}
        for a in ("btc", "eth"):
            raw[a] = load(a, "1h")
            try:
                rawf[a] = funding(a, "binance")
            except Exception as ex:
                print(f"  funding {a} (hosted) failed ({type(ex).__name__}); engines without funding", flush=True)
                rawf[a] = None
        ext = load_ext(rawf)
    ctx["ext"] = ext
    print(f"  data ready ({time.time()-T0:.0f}s)", flush=True)
    for a in ("btc", "eth"):
        print(f"  building {a.upper()} engines + Q3...", flush=True)
        try:
            Dg, day0, nday = grid_daily(raw[a])
            try:
                eng = engines(raw[a], fund=rawf[a])
            except Exception as ex:
                print(f"    engines() error {type(ex).__name__}: {ex}", flush=True); traceback.print_exc(limit=2); eng = {}
            eng = dict(eng)
            eng["Q3"] = q3_trades(daily_bars(raw[a]))
            B = make_book(eng, LIVE, day0, nday, cut=True)
            B0 = make_book(eng, LIVE, day0, nday, cut=False)
            ST = build_states(a, Dg, day0, nday, ext)
            prem = None
            up, krw = ext.get("upbit_" + a), ext.get("usdkrw")
            if up is not None and krw is not None and len(up) and len(krw):
                u = on_grid(up, day0, nday); k = on_grid(krw, day0, nday, ffill=5)
                prem = (u / k) / Dg["close"].to_numpy(float) - 1.0
            ctx[a] = dict(Dg=Dg, day0=day0, nday=nday, eng=eng, B=B, B0=B0, ST=ST, prem=prem)
            P = B["P"]
            print("    shadow trades " + " ".join(f"{nm} {int((P['unit']==i).sum())}" for i, nm in enumerate(P["names"])) + f" (n {P['n']})", flush=True)
            for k in ("er20", "hurst", "fund7", "corr30", "vix20", "dxy30", "mvrv_pct"):
                x = ST["raw"][k]; ok = np.flatnonzero(np.isfinite(x))
                if len(ok):
                    print(f"    {k:<8} from {pd.Timestamp(int((day0 + ok[0]) * D1), unit='ms').date()} last {x[ok[-1]]:.4g}", flush=True)
                else:
                    print(f"    {k:<8} unavailable (neutral)", flush=True)
        except Exception as ex:
            print(f"  BUILD {a} ERROR {type(ex).__name__}: {ex}", flush=True); traceback.print_exc(limit=3)
            if a == "btc":
                return
            ctx["assets"] = ("btc",)
    print(f"  ({time.time()-T0:.0f}s)", flush=True)
    for a in ctx["assets"]:
        s0, s1 = ctx[a]["B0"]["st"], ctx[a]["B"]["st"]
        print(f"  {a.upper()} static (no cut30): MAR {f2(s0['mar'])} ret {pc(s0['ret'])}% DD {pc(s0['dd'])}%  |  with cut30: MAR {f2(s1['mar'])} "
              f"ret {pc(s1['ret'])}% DD {pc(s1['dd'])}%", flush=True)
    for fn in (lambda: [section_A(a, ctx[a]["B"], ctx[a]["ST"], ctx[a]["day0"], ctx[a]["nday"]) for a in ctx["assets"]],
               lambda: section_B(ctx), lambda: section_C(ctx)):
        try:
            fn()
        except Exception as ex:
            print(f"SECTION ERROR {type(ex).__name__}: {ex}", flush=True); traceback.print_exc(limit=3)
        print(f"  ({time.time()-T0:.0f}s)", flush=True)
    print("\n=== VERDICTS ===", flush=True)
    for kind, name, verd, info in VERD:
        print(f"  {kind:<7} {name:<16} {verd:<30} {info}", flush=True)
    keeps = [n for k, n, v, _ in VERD if v == "KEEP_LIVE"]
    adds = [n for k, n, v, _ in VERD if v == "ADD_SMALL"]
    print(f"  Overlays passing every KEEP_LIVE gate: {', '.join(keeps) if keeps else 'none'}", flush=True)
    print(f"  Engines passing ADD_SMALL (BTC): {', '.join(adds) if adds else 'none'}", flush=True)
    for s in NOTES:
        print("  note: " + s, flush=True)
    out = CACHE / ("zai20_smoke.csv" if smoke else "zai20.csv")
    pd.DataFrame(ROWS).to_csv(out, index=False)
    print(f"\nSaved {out} ({len(ROWS)} rows). Total {time.time()-T0:.0f}s", flush=True)

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