# ===== rotation.py - do edges die, or do they rotate across hours / sessions / weekdays / week-of-month? =====
# Colab:  !wget -q -O rotation.py https://osom-boba.pages.dev/colab/rotation.py
#         %run rotation.py
# Box (synthetic smoke only):  python3 rotation.py --smoke
#
# Hypothesis: all-time averages look flat because the hot bucket moves, and the move is persistent
# enough to follow. Each week, rank units by trailing 4 / 8 / 12-week performance, then trade only
# the trailing-best unit the next week (direction = trailing net move for time buckets; engines use
# their own signals, ranked by average R). Compare top vs bottom vs all, both halves, ETH, a 200-run
# random-unit placebo, Spearman rank autocorrelation of week t vs t+1, and corr vs the live basket.
# Units: 24 UTC hours, 4 sessions (Asia 00-08, London 08-13, NY 13-21, late 21-24), 7 weekdays,
# week-of-month W1-W4 (days 1-7 / 8-14 / 15-21 / 22-31), and oslib.engines() live engines.
# Costs 0.12%/side (oslib.COST), 1% risk, next-bar fills, stop wins on a same-bar hit, min stop 0.25%.
# KEEP gates: PF > 1.3 in both halves, n >= 30, placebo >= 90, ETH PF > 1.0, |corr| vs live basket < 0.3.
import os, sys, time, subprocess, traceback
from pathlib import Path

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

