# ===== wf_i09.py - robustness + walk-forward test of batch17 idea I09 (fresh-high red-day pullback long) =====
# Colab:  !wget -q -O wf_i09.py https://osom-boba.pages.dev/colab/wf_i09.py
#         %run wf_i09.py
# Box (synthetic smoke only):  python3 wf_i09.py --smoke
#
# I09 (batch17): daily UTC bars from 1h. Signal at day k close: prior close = highest close of the prior N days
#   AND day k red AND close > lowest low of the prior LL days -> long at next day open.
#   Stop = day-k low - S x ATR14; exit at a day close < lowest low of the prior X days; cap 15 days.
#   Defaults N20 / LL10 / S0.5 / X3. Simulator, metrics and basket math copied unchanged from batch17.py.
# Live basket = oslib.engines(df, fund=funding(asset,'binance')) at oslib.LIVE_RISK (X7 on), 2017+.
# Sections:
#   1) plateau grid N x LL x S x X (162 combos)       2) regime filters on the default (each alone)
#   3) walk-forward: test years 2020..2026, params (grid x filters incl none) picked on 2017..Y-1 by the
#      MAR of basket + I09 @0.5%, applied unchanged to year Y; OOS years stitched; BTC and ETH separately
#   4) fixed default N20 + the best single filter picked on 2017-2020 only -> OOS 2021-26
#   5) I10 (6 higher closes) trades that do not overlap any default I09 trade
# Verdict: KEEP_LIVE if BTC stitched beats baseline MAR in >=5/7 years, ETH >=4/7, and BTC OOS I09 PF 2021-26 > 1.2.
import os, sys, time, traceback, subprocess, itertools
from pathlib import Path

T0 = time.time()
OSLIB_URL = "https://osom-boba.pages.dev/colab/oslib.py"

def _ensure_oslib():
    here = Path.cwd() / "oslib.py"
    if not here.exists():
        print("oslib.py missing -> downloading " + OSLIB_URL, flush=True)
        try:
            subprocess.run(["wget", "-q", "-O", str(here), OSLIB_URL], check=True)
        except Exception:
            from urllib.request import urlopen, Request
            raw = urlopen(Request(OSLIB_URL, headers={"User-Agent": "osom-wfi09/1.0"}), timeout=120).read()
            here.write_bytes(raw)
    if str(Path.cwd()) not in sys.path:
        sys.path.insert(0, str(Path.cwd()))

_ensure_oslib()
import numpy as np
import pandas as pd
import oslib
from oslib import (load, funding, engines, standardize, atr, sma, adx, synthetic_1h, in_colab,
                   tstats, _tframe, _window, COST, RISK, LIVE_RISK, HEADLINE_START, H1, D1)

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

W1 = 7 * D1
MON_OFF = 4 * D1          # 1970-01-05 00:00 UTC was a Monday
GRID_N = [10, 15, 20, 25, 30, 40]
GRID_LL = [5, 10, 20]
GRID_S = [0.25, 0.5, 1.0]
GRID_X = [2, 3, 5]
DEFAULT = (20, 10, 0.5, 3)
CAP = 15
FILTERS = ["none", "c>sma200", "sma50>sma200", "sma200_slope20", "wk_c>wsma20", "adx14>20", "x7_fund"]

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

def f1(x, nd=1):
    try:
        return "-" if x is None or not np.isfinite(x) else f"{x:.{nd}f}"
    except Exception:
        return "-"

def ptxt(p):
    N, LL, S, X, F = p
    return f"N{N}/LL{LL}/S{S}/X{X}/{F}"

# ---------------------------------------------------------------------------
# Bars + simulator (copied from batch17.py)
# ---------------------------------------------------------------------------
class Base:
    def __init__(self, df):
        self.df = df
        self.t = df["time"].to_numpy(np.int64)
        self.o = df["open"].to_numpy(float)
        self.h = df["high"].to_numpy(float)
        self.l = df["low"].to_numpy(float)
        self.c = df["close"].to_numpy(float)
        self.v = df["volume"].to_numpy(float) if "volume" in df.columns else np.zeros(len(df))
        self.n = len(self.t)

def htf(B, period, offset=0):
    """Higher-timeframe bars from 1h with 1h index ranges. Drops the last bar if incomplete."""
    g = (B.t - offset) // period
    _, i0 = np.unique(g, return_index=True)
    i1 = np.r_[i0[1:] - 1, B.n - 1]
    X = pd.DataFrame({
        "time": g[i0] * period + offset,
        "open": B.o[i0], "close": B.c[i1],
        "high": np.maximum.reduceat(B.h, i0), "low": np.minimum.reduceat(B.l, i0),
        "volume": np.add.reduceat(B.v, i0), "i0": i0, "i1": i1})
    if len(X) and B.t[-1] + H1 < X["time"].iloc[-1] + period:
        X = X.iloc[:-1].reset_index(drop=True)
    return X

