# ===== wf_overlay.py - walk-forward test of the Batch 10 basket overlays A2 and A3 =====
# Colab:  !wget -q -O wf_overlay.py https://osom-boba.pages.dev/colab/wf_overlay.py
#         %run wf_overlay.py
# Box (synthetic smoke only):  python3 wf_overlay.py --smoke
#
# Baseline = oslib live basket (oslib.engines, X7 funding filter on by passing funding) at
# oslib.LIVE_RISK, 2017+, compounded on exit time (same math as oslib.overlay / batch10 basket_curve).
# A2 = batch10 "A2 proposed": vol-cycle state of the entry day (weekly BB(20,2) width percentile vs
#      trailing 156 weeks + daily ATR14/ATR100). COIL (pct<=15 and D<=1.0): breakout engines
#      (C1 C2 COCO D34) x1.5. EXPANSION (pct>=80 or D>=1.6): days 1-5 trend engines (K8 MOM30) x1.25,
#      breakout x0.75; day 6+ breakout x0.5. Tuned per fold: coil pct, expansion pct, coil mult, exp days.
# A3 = batch10 "A3 skip": skip C1/C2 entries whose day offset to the nearest monthly expiry
#      (last Friday 08:00 UTC) is inside lo..hi. Tuned per fold: lo..hi within -3..+2.
# A2+A3 = both, each with its own fold-chosen params.
# Walk-forward: test year Y = 2020..2026, train 2017-01-01 .. Y-01-01, pick by best train MAR,
# apply unchanged to Y. Test years are stitched into one compounded curve.
# KEEP an overlay only if stitched BTC MAR beats baseline AND it beats baseline in >= 5 of 7 years.
import os, sys, time, itertools, subprocess
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-wf/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, overlay, expiry_days, atr, bb_width, resample_ohlcv,
                   synthetic_1h, in_colab, LIVE_RISK, RISK, D1)

print(f"oslib v{oslib.__version__} | cost {100*oslib.COST:.2f}%/side | live risk {LIVE_RISK}", flush=True)

TREND_ENG = {"K8", "MOM30"}
BREAK_ENG = {"C1", "C2", "COCO", "D34"}
A3_ENG = ("C1", "C2")
ST_NORMAL, ST_COIL, ST_EXP = 0, 1, 2
# A2 search grid (batch10 values 15 / 80 / 1.5 / 5 are inside it)
A2_GRID = dict(coil_pct=[10, 15, 20], exp_pct=[75, 80, 85], coil_mult=[1.25, 1.5, 2.0], exp_days=[3, 5, 7])
A2_DEFAULT = dict(coil_pct=15, exp_pct=80, coil_mult=1.5, exp_days=5)
A3_WINDOWS = [(lo, hi) for lo in range(-3, 3) for hi in range(lo, 3)]
A3_REF = {"btc": ((-2, 1), ("C1", "C2")), "eth": ((-2, -2), ("C1", "C2", "K8"))}
START = "2017-01-01"

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

# ---------------------------------------------------------------------------
# A2 labels (batch10 label_A2, thresholds as parameters)
# ---------------------------------------------------------------------------
def a2_inputs(D):
    h, l, c = D.high.values, D.low.values, D.close.values
    a14 = atr(h, l, c, 14)
    a100 = atr(h, l, c, 100)
    Dv = a14 / np.where(a100 > 0, a100, np.nan)
    ts = pd.to_datetime(D["time"].values, unit="ms", utc=True)
    w = pd.DataFrame({"open": D.open.values, "high": h, "low": l, "close": c}, index=ts)
    weekly = w.resample("W-MON", label="left", closed="left").agg(
        open=("open", "first"), high=("high", "max"), low=("low", "min"), close=("close", "last")).dropna()
    _, _, _, wbw = bb_width(weekly["close"].to_numpy(dtype=float), 20, 2)
    wpct = pd.Series(wbw, index=weekly.index).rolling(156, min_periods=52).rank(pct=True) * 100.0
    w_pct_d = np.full(len(D), np.nan)
    if len(weekly):
        known = pd.DatetimeIndex(weekly.index + pd.Timedelta(days=7)).asi8
        j = np.searchsorted(known, ts.asi8, side="right") - 1
        ok = j >= 0
        w_val = wpct.to_numpy()
        w_pct_d[ok] = w_val[np.clip(j[ok], 0, len(w_val) - 1)]
    return w_pct_d, Dv