def _download(name):
    here = Path.cwd() / name
    url = BASE_URL + name + "?nc=" + str(int(time.time()))
    tmp = Path(str(here) + ".tmp")
    try:
        try:
            subprocess.run(["wget", "-q", "-O", str(tmp), url], check=True)
        except Exception:
            from urllib.request import urlopen, Request
            tmp.write_bytes(urlopen(Request(url, headers={"User-Agent": "osom-rotation/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, sma, in_colab, synthetic_1h, LIVE_RISK, COST, H1, D1

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

NAN = np.nan
START = "2017-01-01"
SPLIT = "2021-01-01"
RISK = 0.01
MINR = 0.0025
N_PLC = 200
SEED = 20261122
LOOKS = (4, 8, 12)
SESS = [("Asia", 0, 8), ("London", 8, 13), ("NY", 13, 21), ("late", 21, 24)]
DOW = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
WOM = ["W1", "W2", "W3", "W4"]
HOURS = [f"h{h:02d}" for h in range(24)]
# 1970-01-01 was a Thursday; Monday of that week is 3 days earlier (1969-12-29).
MON0 = -3 * D1
W1MS = 7 * D1
ROWS = []
FIND = []
KEEP = {}

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

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

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

def f2(x, nd=2):
    return "n/a" if x is None or not np.isfinite(x) else f"{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 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 first_true(mask):
    anyv = mask.any(1)
    return np.where(anyv, mask.argmax(1), -1)

def day_matrix(df):
    t = df["time"].to_numpy(dtype="int64")
    keep = t >= T_START
    t = t[keep]
    cols = {k: df[k].to_numpy(dtype=float)[keep] for k in ("open", "high", "low", "close")}
    di = t // D1
    hr = ((t % D1) // H1).astype(int)
    days, inv = np.unique(di, return_inverse=True)
    out = {}
    for k, nm in (("open", "O"), ("high", "H"), ("low", "L"), ("close", "C")):
        m = np.full((len(days), 24), NAN)
        m[inv, hr] = cols[k]
        out[nm] = m
    ok = np.isfinite(out["O"]).all(1) & np.isfinite(out["H"]).all(1) & np.isfinite(out["L"]).all(1) & np.isfinite(out["C"]).all(1)
    for nm in ("O", "H", "L", "C"):
        out[nm] = out[nm][ok]
    day = days[ok] * D1
    out["day"] = day
    dts = pd.to_datetime(day, unit="ms", utc=True)
    out["dow"] = dts.dayofweek.to_numpy()
    out["wom"] = np.minimum(3, (dts.day.to_numpy() - 1) // 7)
    out["week"] = week_of(day)
    out["year"] = dts.year.to_numpy()
    dH, dL, dC = out["H"].max(1), out["L"].min(1), out["C"][:, 23]
    a = atr(dH, dL, dC, 14)
    out["atr_prev"] = np.r_[NAN, a[:-1]]
    s50 = sma(dC, 50)
    out["trend"] = np.r_[0, np.where(np.isfinite(s50[:-1]), np.sign(dC[:-1] - s50[:-1]), 0)].astype(int)
    out["h1"] = day < T_SPLIT
    return out

def sim_mat(M, d, e, side, stop, xcol):
    d = np.asarray(d, int); e = np.asarray(e, int); side = np.asarray(side, float); stop = np.asarray(stop, float)
    n = len(d)
    if n == 0:
        return dict(R=np.array([]), risk=np.array([]), ret=np.array([]))
    O, H, L, C = M["O"][d], M["H"][d], M["L"][d], M["C"][d]
    K = O.shape[1]
    cols = np.arange(K)[None, :]
    act = (cols >= e[:, None]) & (cols <= xcol)
    s = side[:, None]
    hit = act & np.where(s > 0, L <= stop[:, None], H >= stop[:, None])
    r = np.arange(n)
    entry = O[r, e]
    fh = first_true(hit)
    ex = C[r, np.full(n, xcol)]
    sx = np.where(side > 0, np.minimum(O[r, np.maximum(fh, 0)], stop), np.maximum(O[r, np.maximum(fh, 0)], stop))
    ex = np.where(fh >= 0, sx, ex)
    ret = side * (ex / entry - 1.0) - 2 * COST
    risk = np.abs(entry - stop) / entry
    R = np.where((risk > 0) & np.isfinite(risk) & np.isfinite(ret) & (entry > 0), ret / risk, NAN)
    return dict(R=R, risk=risk, ret=ret, entry=entry)

def bar_R(o, h, l, c, side, stop):
    side = np.asarray(side, float)
    hit = np.where(side > 0, l <= stop, h >= stop)
    ex = np.where(side > 0, np.minimum(o, stop), np.maximum(o, stop))
    ex = np.where(hit, ex, c)
    ret = side * (ex / o - 1.0) - 2 * COST
    risk = np.abs(o - stop) / o
    R = np.where((risk > 0) & np.isfinite(risk) & np.isfinite(ret) & (o > 0), ret / risk, NAN)
    return R, risk, ret

def adj_frac(entry, atr_px, k):
    entry = np.asarray(entry, float)
    atr_px = np.asarray(atr_px, float)
    return np.maximum(MINR, k * atr_px / np.where(entry > 0, entry, NAN))

def basket_daily(df, fund):
    eng = engines(df, fund=fund)
    pn = {}
    for nm, trs in eng.items():
        rk = LIVE_RISK.get(nm, RISK)
        for t in trs:
            r, R, xt = t.get("risk", NAN), t.get("R", NAN), t.get("exit_time", 0)
            if np.isfinite(r) and r > 0 and np.isfinite(R) and xt >= T_START:
                k = (int(xt) // D1) * D1
                pn[k] = pn.get(k, 0.0) + R * min(rk, r)
    print("    live basket: " + " ".join(f"{k} {len(v)}" for k, v in eng.items()), flush=True)
    return pd.Series(pn, dtype=float).sort_index(), eng

def corr_vs(basket, day, R, risk, all_days, risk_cap=RISK):
    if basket is None or not len(R):
        return NAN
    idea = pd.Series(np.asarray(R) * np.minimum(risk_cap, np.asarray(risk)), index=np.asarray(day, "int64")).groupby(level=0).sum()
    idx = pd.Index(np.asarray(all_days, "int64"))
    a = basket.reindex(idx).fillna(0.0).to_numpy()
    b = idea.reindex(idx).fillna(0.0).to_numpy()
    if a.std() == 0 or b.std() == 0:
        return NAN
    return float(np.corrcoef(a, b)[0, 1])

def spearman(a, b):
    a, b = np.asarray(a, float), np.asarray(b, float)
    m = np.isfinite(a) & np.isfinite(b)
    if m.sum() < 3:
        return NAN
    return float(pd.Series(a[m]).corr(pd.Series(b[m]), method="spearman"))

# ---------------------------------------------------------------------------
# panels: one row per trade-able occurrence, with long and short R already filled
# ---------------------------------------------------------------------------
def hour_panel(df):
    t = df["time"].to_numpy(dtype="int64")
    o, h, l, c = (df[k].to_numpy(dtype=float) for k in ("open", "high", "low", "close"))
    keep = t >= T_START
    t, o, h, l, c = t[keep], o[keep], h[keep], l[keep], c[keep]
    a1 = np.r_[NAN, atr(h, l, c, 14)[:-1]]
    frac = adj_frac(o, a1, 1.0)
    ok = np.isfinite(frac) & (o > 0) & np.isfinite(c) & np.isfinite(h) & np.isfinite(l)
    Rl, riskl, _ = bar_R(o, h, l, c, 1.0, o * (1.0 - frac))
    Rs, risks, _ = bar_R(o, h, l, c, -1.0, o * (1.0 + frac))
    return dict(t=t, day=(t // D1) * D1, week=week_of(t), unit=((t % D1) // H1).astype(int),
                move=np.where(o > 0, c / o - 1.0, NAN), Rl=Rl, Rs=Rs, riskl=riskl, risks=risks,
                ok=ok & np.isfinite(Rl) & np.isfinite(Rs), names=HOURS, kind="time", minn=8)

def chunk_panel(DM, unit, names, h0, h1, atr_k, minn):
    n = len(DM["day"])
    d = np.arange(n)
    e = np.full(n, h0, int)
    xcol = h1 - 1
    entry = DM["O"][:, h0]
    frac = adj_frac(entry, DM["atr_prev"], atr_k)
    ok = np.isfinite(frac) & (entry > 0) & np.isfinite(DM["C"][:, xcol])
    sl = sim_mat(DM, d, e, np.ones(n), entry * (1.0 - frac), xcol)
    ss = sim_mat(DM, d, e, -np.ones(n), entry * (1.0 + frac), xcol)
    move = np.where(entry > 0, DM["C"][:, xcol] / entry - 1.0, NAN)
    return dict(t=DM["day"], day=DM["day"], week=DM["week"], unit=np.asarray(unit, int),
                move=move, Rl=sl["R"], Rs=ss["R"], riskl=sl["risk"], risks=ss["risk"],
                ok=ok & np.isfinite(sl["R"]) & np.isfinite(ss["R"]), names=list(names), kind="time", minn=minn)

def session_panel(DM):
    parts = []
    for i, (nm, h0, h1) in enumerate(SESS):
        p = chunk_panel(DM, np.full(len(DM["day"]), i), [s[0] for s in SESS], h0, h1, 0.40, 6)
        parts.append(p)
    return cat_panels(parts, names=[s[0] for s in SESS], kind="time", minn=6)

def weekday_panel(DM):
    return chunk_panel(DM, DM["dow"], DOW, 0, 24, 0.50, 3)

def wom_panel(DM):
    return chunk_panel(DM, DM["wom"], WOM, 0, 24, 0.50, 5)

def cat_panels(parts, names, kind, minn):
    def stk(k):
        return np.concatenate([p[k] for p in parts])
    return dict(t=stk("t"), day=stk("day"), week=stk("week"), unit=stk("unit"), move=stk("move"),
                Rl=stk("Rl"), Rs=stk("Rs"), riskl=stk("riskl"), risks=stk("risks"), ok=stk("ok"),
                names=list(names), kind=kind, minn=minn)

def engine_panel(eng):
    names = [nm for nm, trs in eng.items() if trs]
    if not names:
        names = list(eng.keys())
    idx = {nm: i for i, nm in enumerate(names)}
    rows = []
    for nm, trs in eng.items():
        if nm not in idx:
            continue
        u = idx[nm]
        rk_live = LIVE_RISK.get(nm, RISK)
        for tr in trs:
            R, r, et, xt = tr.get("R", NAN), tr.get("risk", NAN), 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):
                continue
            day = (int(xt if xt else et) // D1) * D1
            rows.append((int(et), day, week_of(et), u, R, r, rk_live))
    if not rows:
        empty = np.array([], dtype=float)
        z = np.array([], dtype="int64")
        return dict(t=z, day=z, week=z, unit=np.array([], int), move=empty, Rl=empty, Rs=empty,
                    riskl=empty, risks=empty, ok=np.array([], bool), names=names, kind="engine",
                    minn=3, risk_live=empty)
    t, day, week, unit, R, risk, rlive = map(np.array, zip(*rows))
    return dict(t=t.astype("int64"), day=day.astype("int64"), week=week.astype("int64"),
                unit=unit.astype(int), move=R.astype(float), Rl=R.astype(float), Rs=R.astype(float),
                riskl=risk.astype(float), risks=risk.astype(float), ok=np.ones(len(R), bool),
                names=names, kind="engine", minn=3, risk_live=rlive.astype(float))

def mask_panel(P, m):
    out = {k: (P[k][m] if isinstance(P[k], np.ndarray) and len(P[k]) == len(m) else P[k]) for k in P}
    return out

# ---------------------------------------------------------------------------
# weekly score matrices and walk-forward
# ---------------------------------------------------------------------------
def week_pack(P):
    m = P["ok"]
    week, unit, move = P["week"][m], P["unit"][m], P["move"][m]
    Rl, Rs = P["Rl"][m], P["Rs"][m]
    U = len(P["names"])
    W = np.unique(week)
    if not len(W):
        z = np.zeros((0, U))
        return dict(W=W, U=U, sum_move=z, sum_Rl=z, sum_Rs=z, cnt=z, signed=z, tfr=z)
    wi = np.searchsorted(W, week)
    sum_move = np.zeros((len(W), U))
    sum_Rl = np.zeros((len(W), U))
    sum_Rs = np.zeros((len(W), U))
    cnt = np.zeros((len(W), U))
    np.add.at(sum_move, (wi, unit), np.where(np.isfinite(move), move, 0.0))
    np.add.at(sum_Rl, (wi, unit), np.where(np.isfinite(Rl), Rl, 0.0))
    np.add.at(sum_Rs, (wi, unit), np.where(np.isfinite(Rs), Rs, 0.0))
    np.add.at(cnt, (wi, unit), np.isfinite(Rl) & np.isfinite(Rs))
    nsafe = np.maximum(cnt, 1.0)
    signed = np.where(cnt > 0, sum_Rl / nsafe, NAN)
    direc = np.sign(sum_move)
    tfr = np.where(direc >= 0, sum_Rl, sum_Rs) / nsafe
    tfr = np.where(cnt > 0, tfr, NAN)
    if P["kind"] == "engine":
        tfr = signed
    return dict(W=W, U=U, sum_move=sum_move, sum_Rl=sum_Rl, sum_Rs=sum_Rs, cnt=cnt, signed=signed, tfr=tfr)

def trail_scores(pack, i, L, minn, kind):
    sl = slice(i - L, i)
    n = pack["cnt"][sl].sum(0)
    if kind == "engine":
        sR = pack["sum_Rl"][sl].sum(0)
        direc = np.ones(pack["U"])
        sc = np.where(n >= minn, sR / np.maximum(n, 1.0), NAN)
        return sc, direc, n
    sm = pack["sum_move"][sl].sum(0)
    direc = np.sign(sm)
    sR = np.where(direc >= 0, pack["sum_Rl"][sl].sum(0), pack["sum_Rs"][sl].sum(0))
    sc = np.where((n >= minn) & (direc != 0), sR / np.maximum(n, 1.0), NAN)
    return sc, direc, n

def week_unit_slice(P, w, u, side):
    m = P["ok"] & (P["week"] == w) & (P["unit"] == u)
    if P["kind"] == "engine" or side >= 0:
        R, risk = P["Rl"][m], P["riskl"][m]
    else:
        R, risk = P["Rs"][m], P["risks"][m]
    day = P["day"][m]
    if "risk_live" in P:
        cap = P["risk_live"][m]
    else:
        cap = np.full(m.sum(), RISK)
    return R, risk, day, cap

def week_all_slice(P, w, direc):
    # `direc` is indexed by unit id; `side` is per trade. A short week (incomplete
    # UTC day dropped) can have 6 trades including Sunday (unit 6) -- side[u] was OOB.
    m = P["ok"] & (P["week"] == w)
    u = P["unit"][m]
    n_dir = len(direc)
    inb = (u >= 0) & (u < n_dir) if n_dir else np.zeros(m.sum(), bool)
    side = np.zeros(m.sum(), dtype=float)
    if inb.any():
        side[inb] = direc[u[inb]]
    use_long = (P["kind"] == "engine") | (side >= 0)
    R = np.where(use_long, P["Rl"][m], P["Rs"][m])
    risk = np.where(use_long, P["riskl"][m], P["risks"][m])
    keep = inb if P["kind"] == "engine" else (inb & (side != 0))
    day = P["day"][m]
    cap = P["risk_live"][m] if "risk_live" in P else np.full(m.sum(), RISK)
    return R[keep], risk[keep], day[keep], cap[keep]

def walk(P, L, rng):
    # Follow-the-hot-unit for one family and one lookback. Returns trade bundles + placebo PFs.
    pack = week_pack(P)
    W, U, names = pack["W"], pack["U"], P["names"]
    minn = P["minn"]
    kind = P["kind"]
    empty = dict(top=None, bot=None, all=None, plc=np.array([]), freq=np.zeros(U),
                 n_weeks=0, pack=pack, names=names, L=L)
    if len(W) <= L + 1:
        return empty
    top_R, top_risk, top_day, top_cap = [], [], [], []
    bot_R, bot_risk, bot_day, bot_cap = [], [], [], []
    all_R, all_risk, all_day, all_cap = [], [], [], []
    # per evaluable week: pos/neg of each unit (already in trailing direction) for placebo
    ev = []
    freq = np.zeros(U)
    for i in range(L, len(W)):
        sc, direc, _n = trail_scores(pack, i, L, minn, kind)
        valid = np.where(np.isfinite(sc))[0]
        if len(valid) < 2:
            continue
        top = int(valid[np.nanargmax(sc[valid])])
        bot = int(valid[np.nanargmin(sc[valid])])
        freq[top] += 1
        w = W[i]
        Rt, kt, dt, ct = week_unit_slice(P, w, top, direc[top])
        Rb, kb, db, cb = week_unit_slice(P, w, bot, direc[bot])
        Ra, ka, da, ca = week_all_slice(P, w, direc)
        if len(Rt):
            top_R.append(Rt); top_risk.append(kt); top_day.append(dt); top_cap.append(ct)
        if len(Rb):
            bot_R.append(Rb); bot_risk.append(kb); bot_day.append(db); bot_cap.append(cb)
        if len(Ra):
            all_R.append(Ra); all_risk.append(ka); all_day.append(da); all_cap.append(ca)
        pos = np.zeros(U); neg = np.zeros(U); has = np.zeros(U, bool)
        for u in valid:
            Ru, _, _, _ = week_unit_slice(P, w, u, direc[u])
            Ru = Ru[np.isfinite(Ru)]
            if not len(Ru):
                continue
            pos[u] = Ru[Ru > 0].sum()
            neg[u] = -Ru[Ru < 0].sum()
            has[u] = True
        if has[valid].any():
            ev.append((valid[has[valid]], pos, neg))
    def cat(xs):
        return np.concatenate(xs) if xs else np.array([], dtype=float)
    def bundle(Rs, ks, ds, cs):
        return dict(R=cat(Rs), risk=cat(ks), day=cat(ds).astype("int64") if ds else np.array([], dtype="int64"),
                    cap=cat(cs) if cs else np.array([], dtype=float))
    # placebo: each run, each evaluable week pick a random valid unit; PF from pooled pos/neg
    plc = np.full(N_PLC, NAN)
    if ev:
        for r in range(N_PLC):
            tp = tn = 0.0
            for valid, pos, neg in ev:
                u = int(rng.choice(valid))
                tp += pos[u]; tn += neg[u]
            plc[r] = (tp / tn) if tn > 0 else (99.0 if tp > 0 else NAN)
    return dict(top=bundle(top_R, top_risk, top_day, top_cap),
                bot=bundle(bot_R, bot_risk, bot_day, bot_cap),
                all=bundle(all_R, all_risk, all_day, all_cap),
                plc=plc, freq=freq, n_weeks=int(freq.sum()), pack=pack, names=names, L=L)

def plc_pct(pf_act, pfs):
    pfs = np.asarray(pfs, float)
    pfs = pfs[np.isfinite(pfs)]
    if not len(pfs) or not np.isfinite(pf_act):
        return NAN
    return 100.0 * np.mean(pfs < pf_act)

def split_pf(b):
    if b is None or not len(b["R"]):
        return NAN, NAN, NAN, 0, NAN
    R, day = b["R"], b["day"]
    return pf_of(R), pf_of(R[day < T_SPLIT]), pf_of(R[day >= T_SPLIT]), len(R), (np.mean(R > 0) if len(R) else NAN)

TEST_HDR = (f"  {'test':<36} {'n':>5} {'win%':>6} {'PF':>5} {'avgR':>6} {'PF17-20':>8} {'PF21-26':>8} "
            f"{'ETH n':>6} {'ETH PF':>7} {'plc':>5} {'corr':>6}  verdict")

def eval_path(sec, name, btc_b, eth_b, plc, corr):
    if btc_b is None or not len(btc_b.get("R", [])):
        print(f"  {name:<36} no BTC trades", flush=True)
        return
    pf, p1, p2, n, win = split_pf(btc_b)
    avg = np.nanmean(btc_b["R"]) if n else NAN
    epf, _, _, en, _ = split_pf(eth_b) if eth_b is not None else (NAN, NAN, NAN, 0, NAN)
    plc_v = plc_pct(pf, plc)
    cr = corr
    fails = []
    if not (np.isfinite(p1) and p1 > 1.3 and np.isfinite(p2) and p2 > 1.3):
        fails.append("halves")
    if n < 30:
        fails.append("n")
    if not (np.isfinite(plc_v) and plc_v >= 90):
        fails.append("placebo")
    if not (np.isfinite(epf) and epf > 1.0):
        fails.append("ETH")
    if not (np.isfinite(cr) and abs(cr) < 0.3):
        fails.append("corr")
    v = "KEEP" if not fails else "NO (" + ",".join(fails) + ")"
    KEEP[name] = (v, pf, p1, p2, epf, plc_v, n, cr)
    print(f"  {name:<36} {n:>5} {pct(win):>6} {f2(pf):>5} {f2(avg):>6} {f2(p1):>8} {f2(p2):>8} "
          f"{en:>6} {f2(epf):>7} {f2(plc_v,0):>5} {f2(cr):>6}  {v}", flush=True)
    for k, val in (("n", n), ("win", win), ("PF", pf), ("avgR", avg), ("PF_17_20", p1), ("PF_21_26", p2),
                   ("ETH_PF", epf), ("ETH_n", en), ("placebo", plc_v), ("corr", cr),
                   ("keep", 1.0 if not fails else 0.0)):
        rec(sec, "btc", name, k, val)

def path_corr(ctx, asset, b):
    c = ctx[asset]
    if b is None or not len(b["R"]):
        return NAN
    cap = b["cap"] if len(b.get("cap", [])) == len(b["R"]) else np.full(len(b["R"]), RISK)
    return corr_vs(c.get("basket"), b["day"], b["R"], b["risk"], c["DM"]["day"], risk_cap=cap)

def hot_name(freq, names):
    if not np.any(freq):
        return "n/a"
    return names[int(np.argmax(freq))]

# ---------------------------------------------------------------------------
# SECTION 1: all-time averages (the thing the user says hides the rotation)
# ---------------------------------------------------------------------------
def section1(ctx):
    print("\n=== 1) ALL-TIME AVERAGES (always-long R for time buckets; engine avg R) - these can look flat even if a bucket is hot in stretches ===", flush=True)
    for a in ("btc", "eth"):
        c = ctx[a]
        print(f"  {a.upper()}  unit                 n   win%    PF   avgR  PF17-20  PF21-26", flush=True)
        for fam, P in c["fams"].items():
            m = P["ok"]
            if not m.any():
                continue
            for u, nm in enumerate(P["names"]):
                mu = m & (P["unit"] == u)
                if P["kind"] == "engine":
                    R = P["Rl"][mu]
                else:
                    R = P["Rl"][mu]
                day = P["day"][mu]
                if not len(R):
                    continue
                pf, p1, p2, n, win = pf_of(R), pf_of(R[day < T_SPLIT]), pf_of(R[day >= T_SPLIT]), len(R), np.mean(R > 0)
                avg = np.nanmean(R)
                print(f"  {a.upper()}  {fam:<8} {nm:<10} {n:>5} {pct(win):>6} {f2(pf):>5} {f2(avg):>6} {f2(p1):>8} {f2(p2):>8}", flush=True)
                rec("1", a, f"{fam}:{nm}", "n", n); rec("1", a, f"{fam}:{nm}", "PF", pf)
                rec("1", a, f"{fam}:{nm}", "avgR", avg); rec("1", a, f"{fam}:{nm}", "PF_17_20", p1)
                rec("1", a, f"{fam}:{nm}", "PF_21_26", p2)
        if a == "btc":
            # one-line snapshot of session always-long PFs
            P = c["fams"].get("session")
            if P is not None:
                bits = []
                for u, nm in enumerate(P["names"]):
                    R = P["Rl"][P["ok"] & (P["unit"] == u)]
                    bits.append(f"{nm} PF {f2(pf_of(R))} n {len(R)}")
                FIND.append("All-time always-long session PFs (BTC): " + ", ".join(bits) + ".")

# ---------------------------------------------------------------------------
# SECTION 2: Spearman rank autocorrelation, week t vs week t+1
# ---------------------------------------------------------------------------
def auto_corr(mat):
    rs = []
    for i in range(len(mat) - 1):
        r = spearman(mat[i], mat[i + 1])
        if np.isfinite(r):
            rs.append(r)
    rs = np.array(rs, float) if rs else np.array([], float)
    return dict(mean=float(np.mean(rs)) if len(rs) else NAN,
                med=float(np.median(rs)) if len(rs) else NAN,
                pos=float(np.mean(rs > 0)) if len(rs) else NAN,
                n=len(rs), rs=rs)

def block_score(pack, L=4, score="signed"):
    # Non-overlapping L-week means, so consecutive blocks share no weeks.
    mat = pack[score]
    rows = []
    for i in range(0, len(mat) - L + 1, L):
        sl = mat[i:i + L]
        cnt = np.isfinite(sl).sum(0)
        sc = np.where(cnt > 0, np.nansum(sl, axis=0) / cnt, NAN)
        if np.isfinite(sc).sum() >= 3:
            rows.append(sc)
    return np.vstack(rows) if rows else np.zeros((0, pack["U"]))

def month_score(P, score="signed"):
    # One row per calendar month; used for week-of-month (W1-W4 ranks, month t vs t+1).
    m = P["ok"]
    if not m.any():
        return np.zeros((0, len(P["names"])))
    dts = pd.to_datetime(P["day"][m], unit="ms", utc=True)
    mid = (dts.year * 12 + dts.month).to_numpy()
    unit, Rl, move = P["unit"][m], P["Rl"][m], P["move"][m]
    months = np.unique(mid)
    U = len(P["names"])
    mat = np.full((len(months), U), NAN)
    for i, mo in enumerate(months):
        sel = mid == mo
        for u in range(U):
            su = sel & (unit == u)
            if not su.any():
                continue
            if score == "tfr":
                direc = np.sign(np.nansum(move[su]))
                R = np.where(direc >= 0, P["Rl"][m][su], P["Rs"][m][su]) if P["kind"] != "engine" else P["Rl"][m][su]
            else:
                R = Rl[su]
            R = R[np.isfinite(R)]
            if len(R):
                mat[i, u] = R.mean()
    return mat

def family_spearman(P, score="signed"):
    pack = week_pack(P)
    raw = auto_corr(pack[score])
    blk = auto_corr(block_score(pack, 4, score))
    mon = auto_corr(month_score(P, score)) if P["names"] == WOM or len(P["names"]) <= 5 else None
    if P["names"] == WOM and mon is not None and mon["n"] >= 3:
        use, tag = mon, "month"
    elif raw["n"] >= 15:
        use, tag = raw, "week"
    else:
        use, tag = blk, "block4"
    return dict(raw=raw, block=blk, month=mon, use=use, tag=tag)

def section2(ctx):
    print("\n=== 2) SPEARMAN RANK AUTOCORRELATION (unit ranks in week t vs week t+1) ===", flush=True)
    print("  signed = always-long avg R (direction preserved); tfr = in-week trend-follow R (hot place, direction stripped).", flush=True)
    print("  src: week = adjacent weeks; month = adjacent calendar months (week-of-month); block4 = non-overlapping 4-week blocks (no shared weeks).", flush=True)
    print(f"  {'asset':<5} {'family':<10} {'src':>6} {'signed r':>9} {'median':>7} {'%pos':>6} {'n':>5}  {'tfr r':>8} {'tfr %pos':>8} {'tfr n':>6}", flush=True)
    for a in ("btc", "eth"):
        for fam, P in ctx[a]["fams"].items():
            s = family_spearman(P, "signed")
            tf = family_spearman(P, "tfr")
            u, tu = s["use"], tf["use"]
            print(f"  {a:<5} {fam:<10} {s['tag']:>6} {f2(u['mean']):>9} {f2(u['med']):>7} {pct(u['pos']):>6} {u['n']:>5}  {f2(tu['mean']):>8} {pct(tu['pos']):>8} {tu['n']:>6}", flush=True)
            rec("2", a, fam, "spearman_signed", u["mean"]); rec("2", a, fam, "spearman_signed_pos", u["pos"])
            rec("2", a, fam, "spearman_tfr", tu["mean"]); rec("2", a, fam, "spearman_n", u["n"])
            rec("2", a, fam, "spearman_raw_n", s["raw"]["n"]); rec("2", a, fam, "spearman_block4", s["block"]["mean"])
            if a == "btc":
                label = {"hour": "hour", "session": "session", "weekday": "weekday",
                         "wom": "week-of-month", "engine": "engine"}[fam]
                if (not np.isfinite(u["mean"])) or u["n"] < 20:
                    verb = "are inconclusive"
                elif u["mean"] >= 0.10 and u["pos"] >= 0.55:
                    verb = "persist"
                else:
                    verb = "do not persist"
                src = {"week": "week t vs t+1", "month": "month t vs t+1",
                       "block4": "non-overlapping 4-week blocks t vs t+1"}[s["tag"]]
                FIND.append(f"{label} ranks {verb}: Spearman {src} r={f2(u['mean'])} "
                            f"(positive in {pct(u['pos']).strip()}% of pairs, n {u['n']}).")

# ---------------------------------------------------------------------------
# SECTION 3: walk-forward follow-the-hot-unit
# ---------------------------------------------------------------------------
def section3(ctx):
    print("\n=== 3) FOLLOW THE HOT UNIT (each week trade only the trailing-best unit next week) ===", flush=True)
    print("  Time buckets are traded in the trailing net direction (trend-follow R). Engines keep their own signals and are ranked by average R.", flush=True)
    print("  'all' = every unit that week, each in its own trailing direction. Placebo = random eligible unit each week, 200 runs, percentile of follow-hot PF.", flush=True)
    print(TEST_HDR, flush=True)
    ctx["wf"] = {}
    for fam in ("hour", "session", "weekday", "wom", "engine"):
        for L in LOOKS:
            key = f"{fam} L{L}"
            try:
                rng = np.random.default_rng(SEED + 17 * L + 3 * ["hour", "session", "weekday", "wom", "engine"].index(fam))
                wb = walk(ctx["btc"]["fams"][fam], L, rng)
                we = walk(ctx["eth"]["fams"][fam], L, np.random.default_rng(SEED + 99)) if fam in ctx["eth"]["fams"] else dict(top=None)
                ctx["wf"][(fam, L)] = (wb, we)
                cr = path_corr(ctx, "btc", wb["top"])
                eval_path("3", f"hot {key}", wb["top"], we.get("top"), wb["plc"], cr)
                # also report bot / all as diagnostics (gates only on follow-hot)
                for tag, bun in (("bot", wb["bot"]), ("all", wb["all"])):
                    pf, p1, p2, n, win = split_pf(bun)
                    epf, _, _, en, _ = split_pf(we.get(tag) if isinstance(we, dict) else None)
                    avg = np.nanmean(bun["R"]) if n else NAN
                    rec("3", "btc", f"{tag} {key}", "PF", pf); rec("3", "btc", f"{tag} {key}", "n", n)
                    rec("3", "btc", f"{tag} {key}", "PF_17_20", p1); rec("3", "btc", f"{tag} {key}", "PF_21_26", p2)
                    print(f"  {tag+' '+key:<36} {n:>5} {pct(win):>6} {f2(pf):>5} {f2(avg):>6} {f2(p1):>8} {f2(p2):>8} "
                          f"{en:>6} {f2(epf):>7} {'':>5} {'':>6}", flush=True)
                hn = hot_name(wb["freq"], wb["names"])
                rec("3", "btc", f"hot {key}", "top_share", (wb["freq"].max() / wb["n_weeks"]) if wb["n_weeks"] else NAN)
                print(f"    most-frequent top {fam} @ L{L}: {hn} in {int(wb['freq'].max())}/{wb['n_weeks']} weeks", flush=True)
            except Exception as ex:
                print(f"  {key} ERROR {type(ex).__name__}: {ex}", flush=True)
                traceback.print_exc(limit=2)

    # findings: for each family, the L with the best follow-hot BTC PF
    for fam, label in (("hour", "hour"), ("session", "session"), ("weekday", "weekday"),
                       ("wom", "week-of-month"), ("engine", "engine")):
        best = None
        for L in LOOKS:
            pair = ctx["wf"].get((fam, L))
            if not pair:
                continue
            wb, _we = pair
            pf, _, _, n, _ = split_pf(wb["top"])
            pf_all, _, _, _, _ = split_pf(wb["all"])
            if not np.isfinite(pf):
                continue
            if best is None or pf > best[0]:
                best = (pf, pf_all, L, n, hot_name(wb["freq"], wb["names"]), KEEP.get(f"hot {fam} L{L}", ("?",))[0])
        if best:
            pf, pf_all, L, n, hn, verd = best
            rel = "persists" if (np.isfinite(pf) and np.isfinite(pf_all) and pf > pf_all and pf > 1.0) else "does not persist"
            FIND.append(f"hot {label} {rel}: top {hn} next-week PF {f2(pf)} vs all {f2(pf_all)} "
                        f"(lookback {L}w, n {n}, {verd}).")

# ---------------------------------------------------------------------------
def build_asset(df, fund):
    DM = day_matrix(df)
    print(f"    {len(DM['day'])} complete UTC days from {START}", flush=True)
    basket, eng = None, {}
    try:
        ta = time.time()
        basket, eng = basket_daily(df, fund)
        print(f"    basket daily pnl days {len(basket)} ({time.time()-ta:.0f}s)", flush=True)
    except Exception as ex:
        print(f"    basket/engines error {type(ex).__name__}: {ex} (engine family and corr may be n/a)", flush=True)
        traceback.print_exc(limit=2)
        try:
            eng = engines(df, fund=fund)
        except Exception as ex2:
            print(f"    engines() retry failed {type(ex2).__name__}: {ex2}", flush=True)
            eng = {}
    fams = {
        "hour": hour_panel(df),
        "session": session_panel(DM),
        "weekday": weekday_panel(DM),
        "wom": wom_panel(DM),
        "engine": engine_panel(eng),
    }
    return dict(df=df, fund=fund, DM=DM, basket=basket, eng=eng, fams=fams)

def main(smoke=False):
    ctx = {"rng": np.random.default_rng(SEED)}
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        n = int(os.environ.get("ROT_SMOKE_N", str(24 * 1100)))
        b1 = synthetic_1h(n=n, seed=9, start="2019-07-01")
        e1 = synthetic_1h(n=n, seed=21, start="2019-07-01", px0=300.0)
        raw = {"btc": (b1, None), "eth": (e1, None)}
    else:
        raw = {}
        for a in ("btc", "eth"):
            df = load(a, "1h")
            try:
                fd = funding(a, "binance")
            except Exception as ex:
                print(f"  funding {a} failed ({type(ex).__name__}); engines without funding", flush=True)
                fd = None
            raw[a] = (df, fd)
    for a in ("btc", "eth"):
        print(f"  building {a.upper()} panels...", flush=True)
        try:
            ctx[a] = build_asset(*raw[a])
        except Exception as ex:
            print(f"  BUILD {a} ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=3)
            ctx[a] = dict(df=raw[a][0], fund=raw[a][1], DM=day_matrix(raw[a][0]),
                          basket=None, eng={}, fams={})
        print(f"  ({time.time()-T0:.0f}s)", flush=True)

    for fn in (section1, section2, section3):
        try:
            fn(ctx)
        except Exception as ex:
            print(f"SECTION {fn.__name__} ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=3)
        print(f"  ({time.time()-T0:.0f}s)", flush=True)

    print("\n=== FINDINGS ===", flush=True)
    for s in FIND:
        print("  - " + s, flush=True)
    keeps = [k for k, v in KEEP.items() if v[0] == "KEEP"]
    near = sorted([(v[1], k) for k, v in KEEP.items() if v[0] != "KEEP" and np.isfinite(v[1]) and v[1] > 1.2], reverse=True)[:6]
    print(f"  - Follow-hot paths that pass every KEEP gate: {', '.join(keeps) if keeps else 'none'}.", flush=True)
    if near:
        print("  - Best of the rest (PF, failed gates): " + "; ".join(f"{k} PF {v:.2f} {KEEP[k][0]}" for v, k in near) + ".", flush=True)
    print("  KEEP gates: PF > 1.3 both halves, n >= 30, placebo >= 90, ETH PF > 1.0, |corr| < 0.3 vs live basket.", flush=True)

    out_dir = Path("/content") if Path("/content").exists() else Path(".")
    out = out_dir / ("rotation_smoke.csv" if smoke else "rotation.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)