def prior_min(x, n):
    return pd.Series(x).rolling(n, min_periods=n).min().shift(1).to_numpy()

def prior_max(x, n):
    return pd.Series(x).rolling(n, min_periods=n).max().shift(1).to_numpy()

def clv(X):
    rng = (X["high"] - X["low"]).to_numpy(float)
    with np.errstate(invalid="ignore", divide="ignore"):
        return np.where(rng > 0, (X["close"].to_numpy(float) - X["low"].to_numpy(float)) / rng, np.nan)

def hlc(X):
    return X["high"].to_numpy(float), X["low"].to_numpy(float), X["close"].to_numpy(float)

# ---------------------------------------------------------------------------
# Generic single-position simulator on HTF signals, stops walked on 1h bars
# ---------------------------------------------------------------------------
def run_htf(B, X, side, sig, stop_px=None, stop_dist=None, exit_cond=None, cap=None, time_exit=None, name=""):
    """sig[k] True at close of HTF bar k -> fill at open of bar k+1.
    stop_px[k]: absolute stop price, or stop_dist[k]: distance from the fill (price units).
    exit_cond[j] / time_exit[j]: exit at close of bar j. cap: max HTF bars held (fill bar = 1)."""
    nX = len(X)
    i0 = X["i0"].to_numpy(int); i1 = X["i1"].to_numpy(int)
    sig = np.asarray(sig, bool)
    ex = np.zeros(nX, bool) if exit_cond is None else np.nan_to_num(np.asarray(exit_cond, float), nan=0).astype(bool)
    te = np.zeros(nX, bool) if time_exit is None else np.asarray(time_exit, bool)
    trades = []
    free = 0
    for k in range(nX - 1):
        if not sig[k] or k < free:
            continue
        a = i0[k + 1]
        fill = float(B.o[a])
        if stop_px is not None and np.isfinite(stop_px[k]):
            stp = float(stop_px[k])
        elif stop_dist is not None and np.isfinite(stop_dist[k]) and stop_dist[k] > 0:
            stp = fill - side * float(stop_dist[k])
        else:
            continue
        if not (np.isfinite(fill) and fill > 0 and side * (fill - stp) > 0):
            continue
        risk = abs(fill - stp) / fill
        xi, xpx, why, jx = B.n - 1, float(B.c[-1]), "OPEN", nX - 1
        for j in range(k + 1, nX):
            s0, s1 = i0[j], i1[j] + 1
            hit = np.flatnonzero(B.l[s0:s1] <= stp) if side > 0 else np.flatnonzero(B.h[s0:s1] >= stp)
            if len(hit):
                q = s0 + int(hit[0])
                xi = q; xpx = float(min(stp, B.o[q]) if side > 0 else max(stp, B.o[q])); why = "SL"; jx = j
                break
            held = j - k
            if te[j] or ex[j] or (cap is not None and held >= cap):
                xi = i1[j]; xpx = float(B.c[i1[j]]); jx = j
                why = "TIME" if te[j] else ("TRAIL" if ex[j] else "CAP")
                break
        ret = side * (xpx / fill - 1.0) - 2 * COST
        trades.append(dict(entry_time=int(B.t[a]), exit_time=int(B.t[xi]), side=int(side), entry=fill, stop=stp,
                           exit=xpx, risk=risk, ret=ret, R=ret / risk, why=why, src=name,
                           ei=int(a), xi=int(xi), gross=100.0 * abs(xpx / fill - 1.0)))
        free = jx
    return trades


def _pf(arr):
    a = np.asarray(arr, float); a = a[np.isfinite(a)]
    g = a[a > 0].sum(); ls = -a[a < 0].sum()
    return (g / ls) if ls > 0 else (np.inf if g > 0 else np.nan)

def _win(trades, start=HEADLINE_START):
    t0 = ms(start)
    return [t for t in trades if t["exit_time"] >= t0 and np.isfinite(t["R"])]


def tstat_window(trades, a, z=None):
    tr = sorted(standardize(trades), key=lambda x: x["exit_time"])
    return tstats(_window(_tframe(tr), a, z))

def metrics(trades):
    w = sorted(_win(trades), key=lambda x: x["exit_time"])
    st = tstat_window(w, HEADLINE_START)
    h1 = tstat_window(w, "2017-01-01", "2021-01-01"); h2 = tstat_window(w, "2021-01-01")
    y18 = tstat_window(w, "2018-01-01", "2019-01-01"); y22 = tstat_window(w, "2022-01-01", "2023-01-01")
    last30 = _pf([t["R"] for t in w[-30:]]) if w else np.nan
    return dict(n=int(st["tr"]), win=st["win"], pf=st["pf"], avgR=st["avgR"], ret=st["ret"], dd=st["dd"],
                gross=float(np.mean([t["gross"] for t in w])) if w else np.nan,
                pf_h1=h1["pf"], n_h1=int(h1["tr"]), pf_h2=h2["pf"], n_h2=int(h2["tr"]), pf_l30=last30,
                ret18=(y18["ret"] if y18["tr"] else 0.0), n18=int(y18["tr"]),
                ret22=(y22["ret"] if y22["tr"] else 0.0), n22=int(y22["tr"]))