def a2_states(w_pct_d, Dv, coil_pct, exp_pct):
    st = np.full(len(Dv), ST_NORMAL, dtype=np.int8)
    coil = np.isfinite(w_pct_d) & np.isfinite(Dv) & (w_pct_d <= coil_pct) & (Dv <= 1.0)
    exp = (np.isfinite(w_pct_d) & (w_pct_d >= exp_pct)) | (np.isfinite(Dv) & (Dv >= 1.6))
    st[coil] = ST_COIL
    st[exp & ~coil] = ST_EXP
    return st

def day_in_state(st):
    n = len(st)
    out = np.zeros(n, dtype=int)
    if n == 0:
        return out
    chg = np.r_[True, st[1:] != st[:-1]]
    starts = np.flatnonzero(chg)
    lens = np.diff(np.r_[starts, n])
    for s0, ln in zip(starts, lens):
        out[s0:s0 + ln] = np.arange(1, ln + 1)
    return out

# ---------------------------------------------------------------------------
# A3 expiry offset (batch10 expiry_offset, vectorised, same rounding and tie rule)
# ---------------------------------------------------------------------------
def expiry_offsets(t_in, expiries):
    e_ms = np.array([int(e.value // 1_000_000) for e in expiries], dtype=np.int64)
    out = np.zeros(len(t_in), dtype=int)
    for k, t in enumerate(t_in):
        off = (int(t) - e_ms) / float(D1)
        od = np.round(off).astype(int)
        e0_days = (int(t) - int(e_ms[0])) // D1
        best = None; best_abs = 10 ** 9
        for i in range(len(e_ms)):
            a = abs(od[i])
            if a < best_abs or (a == best_abs and abs(off[i]) < abs(e0_days)):
                best, best_abs = int(od[i]), a
        out[k] = best if best is not None else 99
    return out

# ---------------------------------------------------------------------------
# Trade book: flat arrays + fast basket curve (identical math to oslib.overlay)
# ---------------------------------------------------------------------------
class Book:
    def __init__(self, eng, D, expiries):
        rows = []
        for nm, trs in eng.items():
            for t in oslib.standardize(trs, src=nm):
                rows.append((nm, t["entry_time"], t["exit_time"], t["R"], t["risk"]))
        f = pd.DataFrame(rows, columns=["nm", "t_in", "t_out", "R", "risk"]).sort_values(
            ["t_out", "nm", "t_in"], kind="mergesort").reset_index(drop=True)
        self.nm = f["nm"].to_numpy()
        self.t_in = f["t_in"].to_numpy(np.int64)
        self.t_out = f["t_out"].to_numpy(np.int64)
        self.R = f["R"].to_numpy(float)
        self.risk = f["risk"].to_numpy(float)
        self.base = np.array([LIVE_RISK.get(n, RISK) for n in self.nm], float)
        self.valid = np.isfinite(self.R) & np.isfinite(self.risk) & (self.risk > 0)
        self.Rz = np.where(self.valid, self.R, 0.0)
        self.riskz = np.where(self.valid, self.risk, 0.0)
        self.gid = np.unique(self.t_out, return_inverse=True)[1]
        self.ng = int(self.gid.max()) + 1 if len(self.gid) else 0
        self.isT = np.isin(self.nm, list(TREND_ENG))
        self.isB = np.isin(self.nm, list(BREAK_ENG))
        # A2 day index: batch10 rule (last 1D bar with start <= t_in - 1, may be the entry day itself)
        day_t = D["time"].to_numpy(np.int64)
        self.j_b10 = np.searchsorted(day_t, self.t_in - 1, side="right") - 1
        # strictly completed 1D bar (no same-day lookahead), info variant A2c
        self.j_done = np.searchsorted(day_t + D1, self.t_in, side="right") - 1
        self.exp_off = expiry_offsets(self.t_in, expiries)
        self.w_pct, self.Dv = a2_inputs(D)
        self._lab = {}
        print(f"  book: {len(self.nm)} trades, {self.ng} exit stamps, {len(day_t)} daily bars", flush=True)

    def labels(self, coil_pct, exp_pct, completed=False):
        key = (coil_pct, exp_pct, completed)
        if key not in self._lab:
            st = a2_states(self.w_pct, self.Dv, coil_pct, exp_pct)
            di = day_in_state(st)
            j = self.j_done if completed else self.j_b10
            ok = (j >= 0) & (j < len(st))
            jj = np.clip(j, 0, len(st) - 1)
            self._lab[key] = (np.where(ok, st[jj], ST_NORMAL), np.where(ok, di[jj], 0))
        return self._lab[key]

    def a2_mult(self, p, completed=False):
        st, di = self.labels(p["coil_pct"], p["exp_pct"], completed)
        m = np.ones(len(st))
        m[(st == ST_COIL) & self.isB] = p["coil_mult"]
        e = st == ST_EXP
        early = e & (di >= 1) & (di <= p["exp_days"])
        m[early & self.isT] = 1.25
        m[early & ~self.isT & self.isB] = 0.75
        m[e & (di >= p["exp_days"] + 1) & self.isB] = 0.5
        return m

    def a3_mult(self, lo, hi, engs=A3_ENG):
        m = np.ones(len(self.nm))
        m[np.isin(self.nm, list(engs)) & (self.exp_off >= lo) & (self.exp_off <= hi)] = 0.0
        return m

    def curve(self, mult, lo_ms, hi_ms):
        sel = (self.t_out >= lo_ms) & (self.t_out < hi_ms) & (mult > 0)
        if not sel.any():
            return dict(ret=0.0, maxDD=0.0, MAR=np.nan, n=0)
        pnl = self.Rz[sel] * np.minimum(self.base[sel] * mult[sel], self.riskz[sel])
        g = np.bincount(self.gid[sel], weights=pnl, minlength=self.ng)
        present = np.bincount(self.gid[sel], minlength=self.ng) > 0
        eq = np.cumprod(1.0 + g[present])
        peak = np.maximum.accumulate(np.r_[1.0, eq])[1:]
        mdd = min(0.0, float((eq / peak - 1.0).min()))
        ret = 100.0 * (eq[-1] - 1.0); dd = 100.0 * mdd
        return dict(ret=ret, maxDD=dd, MAR=(ret / abs(dd) if dd < 0 else np.nan), n=int(sel.sum()))

def score(s):
    if s["maxDD"] < 0:
        return s["MAR"]
    return 1e12 + s["ret"] if s["ret"] > 0 else s["ret"]

def beats(a, b):
    sa, sb = score(a), score(b)
    if sa >= 1e12 and sb >= 1e12:
        return a["ret"] > b["ret"]
    return sa > sb

def ptxt(p):
    return f"coil<={p['coil_pct']} exp>={p['exp_pct']} x{p['coil_mult']} d{p['exp_days']}"

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

# ---------------------------------------------------------------------------
# One asset
# ---------------------------------------------------------------------------
def run_asset(label, df, fund, years, end_ms):
    t_a = time.time()
    print(f"\n=== {label.upper()}: building oslib live engines (X7 on: funding passed) ...", flush=True)
    eng = engines(df, fund=fund)
    print(f"  {label}: " + ", ".join(f"{k} {len(v)}" for k, v in eng.items()) + f"  ({time.time()-t_a:.0f}s)", flush=True)
    D = resample_ohlcv(df, D1)
    t_last = int(df["time"].iloc[-1])
    exps = expiry_days("2012-01-01", pd.Timestamp(t_last + 60 * D1, unit="ms", tz="UTC").strftime("%Y-%m-%d"))
    B = Book(eng, D, exps)
    one = np.ones(len(B.nm))
    s0 = ms(START)

    # sanity: fast curve == oslib.overlay baseline
    ov = overlay(eng, lambda nm, t: 1.0, start=START)
    fb = B.curve(one, s0, end_ms)
    print(f"  check vs oslib.overlay baseline: ret {f1(ov['baseline']['ret'])} / {f1(fb['ret'])}  "
          f"maxDD {f1(ov['baseline']['maxDD'],2)} / {f1(fb['maxDD'],2)}  MAR {f1(ov['baseline']['MAR'],1)} / {f1(fb['MAR'],1)}", flush=True)

    rows = []
    # full-period references (batch10 fixed params, in-sample)
    (rlo, rhi), reng = A3_REF[label]
    m2 = B.a2_mult(A2_DEFAULT); m3 = B.a3_mult(rlo, rhi, reng)
    m2c = B.a2_mult(A2_DEFAULT, completed=True)
    ref = [("baseline", one, "-"), ("A2 fixed", m2, ptxt(A2_DEFAULT)),
           ("A3 fixed", m3, f"skip {rlo}..{rhi} {'+'.join(reng)}"), ("A2+A3 fixed", m2 * m3, "both"),
           ("A2c fixed (completed day)", m2c, ptxt(A2_DEFAULT))]
    print(f"\n  {label.upper()} full 2017+ reference (batch10 params, in-sample):", flush=True)
    for nm, m, ptx in ref:
        s = B.curve(m, s0, end_ms)
        print(f"    {nm:28s} ret {f1(s['ret']):>9s}%  maxDD {f1(s['maxDD'],2):>7s}%  MAR {f1(s['MAR'],1):>7s}  n {s['n']}  [{ptx}]", flush=True)
        rows.append(dict(asset=label, section="reference_2017+", year="2017+", overlay=nm, params=ptx,
                         ret=s["ret"], maxDD=s["maxDD"], MAR=s["MAR"], n=s["n"]))

    a2_combos = [dict(zip(A2_GRID, v)) for v in itertools.product(*A2_GRID.values())]
    a2_cache = {tuple(p.values()): B.a2_mult(p) for p in a2_combos}
    a2c_cache = {tuple(p.values()): B.a2_mult(p, completed=True) for p in a2_combos}
    a3_cache = {w: B.a3_mult(*w) for w in A3_WINDOWS}

    OV = ["A2", "A3", "A2+A3", "A2c"]
    stitched = {k: np.zeros(len(B.nm)) for k in OV}
    stitched["baseline"] = np.zeros(len(B.nm))
    wins = {k: 0 for k in OV}
    nyears = 0
    print(f"\n  {label.upper()} walk-forward (train 2017..Y-1 -> test Y):", flush=True)
    for Y in years:
        lo_ms, hi_ms = ms(f"{Y}-01-01"), min(ms(f"{Y+1}-01-01"), end_ms)
        if lo_ms >= end_ms:
            continue
        nyears += 1
        tr_lo, tr_hi = s0, lo_ms
        best2 = max(a2_combos, key=lambda p: score(B.curve(a2_cache[tuple(p.values())], tr_lo, tr_hi)))
        best2c = max(a2_combos, key=lambda p: score(B.curve(a2c_cache[tuple(p.values())], tr_lo, tr_hi)))
        best3 = max(A3_WINDOWS, key=lambda w: score(B.curve(a3_cache[w], tr_lo, tr_hi)))
        mm = {"baseline": one, "A2": a2_cache[tuple(best2.values())], "A3": a3_cache[best3],
              "A2+A3": a2_cache[tuple(best2.values())] * a3_cache[best3],
              "A2c": a2c_cache[tuple(best2c.values())]}
        pp = {"baseline": "-", "A2": ptxt(best2), "A3": f"skip {best3[0]}..{best3[1]}",
              "A2+A3": ptxt(best2) + f" | skip {best3[0]}..{best3[1]}", "A2c": ptxt(best2c)}
        ymask = (B.t_out >= lo_ms) & (B.t_out < hi_ms)
        sb = B.curve(one, lo_ms, hi_ms)
        trn_b = B.curve(one, tr_lo, tr_hi)
        line = [f"    {Y}: base ret {f1(sb['ret']):>7s} dd {f1(sb['maxDD'],2):>6s} MAR {f1(sb['MAR'],2):>6s}"]
        for k in ["baseline"] + OV:
            stitched[k][ymask] = mm[k][ymask]
            s = B.curve(mm[k], lo_ms, hi_ms)
            st = B.curve(mm[k], tr_lo, tr_hi)
            bt = (k != "baseline") and beats(s, sb)
            if k != "baseline":
                wins[k] += int(bt)
                line.append(f"{k} {f1(s['ret'])}/{f1(s['maxDD'],1)}/{f1(s['MAR'],2)}{'+' if bt else '-'}")
            rows.append(dict(asset=label, section="test_year", year=Y, overlay=k, params=pp[k],
                             ret=s["ret"], maxDD=s["maxDD"], MAR=s["MAR"], n=s["n"],
                             train_MAR=st["MAR"], train_base_MAR=trn_b["MAR"],
                             base_ret=sb["ret"], base_MAR=sb["MAR"], beat_base=bt if k != "baseline" else np.nan))
        print("  |  ".join(line), flush=True)
        print(f"          params A2 [{pp['A2']}]  A3 [{pp['A3']}]  A2c [{pp['A2c']}]", flush=True)

    t_wf = ms(f"{years[0]}-01-01")
    sb = B.curve(one, t_wf, end_ms)
    summ = {}
    print(f"\n  {label.upper()} stitched test years {years[0]}..{years[-1]} (n years {nyears}):", flush=True)
    print(f"    {'baseline':8s} ret {f1(sb['ret']):>8s}%  maxDD {f1(sb['maxDD'],2):>7s}%  MAR {f1(sb['MAR'],2):>7s}", flush=True)
    rows.append(dict(asset=label, section="stitched", year=f"{years[0]}-{years[-1]}", overlay="baseline", params="-",
                     ret=sb["ret"], maxDD=sb["maxDD"], MAR=sb["MAR"], n=sb["n"]))
    for k in OV:
        s = B.curve(stitched[k], t_wf, end_ms)
        summ[k] = dict(stitched=s, base=sb, wins=wins[k], nyears=nyears, beat_stitched=beats(s, sb))
        print(f"    {k:8s} ret {f1(s['ret']):>8s}%  maxDD {f1(s['maxDD'],2):>7s}%  MAR {f1(s['MAR'],2):>7s}  "
              f"beat base {wins[k]}/{nyears} years", flush=True)
        rows.append(dict(asset=label, section="stitched", year=f"{years[0]}-{years[-1]}", overlay=k, params="per-fold",
                         ret=s["ret"], maxDD=s["maxDD"], MAR=s["MAR"], n=s["n"], base_ret=sb["ret"],
                         base_MAR=sb["MAR"], beat_base=summ[k]["beat_stitched"], years_beat=wins[k]))
    print(f"  {label}: done ({time.time()-t_a:.0f}s)", flush=True)
    return rows, summ

def main(smoke=False):
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        h1 = synthetic_1h(n=20000, seed=9, start="2017-01-02")
        fund = pd.DataFrame({"time": h1["time"].to_numpy()[::8],
                             "funding": np.random.default_rng(0).normal(0, 1e-5, (len(h1) + 7) // 8)})
        data = {"btc": (h1, fund)}
        years = [2018, 2019]
    else:
        data = {}
        for a in ("btc", "eth"):
            data[a] = (load(a, "1h"), funding(a, "binance"))
        years = list(range(2020, 2027))
    all_rows, S = [], {}
    for a, (df, fund) in data.items():
        end_ms = int(df["time"].iloc[-1]) + D1
        r, s = run_asset(a, df, fund, years, end_ms)
        all_rows += r; S[a] = s
    need = 5 if not smoke else 1
    print(f"\n=== VERDICT (KEEP if stitched BTC MAR > baseline AND beats baseline in >= {need} of {len(years)} years) ===", flush=True)
    for k in ["A2", "A3", "A2+A3", "A2c"]:
        b = S["btc"][k]
        keep = bool(b["beat_stitched"]) and b["wins"] >= need
        eth = S.get("eth", {}).get(k)
        etxt = (f" | ETH stitched MAR {f1(eth['stitched']['MAR'],2)} vs {f1(eth['base']['MAR'],2)}, "
                f"{eth['wins']}/{eth['nyears']} yrs") if eth else ""
        print(f"  {'KEEP' if keep else 'DROP'}  {k:6s} BTC stitched MAR {f1(b['stitched']['MAR'],2)} vs base "
              f"{f1(b['base']['MAR'],2)}, beat {b['wins']}/{b['nyears']} yrs{etxt}", flush=True)
        all_rows.append(dict(asset="btc", section="verdict", year="-", overlay=k, params="-",
                             ret=b["stitched"]["ret"], maxDD=b["stitched"]["maxDD"], MAR=b["stitched"]["MAR"],
                             base_MAR=b["base"]["MAR"], years_beat=b["wins"], verdict="KEEP" if keep else "DROP"))
    print("  (A2c = A2 labelled from the last fully completed daily bar; info only, shows same-day lookahead effect.)", flush=True)
    out_dir = Path("/content") if Path("/content").exists() else Path(".")
    out = out_dir / ("wf_overlay_smoke.csv" if smoke else "wf_overlay.csv")
    pd.DataFrame(all_rows).to_csv(out, index=False)
    print(f"\nSaved {out} ({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)
