# ===== tilt.py - does tilting live risk toward recently-hot engines beat the static mix in dollars and DD? =====
# Colab:  !wget -q -O tilt.py https://osom-boba.pages.dev/colab/tilt.py
#         %run tilt.py
# Box (synthetic smoke only):  python3 tilt.py --smoke
#
# Live risk: K8 2%; COCO, B1G, S5 3%; V7, R0, C1, C2, MOM30, D34 1%. Costs already in engines()
# (oslib.COST 0.12%/side). 10% stop cap is applied inside engines() as live (STOP_RULE cap 0.10).
# Equity compounds from 1.0 on exit-time PnL. oslib has no basket-level maxOpen, so this script
# enforces maxOpen 4 (a new entry is skipped while 4 positions are already open) on every variant
# including the static baseline. Multipliers are recomputed each UTC Monday from trades whose
# exit_time is strictly before that Monday (no lookahead).
# Variants:
#   static     - live risk, no tilt
#   tilt_kK_LW - among engines with >=5 exits in the trailing L weeks, x1.5 top-K, x0.5 bottom-K, else x1
#                (K in {2,3}, L in {8,12,26}); engines with <5 trailing trades stay at x1 and are not ranked
#   cut30      - x0 (pause) if that engine's last 30 exited trades have PF < 1.0, else x1; x1 if n < 30
#   cut30soft  - same rule with x0.5 instead of x0
#   prop_LW    - rank-proportional multipliers (best gets n, worst gets 1) on engines with >=5 trailing
#                trades, others x1, then rescaled so sum(m * live_risk) equals the static total risk
# KEEP_LIVE if MAR > baseline in both halves, beats baseline in >=5/7 years 2020-2026 on BTC and
# >=4/7 on ETH, placebo MAR percentile >= 90, and maxDD is not worse than baseline by more than 3 pts.
# Placebo: each week shuffle the engine labels on that week's multipliers, 200 runs.
import os, sys, time, subprocess, traceback, heapq
from pathlib import Path

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