def basket_curve(eng, extra=None, extra_risk=0.01, start=HEADLINE_START):
    """Same math as oslib.overlay: pnl = R * min(risk_pct, trade stop frac), summed per exit stamp, compounded."""
    t0 = ms(start); by = {}
    def add(trs, rp):
        for t in standardize(trs):
            if t["exit_time"] < t0 or not (np.isfinite(t["risk"]) and t["risk"] > 0 and np.isfinite(t["R"])):
                continue
            by[t["exit_time"]] = by.get(t["exit_time"], 0.0) + t["R"] * min(rp, t["risk"])
    for nm, trs in eng.items():
        add(trs, LIVE_RISK.get(nm, RISK))
    if extra:
        add(extra, extra_risk)
    eq = 1.0; pk = 1.0; mdd = 0.0
    for ts in sorted(by):
        eq *= 1.0 + by[ts]; pk = max(pk, eq); mdd = min(mdd, eq / pk - 1.0)
    ret, dd = 100 * (eq - 1.0), 100 * mdd
    return dict(ret=ret, maxDD=dd, MAR=(ret / abs(dd) if dd < 0 else np.nan))


# ---------------------------------------------------------------------------
# I09 parametrised (default == batch17 i09) + I10 (copied from batch17.py)
# ---------------------------------------------------------------------------
class Day:
    """Daily bars + everything the I09 grid and filters need, computed once per asset."""
    def __init__(self, B, fund=None):
        self.B = B
        X = htf(B, D1); self.X = X
        h, l, c = hlc(X); o = X["open"].to_numpy(float)
        self.h, self.l, self.c, self.o = h, l, c, o
        self.a14 = atr(h, l, c, 14)
        self.prev_c = np.r_[np.nan, c[:-1]]
        self.red = c < o
        self.hc = {N: pd.Series(c).rolling(N, min_periods=N).max().shift(1).to_numpy() for N in GRID_N}
        self.ll = {n: prior_min(l, n) for n in sorted(set(GRID_LL) | set(GRID_X))}
        self.filt = self._filters(fund)

    def _filters(self, fund):
        c, h, l = self.c, self.h, self.l
        n = len(c)
        s50, s200 = sma(c, 50), sma(c, 200)
        with np.errstate(invalid="ignore"):
            F = {"none": np.ones(n, bool)}
            F["c>sma200"] = np.nan_to_num(c > s200, nan=0).astype(bool) & np.isfinite(s200)
            F["sma50>sma200"] = np.isfinite(s50) & np.isfinite(s200) & (s50 > s200)
            s200p = np.r_[np.full(20, np.nan), s200[:-20]] if n > 20 else np.full(n, np.nan)
            F["sma200_slope20"] = np.isfinite(s200) & np.isfinite(s200p) & (s200 > s200p)
            # weekly (Monday 00:00 UTC) close > weekly SMA20, last week fully closed at the day-k close
            W = htf(self.B, W1, MON_OFF)
            wc = W["close"].to_numpy(float); ws = sma(wc, 20)
            wend = W["time"].to_numpy(np.int64) + W1
            dend = self.X["time"].to_numpy(np.int64) + D1
            j = np.searchsorted(wend, dend, side="right") - 1
            ok = j >= 0; jj = np.clip(j, 0, max(len(wc) - 1, 0))
            wk = np.zeros(n, bool)
            if len(wc):
                wk = ok & np.isfinite(ws[jj]) & (wc[jj] > ws[jj])
            F["wk_c>wsma20"] = wk
            ad, _, _ = adx(h, l, c, 14)
            F["adx14>20"] = np.isfinite(ad) & (ad > 20)
            # X7-style funding filter: skip a long if the sum of the last 3 settlements known at the day close
            # is >= the 90th percentile of that 3-settlement sum over the prior 365 days. No data -> allowed.
            allow = np.ones(n, bool)
            if fund is not None and len(fund) > 10:
                f = fund[["time", "funding"]].dropna().sort_values("time").drop_duplicates("time")
                s3 = f["funding"].rolling(3, min_periods=3).sum()
                ser = pd.Series(s3.to_numpy(), index=pd.to_datetime(f["time"].to_numpy(np.int64), unit="ms", utc=True))
                thr = ser.rolling("365D", min_periods=300, closed="left").quantile(0.90)
                ft = f["time"].to_numpy(np.int64)
                k = np.searchsorted(ft, dend, side="right") - 1
                okk = k >= 0; kk = np.clip(k, 0, len(ft) - 1)
                sv, tv = ser.to_numpy()[kk], thr.to_numpy()[kk]
                hot = okk & np.isfinite(sv) & np.isfinite(tv) & (sv >= tv)
                allow = ~hot
            F["x7_fund"] = allow
        return F

    def i09(self, N=20, LL=10, S=0.5, Xl=3, filt="none"):
        with np.errstate(invalid="ignore"):
            sig = (self.prev_c >= self.hc[N]) & self.red & (self.c > self.ll[LL]) & self.filt[filt]
        return run_htf(self.B, self.X, 1, sig, stop_px=self.l - S * self.a14, exit_cond=self.c < self.ll[Xl],
                       cap=CAP, name="I09")

def i10(B):
    X = htf(B, D1); h, l, c = hlc(X); a14 = atr(h, l, c, 14)
    up = np.r_[False, c[1:] > c[:-1]]
    streak = np.zeros(len(c), int)
    for i in range(1, len(c)):
        streak[i] = streak[i - 1] + 1 if up[i] else 0
    sig = streak == 6
    return run_htf(B, X, 1, sig, stop_dist=2.5 * a14, exit_cond=c < prior_min(l, 3), cap=12, name="I10")


def overlap_pct(A, Bt):
    """% of A's trades whose holding window overlaps any trade of B."""
    if not A or not Bt:
        return np.nan
    bi = np.array([t["entry_time"] for t in Bt]); bo = np.array([t["exit_time"] for t in Bt])
    hit = sum(1 for t in A if np.any((bi <= t["exit_time"]) & (bo >= t["entry_time"])))
    return 100.0 * hit / len(A)

# ---------------------------------------------------------------------------
# Fast basket book (same math as batch17 basket_curve / oslib.overlay; verified below)
# ---------------------------------------------------------------------------
def to_arr(trades, rp):
    st = [t for t in standardize(trades) if np.isfinite(t["risk"]) and t["risk"] > 0 and np.isfinite(t["R"])]
    if not st:
        return np.zeros(0, np.int64), np.zeros(0)
    return (np.array([t["exit_time"] for t in st], np.int64),
            np.array([t["R"] * min(rp, t["risk"]) for t in st], float))

def base_arr(eng):
    ts, ps = [], []
    for nm, trs in eng.items():
        a, b = to_arr(trs, LIVE_RISK.get(nm, RISK)); ts.append(a); ps.append(b)
    return np.concatenate(ts) if ts else np.zeros(0, np.int64), np.concatenate(ps) if ps else np.zeros(0)

def curve(parts, lo, hi):
    ts = np.concatenate([p[0] for p in parts]); ps = np.concatenate([p[1] for p in parts])
    m = (ts >= lo) & (ts < hi)
    ts, ps = ts[m], ps[m]
    if len(ts) == 0:
        return dict(ret=0.0, maxDD=0.0, MAR=np.nan, n=0)
    u, inv = np.unique(ts, return_inverse=True)
    g = np.bincount(inv, weights=ps, minlength=len(u))
    eq = np.cumprod(1.0 + g)
    pk = np.maximum.accumulate(np.r_[1.0, eq])[1:]
    mdd = min(0.0, float((eq / pk - 1.0).min()))
    ret, dd = 100 * (eq[-1] - 1.0), 100 * mdd
    return dict(ret=ret, maxDD=dd, MAR=(ret / abs(dd) if dd < 0 else np.nan), n=len(ts))

def score(s):
    m = s["MAR"]
    if np.isfinite(m):
        return m
    return 1e6 + s["ret"] if s["ret"] > 0 else (-1e6 + s["ret"])

def beats(a, b):
    return score(a) > score(b) + 1e-12

def pf_win(trades, lo, hi):
    return _pf([t["R"] for t in trades if lo <= t["exit_time"] < hi and np.isfinite(t["R"])])

def n_win(trades, lo, hi):
    return sum(1 for t in trades if lo <= t["exit_time"] < hi and np.isfinite(t["R"]))

def mrow(m):
    return dict(n=m["n"], PF=m["pf"], PF_17_20=m["pf_h1"], PF_21_26=m["pf_h2"], n_21_26=m["n_h2"],
                PF_last30=m["pf_l30"], ret_pct=m["ret"], maxDD_pct=m["dd"], ret_2018=m["ret18"], ret_2022=m["ret22"])