def _download(name):
    here = Path.cwd() / name
    url = BASE_URL + name + "?nc=" + str(int(time.time()))
    tmp = Path(str(here) + ".tmp")
    try:
        try:
            subprocess.run(["wget", "-q", "-O", str(tmp), url], check=True)
        except Exception:
            from urllib.request import urlopen, Request
            tmp.write_bytes(urlopen(Request(url, headers={"User-Agent": "osom-tilt/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"tilt | oslib v{oslib.__version__} | cost {100*COST:.2f}%/side | live-risk mix | maxOpen 4", flush=True)

NAN = np.nan
START = "2017-01-01"
SPLIT = "2021-01-01"
MAX_OPEN = 4
N_PLC = 200
SEED = 20261122
MIN_TRAIL = 5
LOOKS = (8, 12, 26)
KS = (2, 3)
YEARS = list(range(2020, 2027))
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 week_start(w):
    return np.asarray(w, dtype="int64") * W1MS + MON0

# ---------------------------------------------------------------------------
# trades
# ---------------------------------------------------------------------------
def pack_trades(eng):
    names = [nm for nm, trs in eng.items()]
    idx = {nm: i for i, nm in enumerate(names)}
    base = np.array([LIVE_RISK.get(nm, 0.01) for nm in names], dtype=float)
    rows = []
    for nm, trs in eng.items():
        u = idx[nm]
        for tr in trs:
            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))
    if not rows:
        z = np.array([], dtype="int64"); e = np.array([], dtype=float)
        return dict(entry=z, exit=z, R=e, risk=e, unit=np.array([], dtype=int),
                    week=z, names=names, base=base, n=0)
    entry, exit, R, risk, unit = (np.array(x) for x in zip(*rows))
    order = np.lexsort((np.array(names)[np.asarray(unit, int)], entry))
    entry, exit, R, risk, unit = entry[order], exit[order], R[order], risk[order], unit[order]
    return dict(entry=entry.astype("int64"), exit=exit.astype("int64"), R=R.astype(float),
                risk=risk.astype(float), unit=unit.astype(int), week=week_of(entry),
                names=names, base=base, n=len(R))

def exit_week(P):
    return week_of(P["exit"])

# ---------------------------------------------------------------------------
# weekly multipliers from past exits only
# ---------------------------------------------------------------------------
def weekly_grid(P):
    ew = exit_week(P)
    ew_ok = ew if len(ew) else np.array([], dtype="int64")
    we = week_of(P["entry"]) if P["n"] else np.array([], dtype="int64")
    w_all = np.unique(np.concatenate([ew_ok, we])) if (len(ew_ok) or len(we)) else np.array([], dtype="int64")
    return w_all

def build_exit_lists(P):
    # per engine, exits sorted by exit_time: arrays of (exit_time, R)
    U = len(P["names"])
    lists = []
    for u in range(U):
        m = P["unit"] == u
        xt, R = P["exit"][m], P["R"][m]
        if len(xt):
            o = np.argsort(xt, kind="stable")
            lists.append((xt[o], R[o]))
        else:
            lists.append((np.array([], dtype="int64"), np.array([], dtype=float)))
    return lists

def trail_avg(xt, R, t0, t1, min_n=MIN_TRAIL):
    # exits in [t0, t1)
    if not len(xt):
        return NAN, 0
    i0, i1 = np.searchsorted(xt, t0, "left"), np.searchsorted(xt, t1, "left")
    sl = R[i0:i1]
    sl = sl[np.isfinite(sl)]
    n = len(sl)
    if n < min_n:
        return NAN, n
    return float(sl.mean()), n

def last30_pf(xt, R, t1):
    if not len(xt):
        return NAN, 0
    i1 = np.searchsorted(xt, t1, "left")
    sl = R[:i1]
    sl = sl[np.isfinite(sl)]
    n = len(sl)
    if n < 30:
        return NAN, n
    return pf_of(sl[-30:]), 30

def mult_static(U, nW):
    return np.ones((nW, U), dtype=float)

def mult_tilt(lists, W, k, L, base):
    U, nW = len(lists), len(W)
    M = np.ones((nW, U), dtype=float)
    starts = week_start(W)
    span = L * W1MS
    for i, t1 in enumerate(starts):
        t0 = t1 - span
        scores = np.full(U, NAN)
        for u in range(U):
            scores[u], _n = trail_avg(lists[u][0], lists[u][1], t0, t1, MIN_TRAIL)
        valid = np.where(np.isfinite(scores))[0]
        if len(valid) < 2:
            continue
        kk = min(k, max(1, len(valid) // 2))
        order = valid[np.argsort(scores[valid], kind="stable")]
        bot, top = order[:kk], order[-kk:]
        M[i, bot] = 0.5
        M[i, top] = 1.5
    return M

def mult_cut(lists, W, soft=False):
    U, nW = len(lists), len(W)
    M = np.ones((nW, U), dtype=float)
    lo = 0.5 if soft else 0.0
    starts = week_start(W)
    for i, t1 in enumerate(starts):
        for u in range(U):
            pf, n = last30_pf(lists[u][0], lists[u][1], t1)
            if n >= 30 and np.isfinite(pf) and pf < 1.0:
                M[i, u] = lo
    return M

def mult_prop(lists, W, L, base):
    U, nW = len(lists), len(W)
    M = np.ones((nW, U), dtype=float)
    T = float(base.sum()) if len(base) else 0.0
    starts = week_start(W)
    span = L * W1MS
    for i, t1 in enumerate(starts):
        t0 = t1 - span
        scores = np.full(U, NAN)
        for u in range(U):
            scores[u], _n = trail_avg(lists[u][0], lists[u][1], t0, t1, MIN_TRAIL)
        valid = np.where(np.isfinite(scores))[0]
        if len(valid) == 0 or T <= 0:
            continue
        # rank 1 = worst, n = best; ties get average rank
        rk = pd.Series(scores[valid]).rank(method="average").to_numpy()
        frozen = np.ones(U, bool); frozen[valid] = False
        F = float(base[frozen].sum()) if frozen.any() else 0.0
        budget = T - F
        if budget <= 0 or rk.sum() <= 0:
            continue
        # m_u * base_u proportional to rank, summing to budget
        raw = rk
        denom = float((raw * base[valid]).sum())
        if denom <= 0:
            continue
        M[i, valid] = raw * budget / denom
    return M

# ---------------------------------------------------------------------------
# apply multipliers, maxOpen, compound
# ---------------------------------------------------------------------------
def apply_maxopen(entry, exit, take, max_open=MAX_OPEN):
    kept = np.zeros(len(entry), dtype=bool)
    if not take.any():
        return kept
    order = np.argsort(entry, kind="stable")
    heap = []
    for i in order:
        if not take[i]:
            continue
        t = int(entry[i])
        while heap and heap[0] <= t:
            heapq.heappop(heap)
        if len(heap) < max_open:
            kept[i] = True
            heapq.heappush(heap, int(exit[i]))
    return kept

def windex(week, W):
    # map trade week id -> row in W; unseen weeks -> 0 (multipliers default to 1 if we guard)
    if not len(W):
        return np.zeros(len(week), dtype=int)
    ix = np.searchsorted(W, week)
    ix = np.clip(ix, 0, len(W) - 1)
    match = W[ix] == week
    # if a trade's week is not in W, treat as row 0 but caller should have W covering all entry weeks
    return np.where(match, ix, 0)

def run_path(P, M, W, cap_open=True):
    if P["n"] == 0 or not len(W):
        return empty_stats()
    wi = windex(P["week"], W)
    m = M[wi, P["unit"]]
    take = np.isfinite(m) & (m > 0)
    if cap_open:
        take = apply_maxopen(P["entry"], P["exit"], take, MAX_OPEN)
    pnl = np.where(take, P["R"] * np.minimum(P["base"][P["unit"]] * m, P["risk"]), 0.0)
    pnl = np.where(take & np.isfinite(pnl), pnl, 0.0)
    return stats_from(P["exit"][take], pnl[take], P["R"][take])

def empty_stats():
    keys = ("ret", "cagr", "dd", "mar", "pf", "n", "eq", "daily")
    out = {k: (NAN if k != "n" else 0) for k in keys}
    out["daily"] = pd.Series(dtype=float)
    out["eq"] = 1.0
    out["ret"] = NAN
    return out

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

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

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

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

# ---------------------------------------------------------------------------
# placebo: shuffle engine labels on each week's multiplier row
# ---------------------------------------------------------------------------
def placebo_mar(P, M, W, rng, n_plc=N_PLC):
    if P["n"] == 0 or not len(W):
        return np.full(n_plc, NAN)
    U = M.shape[1]
    out = np.full(n_plc, NAN)
    for r in range(n_plc):
        Mp = np.empty_like(M)
        for i in range(len(W)):
            perm = rng.permutation(U)
            Mp[i] = M[i, perm]
        out[r] = run_path(P, Mp, W)["mar"]
    return out

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

# ---------------------------------------------------------------------------
# variant list
# ---------------------------------------------------------------------------
def variant_specs():
    specs = [("static", "static", None)]
    for k in KS:
        for L in LOOKS:
            specs.append((f"tilt_k{k}_L{L}", "tilt", dict(k=k, L=L)))
    specs.append(("cut30", "cut", dict(soft=False)))
    specs.append(("cut30soft", "cut", dict(soft=True)))
    for L in LOOKS:
        specs.append((f"prop_L{L}", "prop", dict(L=L)))
    return specs

def make_mult(kind, lists, W, base, params):
    if kind == "static":
        return mult_static(len(base), len(W))
    if kind == "tilt":
        return mult_tilt(lists, W, params["k"], params["L"], base)
    if kind == "cut":
        return mult_cut(lists, W, soft=params["soft"])
    if kind == "prop":
        return mult_prop(lists, W, params["L"], base)
    raise ValueError(kind)

# ---------------------------------------------------------------------------
# reporting
# ---------------------------------------------------------------------------
HDR = (f"  {'variant':<16} {'n':>5} {'PF':>5} {'ret%':>8} {'CAGR%':>7} {'maxDD%':>7} {'MAR':>6} "
       f"{'ret17-20':>8} {'dd17-20':>8} {'MAR1':>6} {'ret21-26':>8} {'dd21-26':>8} {'MAR2':>6} "
       f"{'yrBTC':>5} {'ETH ret':>8} {'ETH MAR':>7} {'yrETH':>5} {'plc':>5}  verdict")

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

def verdict_of(btc, eth, base_b, base_e, plc):
    fails = []
    h1b, h2b = btc["h1"], btc["h2"]
    if not (np.isfinite(h1b["mar"]) and np.isfinite(base_b["h1"]["mar"]) and h1b["mar"] > base_b["h1"]["mar"]
            and np.isfinite(h2b["mar"]) and np.isfinite(base_b["h2"]["mar"]) and h2b["mar"] > base_b["h2"]["mar"]):
        fails.append("halves")
    hb, _tb = btc["beats"]
    he, _te = eth["beats"] if eth is not None else (0, 7)
    if hb < 5:
        fails.append("yrsBTC")
    if he < 4:
        fails.append("yrsETH")
    if not (np.isfinite(plc) and plc >= 90):
        fails.append("placebo")
    # maxDD not worse than baseline by > 3 percentage points (dd is a negative fraction)
    if not (np.isfinite(btc["st"]["dd"]) and np.isfinite(base_b["st"]["dd"])
            and (btc["st"]["dd"] >= base_b["st"]["dd"] - 0.03)):
        fails.append("DD")
    return ("KEEP_LIVE" if not fails else "NO (" + ",".join(fails) + ")"), fails

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

# ---------------------------------------------------------------------------
# sections
# ---------------------------------------------------------------------------
def section1(ctx):
    print("\n=== 1) STATIC LIVE-RISK BASKET (maxOpen 4, compound from 1.0, 10% stop cap already in engines()) ===", flush=True)
    for a in ("btc", "eth"):
        c = ctx[a]
        P, st = c["P"], c["base_st"]
        print(f"  {a.upper()} engines: " + " ".join(f"{nm} {int((P['unit']==i).sum())}" for i, nm in enumerate(P["names"])), flush=True)
        print(f"  {a.upper()} static: n {st['n']} PF {f2(st['pf'])} ret {fmt_ret(st['ret']).strip()}% "
              f"CAGR {fmt_ret(st['cagr']).strip()}% maxDD {fmt_ret(st['dd']).strip()}% MAR {f2(st['mar'])} "
              f"end equity {f2(st['eq'], 3)}", flush=True)
        rec("1", a, "static", "n", st["n"]); rec("1", a, "static", "PF", st["pf"])
        rec("1", a, "static", "ret", st["ret"]); rec("1", a, "static", "cagr", st["cagr"])
        rec("1", a, "static", "dd", st["dd"]); rec("1", a, "static", "mar", st["mar"])
    b, e = ctx["btc"]["base_en"], ctx["eth"]["base_en"]
    FIND.append(f"Static live mix (maxOpen 4): BTC ret {fmt_ret(b['st']['ret']).strip()}% CAGR {fmt_ret(b['st']['cagr']).strip()}% "
                f"maxDD {fmt_ret(b['st']['dd']).strip()}% MAR {f2(b['st']['mar'])} vs ETH ret {fmt_ret(e['st']['ret']).strip()}% "
                f"MAR {f2(e['st']['mar'])}.")

def section2(ctx):
    print("\n=== 2) TILT / CUT / RANK-PROPORTIONAL vs STATIC ===", flush=True)
    print("  Multipliers set each Monday from exits before that Monday. PnL = R * min(live_risk*m, trade_stop).", flush=True)
    print(HDR, flush=True)
    rng0 = np.random.default_rng(SEED)
    ctx["res"] = {}
    base_b, base_e = ctx["btc"]["base_en"], ctx["eth"]["base_en"]
    for name, kind, params in variant_specs():
        try:
            rows = {}
            for a in ("btc", "eth"):
                c = ctx[a]
                M = make_mult(kind, c["lists"], c["W"], c["P"]["base"], params or {})
                st = c["base_st"] if kind == "static" else run_path(c["P"], M, c["W"])
                en = enrich(st, c["base_st"])
                en["M"] = M
                rows[a] = en
                c["var"] = c.get("var", {})
                c["var"][name] = en
            b, e = rows["btc"], rows["eth"]
            if kind == "static":
                plc = NAN
            else:
                plc = plc_pct(b["st"]["mar"], placebo_mar(ctx["btc"]["P"], b["M"], ctx["btc"]["W"],
                                                          np.random.default_rng(SEED + 17 * (sum(ord(ch) for ch in name) + 31 * len(name)))))
            verd, fails = verdict_of(b, e, base_b, base_e, plc) if kind != "static" else ("baseline", [])
            if kind != "static":
                KEEP[name] = (verd, b["st"]["mar"], b["st"]["ret"], b["st"]["dd"], plc, b["beats"][0], e["beats"][0])
            yr = f"{b['beats'][0]}/7"
            ye = f"{e['beats'][0]}/7"
            print(f"  {name:<16} {b['st']['n']:>5} {f2(b['st']['pf']):>5} {fmt_ret(b['st']['ret']):>8} "
                  f"{fmt_ret(b['st']['cagr']):>7} {fmt_ret(b['st']['dd']):>7} {f2(b['st']['mar']):>6} "
                  f"{fmt_ret(b['h1']['ret']):>8} {fmt_ret(b['h1']['dd']):>8} {f2(b['h1']['mar']):>6} "
                  f"{fmt_ret(b['h2']['ret']):>8} {fmt_ret(b['h2']['dd']):>8} {f2(b['h2']['mar']):>6} "
                  f"{yr:>5} {fmt_ret(e['st']['ret']):>8} {f2(e['st']['mar']):>7} {ye:>5} {f2(plc,0):>5}  {verd}", flush=True)
            for metric, val in (("n", b["st"]["n"]), ("PF", b["st"]["pf"]), ("ret", b["st"]["ret"]),
                                ("cagr", b["st"]["cagr"]), ("dd", b["st"]["dd"]), ("mar", b["st"]["mar"]),
                                ("ret_17_20", b["h1"]["ret"]), ("dd_17_20", b["h1"]["dd"]), ("mar_17_20", b["h1"]["mar"]),
                                ("ret_21_26", b["h2"]["ret"]), ("dd_21_26", b["h2"]["dd"]), ("mar_21_26", b["h2"]["mar"]),
                                ("yrs_btc", b["beats"][0]), ("eth_ret", e["st"]["ret"]), ("eth_mar", e["st"]["mar"]),
                                ("yrs_eth", e["beats"][0]), ("placebo", plc),
                                ("keep", 1.0 if verd == "KEEP_LIVE" else 0.0)):
                rec("2", "btc", name, metric, val)
            for y in YEARS:
                rec("2", "btc", name, f"ret_{y}", b["yrs"].get(y, NAN))
                rec("2", "eth", name, f"ret_{y}", e["yrs"].get(y, NAN))
            # findings line for non-static
            if kind != "static":
                FIND.append(f"{name}: BTC MAR {f2(b['st']['mar'])} vs baseline {f2(base_b['st']['mar'])}, "
                            f"ret {fmt_ret(b['st']['ret']).strip()}% vs {fmt_ret(base_b['st']['ret']).strip()}%, "
                            f"maxDD {fmt_ret(b['st']['dd']).strip()}% vs {fmt_ret(base_b['st']['dd']).strip()}%, "
                            f"beats {b['beats'][0]}/7 years BTC and {e['beats'][0]}/7 ETH, placebo {f2(plc,0)}; {verd}.")
            ctx["res"][name] = (b, e, plc, verd)
        except Exception as ex:
            print(f"  {name} ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=2)

def section3(ctx):
    print("\n=== 3) WHO GOT THE TILT (share of weeks, BTC) ===", flush=True)
    c = ctx["btc"]
    names = c["P"]["names"]
    U = len(names)
    for name, kind, params in variant_specs():
        if kind == "static" or name not in c.get("var", {}):
            continue
        M = c["var"][name]["M"]
        if not len(M):
            continue
        # skip leading all-ones weeks in the share
        active = ~np.all(np.isclose(M, 1.0), axis=1)
        if not active.any():
            Mw = M
        else:
            Mw = M[active]
        nW = len(Mw)
        if kind == "tilt":
            top = (Mw >= 1.49).sum(0)
            bot = (Mw <= 0.51).sum(0)
            bits = [f"{nm} top {top[i]}/{nW} bot {bot[i]}/{nW}" for i, nm in enumerate(names)]
            print(f"  {name}: " + " | ".join(bits), flush=True)
            for i, nm in enumerate(names):
                rec("3", "btc", f"{name}:{nm}", "top_share", top[i] / nW if nW else NAN)
        elif kind == "cut":
            paused = (Mw < 0.99).sum(0)
            bits = [f"{nm} {'paused' if not (params or {}).get('soft') else 'cut'} {paused[i]}/{nW}" for i, nm in enumerate(names)]
            print(f"  {name}: " + " | ".join(bits), flush=True)
            for i, nm in enumerate(names):
                rec("3", "btc", f"{name}:{nm}", "cut_share", paused[i] / nW if nW else NAN)
        elif kind == "prop":
            med = np.median(Mw, 0)
            bits = [f"{nm} med m {med[i]:.2f}" for i, nm in enumerate(names)]
            print(f"  {name}: " + " | ".join(bits), flush=True)
            for i, nm in enumerate(names):
                rec("3", "btc", f"{name}:{nm}", "med_m", med[i])

# ---------------------------------------------------------------------------
def build_asset(df, fund):
    try:
        eng = engines(df, fund=fund)
    except Exception as ex:
        print(f"    engines() error {type(ex).__name__}: {ex}", flush=True)
        traceback.print_exc(limit=2)
        eng = {}
    P = pack_trades(eng)
    print("    packed " + " ".join(f"{nm} {int((P['unit']==i).sum())}" for i, nm in enumerate(P["names"]))
          + f"  (n {P['n']})", flush=True)
    lists = build_exit_lists(P)
    W = weekly_grid(P)
    # warmup atr/sma so the public helpers are used (and fail loudly if missing)
    if "close" in df and len(df) > 60:
        _ = sma(df["close"].to_numpy(dtype=float), 50)
        if all(k in df for k in ("high", "low", "close")):
            _ = atr(df["high"].to_numpy(dtype=float), df["low"].to_numpy(dtype=float),
                    df["close"].to_numpy(dtype=float), 14)
    M0 = mult_static(len(P["base"]), len(W))
    st = run_path(P, M0, W)
    en = enrich(st, st)
    en["M"] = M0
    return dict(df=df, fund=fund, eng=eng, P=P, lists=lists, W=W, base_st=st, base_en=en)

def main(smoke=False):
    ctx = {}
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        n = int(os.environ.get("TILT_SMOKE_N", str(24 * 1400)))
        b1 = synthetic_1h(n=n, seed=9, start="2017-07-01")
        e1 = synthetic_1h(n=n, seed=21, start="2017-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()}...", 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)
            empty = pack_trades({})
            ctx[a] = dict(df=raw[a][0], fund=raw[a][1], eng={}, P=empty, lists=build_exit_lists(empty),
                          W=np.array([], dtype="int64"), base_st=empty_stats(),
                          base_en=enrich(empty_stats(), empty_stats()))
        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_LIVE"]
    near = sorted([(v[1], k) for k, v in KEEP.items() if v[0] != "KEEP_LIVE" and np.isfinite(v[1])], reverse=True)[:6]
    print(f"  - Variants that pass every KEEP_LIVE gate: {', '.join(keeps) if keeps else 'none'}.", flush=True)
    if near:
        print("  - Best of the rest by BTC MAR (failed gates): " + "; ".join(
            f"{k} MAR {v:.2f} {KEEP[k][0]}" for v, k in near) + ".", flush=True)
    print("  KEEP_LIVE gates: MAR > baseline in both halves, beats baseline in >=5/7 years 2020-2026 BTC "
          "and >=4/7 ETH, placebo >= 90, maxDD not worse than baseline by more than 3 pts.", flush=True)

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