# ---------------------------------------------------------------------------
# Per-asset run
# ---------------------------------------------------------------------------
def run_asset(label, df, fund, years, end_ms, smoke=False):
    rows, S = [], {}
    t_a = time.time()
    B = Base(df)
    print(f"\n######## {label.upper()} ########", flush=True)
    eng = engines(df, fund=fund)
    print("  basket: " + ", ".join(f"{k} {len(v)}" for k, v in eng.items()) + f"  ({time.time()-t_a:.0f}s)", flush=True)
    BA = base_arr(eng)
    t0 = ms(HEADLINE_START)
    base_full = curve([BA], t0, end_ms)
    chk = basket_curve(eng)
    print(f"  baseline 2017+ ret {f1(base_full['ret'])}% maxDD {f1(base_full['maxDD'],2)}% MAR {f1(base_full['MAR'],2)}"
          f"  (batch17 basket_curve check MAR {f1(chk['MAR'],2)})", flush=True)
    Dy = Day(B, fund)
    print("  filter pass rate (% of days): " + ", ".join(f"{k} {100*np.mean(Dy.filt[k]):.0f}" for k in FILTERS), flush=True)

    # all configs once (grid x filters)
    CFG = {}
    t_c = time.time()
    for N, LL, Sx, Xl in itertools.product(GRID_N, GRID_LL, GRID_S, GRID_X):
        for F in FILTERS:
            CFG[(N, LL, Sx, Xl, F)] = Dy.i09(N, LL, Sx, Xl, F)
    print(f"  simulated {len(CFG)} I09 configs ({time.time()-t_c:.0f}s)", flush=True)
    dflt = DEFAULT + ("none",)
    tb = CFG[dflt]
    # batch17 identity check: default config vs i09 recomputed the batch17 way
    try:
        X = htf(B, D1); h, l, c = hlc(X); o = X["open"].to_numpy(float); a14 = atr(h, l, c, 14)
        hc20 = pd.Series(c).rolling(20, min_periods=20).max().shift(1).to_numpy(); pc = np.r_[np.nan, c[:-1]]
        ref = run_htf(B, X, 1, (pc >= hc20) & (c < o) & (c > prior_min(l, 10)), stop_px=l - 0.5 * a14,
                      exit_cond=c < prior_min(l, 3), cap=15, name="I09")
        same = len(ref) == len(tb) and all(abs(a["R"] - b["R"]) < 1e-12 for a, b in zip(ref, tb))
        print(f"  default == batch17 i09: {same} (n {len(tb)})", flush=True)
    except Exception as e:
        print(f"  batch17 identity check failed: {e}", flush=True)

    # ---------------- 1) plateau grid ----------------
    try:
        print(f"\n=== 1) {label.upper()} PLATEAU GRID (no filter, 1% risk, 2017+) ===", flush=True)
        g = []
        for N, LL, Sx, Xl in itertools.product(GRID_N, GRID_LL, GRID_S, GRID_X):
            m = metrics(CFG[(N, LL, Sx, Xl, "none")])
            g.append(dict(asset=label, section="grid", N=N, LL=LL, S=Sx, X=Xl, filter="none", **mrow(m)))
        G = pd.DataFrame(g)
        rows += g
        cols = ["N", "LL", "S", "X", "n", "PF", "PF_17_20", "PF_21_26", "n_21_26", "PF_last30", "ret_2022"]
        with pd.option_context("display.float_format", lambda x: f"{x:.2f}", "display.width", 200):
            print("  default row:", flush=True)
            print(G[(G.N == 20) & (G.LL == 10) & (G.S == 0.5) & (G.X == 3)][cols].to_string(index=False), flush=True)
            print("  top 10 by PF_21_26 (n_21_26 >= 20):", flush=True)
            print(G[G.n_21_26 >= 20].sort_values("PF_21_26", ascending=False).head(10)[cols].to_string(index=False), flush=True)
            print("  bottom 5 by PF_21_26:", flush=True)
            print(G.sort_values("PF_21_26").head(5)[cols].to_string(index=False), flush=True)
        good = (G.PF_21_26 > 1.2)
        print(f"  HEAT: {good.sum()}/{len(G)} = {100*good.mean():.0f}% of grid has PF_21_26 > 1.2 | "
              f"PF all > 1.3: {100*(G.PF > 1.3).mean():.0f}% | both halves > 1.2: {100*((G.PF_17_20 > 1.2) & good).mean():.0f}% | "
              f"2022 ret > 0: {100*(G.ret_2022 > 0).mean():.0f}%", flush=True)
        for dim in ["N", "LL", "S", "X"]:
            t = G.groupby(dim).agg(frac=("PF_21_26", lambda s: 100 * np.mean(s > 1.2)), med21=("PF_21_26", "median"),
                                   medPF=("PF", "median"), med22=("ret_2022", "median"))
            print(f"  by {dim:2s}: " + " | ".join(f"{k}: {v.frac:.0f}% med21 {v.med21:.2f} medPF {v.medPF:.2f} 22 {v.med22:.1f}"
                                                for k, v in t.iterrows()), flush=True)
        S["heat"] = float(good.mean())
    except Exception as e:
        print(f"  section 1 ERROR {type(e).__name__}: {e}", flush=True); traceback.print_exc()

    # ---------------- 2) regime filters ----------------
    try:
        print(f"\n=== 2) {label.upper()} REGIME FILTERS on default N20/LL10/S0.5/X3 (each alone) ===", flush=True)
        fr = []
        for F in FILTERS:
            m = metrics(CFG[DEFAULT + (F,)])
            r = dict(asset=label, section="filter", N=20, LL=10, S=0.5, X=3, filter=F, **mrow(m))
            for rp, tag in ((0.005, "05"), (0.01, "1")):
                s = curve([BA, to_arr(CFG[DEFAULT + (F,)], rp)], t0, end_ms)
                r[f"basket_MAR_{tag}"] = s["MAR"]
            fr.append(r)
        FR = pd.DataFrame(fr); rows += fr
        cols = ["filter", "n", "PF", "PF_17_20", "PF_21_26", "ret_2018", "ret_2022", "PF_last30", "basket_MAR_05", "basket_MAR_1"]
        print(f"  baseline basket MAR {f1(base_full['MAR'],2)}", flush=True)
        with pd.option_context("display.float_format", lambda x: f"{x:.2f}", "display.width", 200):
            print(FR[cols].to_string(index=False), flush=True)
    except Exception as e:
        print(f"  section 2 ERROR {type(e).__name__}: {e}", flush=True); traceback.print_exc()

    # ---------------- 3) walk-forward ----------------
    ARR05 = {p: to_arr(tr, 0.005) for p, tr in CFG.items()}
    ARR1 = {p: to_arr(tr, 0.01) for p, tr in CFG.items()}
    try:
        print(f"\n=== 3) {label.upper()} WALK-FORWARD (pick on 2017..Y-1 by MAR basket+I09@0.5%, test Y) ===", flush=True)
        chosen, wins05, wins1, oos_tr = {}, 0, 0, []
        parts_b, parts_05, parts_1 = [BA], [BA], [BA]
        ny = 0
        for Y in years:
            lo, hi = ms(f"{Y}-01-01"), min(ms(f"{Y+1}-01-01"), end_ms)
            if lo >= end_ms:
                continue
            best, bsc = None, -np.inf
            for p in CFG:
                sc = score(curve([BA, ARR05[p]], t0, lo))
                if sc > bsc + 1e-12 or (best is None):
                    best, bsc = p, sc
            chosen[Y] = best
            sb = curve([BA], lo, hi)
            s05 = curve([BA, ARR05[best]], lo, hi); s1 = curve([BA, ARR1[best]], lo, hi)
            w05, w1 = beats(s05, sb), beats(s1, sb)
            wins05 += int(w05); wins1 += int(w1); ny += 1
            yt = [t for t in CFG[best] if lo <= t["exit_time"] < hi]
            oos_tr += yt
            print(f"  {Y}: pick {ptxt(best):32s} train MAR {f1(bsc,2):>8s} | test base MAR {f1(sb['MAR'],2):>7s} ret {f1(sb['ret']):>6s}% "
                  f"| +I09@0.5 MAR {f1(s05['MAR'],2):>7s} ret {f1(s05['ret']):>6s}% {'WIN' if w05 else 'lose'} "
                  f"| @1 MAR {f1(s1['MAR'],2):>7s} | I09 n {len(yt)} PF {f1(_pf([t['R'] for t in yt]),2)}", flush=True)
            rows.append(dict(asset=label, section="wf_fold", year=Y, params=ptxt(best), train_MAR=bsc,
                             base_MAR=sb["MAR"], base_ret=sb["ret"], MAR_05=s05["MAR"], ret_05=s05["ret"], MAR_1=s1["MAR"],
                             ret_1=s1["ret"], win_05=w05, win_1=w1, n=len(yt), PF=_pf([t["R"] for t in yt])))
        lo0 = ms(f"{years[0]}-01-01")
        oos05 = to_arr(oos_tr, 0.005); oos1 = to_arr(oos_tr, 0.01)
        sb = curve([BA], lo0, end_ms); s05 = curve([BA, oos05], lo0, end_ms); s1 = curve([BA, oos1], lo0, end_ms)
        h2 = ms("2021-01-01")
        pf21, n21 = pf_win(oos_tr, h2, end_ms), n_win(oos_tr, h2, end_ms)
        print(f"  STITCHED {years[0]}..{years[-1]}: baseline ret {f1(sb['ret'])}% maxDD {f1(sb['maxDD'],2)}% MAR {f1(sb['MAR'],2)}", flush=True)
        print(f"                 +I09@0.5%  ret {f1(s05['ret'])}% maxDD {f1(s05['maxDD'],2)}% MAR {f1(s05['MAR'],2)}  years beat {wins05}/{ny}", flush=True)
        print(f"                 +I09@1.0%  ret {f1(s1['ret'])}% maxDD {f1(s1['maxDD'],2)}% MAR {f1(s1['MAR'],2)}  years beat {wins1}/{ny}", flush=True)
        print(f"  OOS I09 trades: n {len(oos_tr)} PF {f1(_pf([t['R'] for t in oos_tr]),2)} | 2021-26 n {n21} PF {f1(pf21,2)}", flush=True)
        cnt = pd.Series([ptxt(p) for p in chosen.values()]).value_counts()
        print("  pick frequency: " + "; ".join(f"{k} x{v}" for k, v in cnt.items()), flush=True)
        for tag, s in (("baseline", sb), ("I09@0.5", s05), ("I09@1", s1)):
            rows.append(dict(asset=label, section="wf_stitched", year=f"{years[0]}-{years[-1]}", params=tag,
                             ret=s["ret"], maxDD=s["maxDD"], MAR=s["MAR"],
                             years_beat=(wins05 if tag == "I09@0.5" else (wins1 if tag == "I09@1" else np.nan)),
                             n=len(oos_tr), PF_21_26=pf21))
        S.update(wins05=wins05, wins1=wins1, ny=ny, st_base=sb, st05=s05, st1=s1, pf21=pf21, n21=n21,
                 last_pick=chosen[max(chosen)] if chosen else None, picks=chosen)
    except Exception as e:
        print(f"  section 3 ERROR {type(e).__name__}: {e}", flush=True); traceback.print_exc()

    # ---------------- 4) fixed default + best single filter chosen on 2017-2020 ----------------
    try:
        cut = ms("2021-01-01")
        print(f"\n=== 4) {label.upper()} FIXED DEFAULT N20/LL10/S0.5/X3 + filter picked on 2017-2020 only ===", flush=True)
        best, bsc = None, -np.inf
        for F in FILTERS:
            sc = score(curve([BA, ARR05[DEFAULT + (F,)]], t0, cut))
            print(f"    train 2017-20 {F:15s} basket+I09@0.5 MAR {f1(sc,2)}", flush=True)
            if sc > bsc + 1e-12:
                best, bsc = F, sc
        p = DEFAULT + (best,)
        tr = CFG[p]
        pf, n = pf_win(tr, cut, end_ms), n_win(tr, cut, end_ms)
        sb = curve([BA], cut, end_ms); s05 = curve([BA, ARR05[p]], cut, end_ms); s1 = curve([BA, ARR1[p]], cut, end_ms)
        print(f"  picked filter: {best} | OOS 2021-26 I09 n {n} PF {f1(pf,2)}", flush=True)
        print(f"  OOS 2021-26 basket MAR {f1(sb['MAR'],2)} -> {f1(s05['MAR'],2)} @0.5% (delta {f1(s05['MAR']-sb['MAR'],2)}) "
              f"/ {f1(s1['MAR'],2)} @1% | ret {f1(sb['ret'])}% -> {f1(s05['ret'])}% / {f1(s1['ret'])}% | "
              f"maxDD {f1(sb['maxDD'],2)}% -> {f1(s05['maxDD'],2)}% / {f1(s1['maxDD'],2)}%", flush=True)
        rows.append(dict(asset=label, section="fixed_default", params=ptxt(p), n=n, PF_21_26=pf, base_MAR=sb["MAR"],
                         MAR_05=s05["MAR"], MAR_1=s1["MAR"], ret_05=s05["ret"], ret_1=s1["ret"]))
        S.update(fixed=p, fixed_pf=pf, fixed_d05=s05["MAR"] - sb["MAR"] if np.isfinite(s05["MAR"]) and np.isfinite(sb["MAR"]) else np.nan)
    except Exception as e:
        print(f"  section 4 ERROR {type(e).__name__}: {e}", flush=True); traceback.print_exc()

    # ---------------- 5) I10 dedup ----------------
    try:
        print(f"\n=== 5) {label.upper()} I10 (6 higher closes) trades not overlapping any default I09 trade ===", flush=True)
        t10 = _win(i10(B)); t9 = _win(tb)
        bi = np.array([t["entry_time"] for t in t9]); bo = np.array([t["exit_time"] for t in t9])
        solo = [t for t in t10 if not (len(bi) and np.any((bi <= t["exit_time"]) & (bo >= t["entry_time"])))]
        pfa = _pf([t["R"] for t in t10]); pfs = _pf([t["R"] for t in solo])
        h2 = ms("2021-01-01")
        print(f"  I10 all n {len(t10)} PF {f1(pfa,2)} | overlap with I09 {f1(overlap_pct(t10, t9),1)}% | "
              f"non-overlap n {len(solo)} PF {f1(pfs,2)} (2021-26 n {n_win(solo, h2, end_ms)} PF {f1(pf_win(solo, h2, end_ms),2)})", flush=True)
        rows.append(dict(asset=label, section="i10_dedup", n=len(solo), PF=pfs, n_all=len(t10), PF_all=pfa))
    except Exception as e:
        print(f"  section 5 ERROR {type(e).__name__}: {e}", flush=True); traceback.print_exc()
    print(f"  ({label} done in {time.time()-t_a:.0f}s)", flush=True)
    return rows, S

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main(smoke=False):
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        btc = synthetic_1h(n=24 * 1700, seed=9, start="2017-01-02")
        eth = synthetic_1h(n=24 * 1700, seed=21, start="2017-01-02", px0=300.0)
        rng = np.random.default_rng(0)
        fb = pd.DataFrame({"time": btc["time"].to_numpy()[::8], "funding": rng.normal(0, 1e-5, (len(btc) + 7) // 8)})
        fe = pd.DataFrame({"time": eth["time"].to_numpy()[::8], "funding": rng.normal(0, 1e-5, (len(eth) + 7) // 8)})
        years = [2019, 2020, 2021]
    else:
        btc, eth = load("btc", "1h"), load("eth", "1h")
        fb, fe = funding("btc", "binance"), funding("eth", "binance")
        years = list(range(2020, 2027))
    all_rows, S = [], {}
    for label, df, fund in (("btc", btc, fb), ("eth", eth, fe)):
        try:
            end_ms = int(df["time"].iloc[-1]) + H1
            r, s = run_asset(label, df, fund, years, end_ms, smoke)
            all_rows += r; S[label] = s
        except Exception as e:
            print(f"  {label} ERROR {type(e).__name__}: {e}", flush=True); traceback.print_exc()
            S[label] = {}

    try:
        b, e = S.get("btc", {}), S.get("eth", {})
        nb, ne = len(years), len(years)
        need_b = 5 if not smoke else 1; need_e = 4 if not smoke else 1
        wb, we = b.get("wins05", 0), e.get("wins05", 0)
        pf21 = b.get("pf21", np.nan)
        keep = wb >= need_b and we >= need_e and np.isfinite(pf21) and pf21 > 1.2
        paper = (not keep) and wb >= max(1, need_b - 1) and np.isfinite(pf21) and pf21 > 1.0
        v = "KEEP_LIVE" if keep else ("PAPER" if paper else "DROP")
        print(f"\n=== VERDICT: {v} ===", flush=True)
        print(f"  BTC stitched beat baseline {wb}/{b.get('ny', nb)} yrs (need {need_b}) | ETH {we}/{e.get('ny', ne)} (need {need_e}) | "
              f"BTC OOS I09 PF 2021-26 {f1(pf21,2)} (n {b.get('n21', 0)}, need > 1.2) | grid heat {f1(100*b.get('heat', np.nan),0)}%", flush=True)
        if b.get("st05"):
            print(f"  BTC stitched MAR baseline {f1(b['st_base']['MAR'],2)} | @0.5% {f1(b['st05']['MAR'],2)} | @1% {f1(b['st1']['MAR'],2)}", flush=True)
        if v != "DROP":
            r1 = b.get("st1", {}).get("MAR", np.nan); r05 = b.get("st05", {}).get("MAR", np.nan)
            rk = "1.0%" if (keep and np.isfinite(r1) and np.isfinite(r05) and r1 > r05 and b.get("wins1", 0) >= 6) else "0.5%"
            lp = b.get("last_pick"); fx = b.get("fixed")
            print(f"  recommend risk {rk} | params: latest fold pick (trained through {max(years)-1}) {ptxt(lp) if lp else '-'}; "
                  f"fixed-default alternative {ptxt(fx) if fx else '-'} (OOS PF 21-26 {f1(b.get('fixed_pf', np.nan),2)})", flush=True)
            print("  exits unchanged: stop day-low - S x ATR14 (1h-checked), exit close < LL of prior X days, cap 15d, long only.", flush=True)
        all_rows.append(dict(asset="btc", section="verdict", params=v, years_beat=wb, n=b.get("n21", 0), PF_21_26=pf21))
    except Exception as e:
        print(f"  verdict ERROR {type(e).__name__}: {e}", flush=True); traceback.print_exc()

    out_dir = Path("/content") if Path("/content").exists() else Path(".")
    path = out_dir / ("wf_i09_smoke.csv" if smoke else "wf_i09.csv")
    pd.DataFrame(all_rows).to_csv(path, index=False)
    print(f"\nSaved {path} ({len(all_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)
