# ===== f18ema.py - F18 official vs pure EMA30 inside the live basket at maxOpen 6 (cut30) =====
# Colab:  !wget -q -O f18ema.py "https://osom-boba.pages.dev/colab/f18ema.py"
#         %run f18ema.py
# Box (synthetic smoke only):  python3 f18ema.py --smoke
#
# Same conventions as nearmiss.py / f18check.py: hosted oslib, COST 0.12%/side, Binance 1h perp data + Binance
# funding, PnL = R * min(risk_weight, trade stop distance), equity compounds from 1.0 on exit-time PnL, cut30 on every
# unit, live mix + Q3, maxOpen 6 (live since 2026-11-23).
# Setups (BTC + ETH), all vs the maxOpen-6 live basket with no addition:
#   (c) no addition (baseline)
#   (a) official F18 = batch16 #18 (close vs EMA30 + funding gate, 2.5 ATR stop, state exits) at 1%
#   (b) pure EMA30 = batch16 #18 without the funding gate (same 2.5 ATR stop, same exits) at 1% and 0.5%
# Reports ret/CAGR/maxDD/MAR, MAR halves (2017-20 / 2021-26), years beating the mo6 baseline, daily corr to the
# basket, placebo (100 runs) for the best variant (and any other variant that clears the gates), ADD_SMALL verdicts.
# ADD_SMALL: MAR >= mo6 baseline both halves, maxDD <= 3 pts worse, >= 4/7 years BTC, >= 3/7 ETH, placebo >= 80.
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-f18ema/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 d / name
        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()))
    return Path.cwd() / name

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

_need("nearmiss.py", IN_COLAB_DIR)
import nearmiss as nm

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

NAN = np.nan
START = "2017-01-01"
FUND_EXIST = "2019-09-10"
SEED = 20261123
YRS_PF = list(range(2017, 2027))
ROWS = []
FIND = []

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

def iso(t):
    return pd.Timestamp(int(t), unit="ms", tz="UTC").strftime("%Y-%m-%d %H:%M UTC")

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

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

def rec(**kw):
    ROWS.append(kw)

def run_path_mo(P, use_cut=True, max_open=4):
    if P["n"] == 0:
        return nm.empty_stats()
    if use_cut:
        M, W = nm.cut30_mult(P)
        wi = np.clip(np.searchsorted(W, P["week"]), 0, len(W) - 1)
        m = M[wi, P["unit"]]
    else:
        m = np.ones(P["n"])
    take = nm.apply_maxopen(P["entry"], P["exit"], m > 0, max_open=max_open)
    pnl = np.where(take, P["R"] * np.minimum(P["base"][P["unit"]], P["risk"]), 0.0)
    pnl = np.where(np.isfinite(pnl), pnl, 0.0)
    st = nm.stats_from(P["exit"][take], pnl[take])
    st["taken_by_unit"] = np.bincount(P["unit"][take], minlength=len(P["names"]))
    st["pnl_by_unit"] = np.bincount(P["unit"][take], weights=pnl[take], minlength=len(P["names"]))
    return st

def placebo_pct_mo(base_units, adds, bars, real_mar, seed, n_runs, max_open):
    if not np.isfinite(real_mar):
        return NAN
    rng = np.random.default_rng(seed)
    sets = [nm.placebo_sets(_t, bars, rng, n_runs) for _nm, _w, _t in adds]
    mars = []
    for k in range(n_runs):
        units = list(base_units) + [(name, w, sets[j][k]) for j, (name, w, _t) in enumerate(adds)]
        mars.append(run_path_mo(nm.pack(units), max_open=max_open)["mar"])
    mars = np.array([m for m in mars if np.isfinite(m)])
    if not len(mars):
        return NAN
    return 100.0 * float(np.mean(mars < real_mar))

def eval_at(ctx, adds_b, adds_e, max_open, base_btc, base_eth):
    ub = ctx["btc"]["units"] + list(adds_b)
    stb = run_path_mo(nm.pack(ub), max_open=max_open)
    b = nm.enrich(stb, base_btc)
    n0 = len(ctx["btc"]["units"])
    tu = stb.get("taken_by_unit", np.zeros(0))
    nb = int(tu[n0:].sum()) if len(tu) > n0 else 0
    e = None
    if adds_e is not None:
        ue = ctx["eth"]["units"] + list(adds_e)
        e = nm.enrich(run_path_mo(nm.pack(ue), max_open=max_open), base_eth)
    return b, e, nb

def idea_trades(b16, fn, X, Y, asset):
    raw = b16.run_idea(fn, X, Y, False, None)["trades"]
    return nm.clean([t for t in raw if t.get("asset") == asset])

def pf_years(trs):
    out = {}
    for y in YRS_PF:
        t0, t1 = ms(f"{y}-01-01"), ms(f"{y+1}-01-01")
        R = [t["R"] for t in (trs or []) if t0 <= t["exit_time"] < t1]
        out[y] = (len(R), nm.pf_of(R) if R else NAN)
    return out

def bask_line(tag, mo, n_add, b, e, corr, tpy, plc, verd):
    return (f"  {tag:<22} {mo:>2} {n_add:>5} {fr(b['st']['ret']):>9} {fr(b['st']['cagr']):>7} "
            f"{fr(b['st']['dd']):>7} {f2(b['st']['mar']):>5} {f2(b['h1']['mar']):>5} "
            f"{f2(b['h2']['mar']):>5} {str(b['beats'])+'/7':>4} "
            f"{fr(e['st']['ret']) if e else '   n/a':>8} {fr(e['st']['dd']) if e else '   n/a':>7} "
            f"{f2(e['st']['mar']) if e else 'n/a':>6} {(str(e['beats'])+'/7') if e else 'n/a':>4} "
            f"{f2(corr):>5} {f2(tpy,0):>5} {f2(plc,0):>4}  {verd}")

BASK_HDR = (f"  {'setup':<22} {'mo':>2} {'n+':>5} {'ret%':>9} {'CAGR%':>7} {'maxDD%':>7} {'MAR':>5} "
            f"{'MAR1':>5} {'MAR2':>5} {'yrB':>4} {'ETHret%':>8} {'ETHdd%':>7} {'ETHMAR':>6} {'yrE':>4} "
            f"{'corr':>5} {'tr/yr':>5} {'plc':>4}  verdict")

def make_i18_ema(b16, start=None):
    def fn(A, O):
        D = A.d
        c = D["c"]
        e30 = b16.ema(c, 30)
        st = np.where(c > e30, 1, np.where(c < e30, -1, 0))
        kw = dict(B=D, sig=st, stop_atr=2.5, exitL=st != 1, exitS=st != -1)
        if start is not None:
            kw["start"] = start
        return [(A.name, kw)]
    return fn

def make_i18_from(b16, start):
    def fn(A, O):
        label, kw = b16.i18(A, O)[0]
        kw = dict(kw)
        kw["start"] = start
        return [(label, kw)]
    return fn

def main(smoke=False):
    n_plc = 8 if smoke else 100
    MO = 6
    D = {}
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        n = int(os.environ.get("F18_SMOKE_N", str(24 * 1600)))
        b1 = synthetic_1h(n=n, seed=9, start="2016-09-01")
        e1 = synthetic_1h(n=n, seed=21, start="2016-09-01", px0=300.0)
        rng = np.random.default_rng(0)
        t_fund0 = ms(FUND_EXIST)
        for a, df in (("btc", b1), ("eth", e1)):
            tt = df["time"].to_numpy()
            tt = tt[(tt >= t_fund0)]
            tt = tt[::8]
            D[a] = dict(df=df, fund=pd.DataFrame({"time": tt, "funding": 0.0001 + rng.normal(0, 0.0002, len(tt))}))
    else:
        for a in ("btc", "eth"):
            D[a] = dict(df=load(a, "1h"), fund=funding(a, "binance"))
    end_ms = int(D["btc"]["df"]["time"].iloc[-1])

    b16 = nm.import_plain("batch16.py", "batch16")
    BT = b16.Ctx("btc", D["btc"]["df"], D["btc"]["fund"])
    ET = b16.Ctx("eth", D["eth"]["df"], D["eth"]["fund"])
    D["_b16"] = (b16, BT, ET)

    # ---- solo trades
    print("\n=== 1) SOLO (1% risk, 0.12%/side, by exit) ===", flush=True)
    VAR = {}
    for key, fn, start in (("F18", b16.i18, b16.FUND_START), ("EMA30", make_i18_ema(b16, None), START)):
        VAR[key] = {"start": start}
        for asset, X, Y in (("btc", BT, ET), ("eth", ET, BT)):
            trs = idea_trades(b16, fn, X, Y, asset)
            s = nm.solo(trs, start, end_ms)
            VAR[key][asset] = dict(trs=trs, solo=s)
            print(f"  {key:<6} {asset:<4} n={s['n']:>4} tr/yr={f2(s['tpy'],0):>4} PF={f2(s['pf']):>5} "
                  f"(PF17-20 {f2(s['pf1'])}, PF21-26 {f2(s['pf2'])}) start {start}", flush=True)
            rec(section="1", setup=key, asset=asset, n=s["n"], tpy=s["tpy"], pf=s["pf"], pf1=s["pf1"], pf2=s["pf2"])

    # ---- live basket at maxOpen 6
    print(f"\n=== building live baskets (cut30, maxOpen {MO}) ===", flush=True)
    ctx = {}
    for a in ("btc", "eth"):
        print(f"  building {a.upper()} live basket ...", flush=True)
        eng = engines(D[a]["df"], fund=D[a]["fund"])
        units = [(name, nm.BASE_RISK.get(name, 0.01), nm.clean(trs)) for name, trs in eng.items()]
        try:
            units.append(("Q3", nm.BASE_RISK["Q3"], nm.q3_trades(D, a)))
        except Exception as ex:
            print(f"    Q3 {a} ERROR {type(ex).__name__}: {ex} (basket runs without Q3)", flush=True)
        st = run_path_mo(nm.pack(units), max_open=MO)
        ctx[a] = dict(units=units, base_st=st, en=nm.enrich(st, st), bars=(
            D[a]["df"]["time"].to_numpy("int64"), D[a]["df"]["open"].to_numpy(float),
            D[a]["df"]["high"].to_numpy(float), D[a]["df"]["low"].to_numpy(float),
            D[a]["df"]["close"].to_numpy(float)))
        print("    " + " ".join(f"{u[0]} {sum(1 for t in u[2] if t['entry_time'] >= nm.T_START)}" for u in units), flush=True)
        print(f"    live-only maxOpen {MO}: ret {fr(st['ret']).strip()}% CAGR {fr(st['cagr']).strip()}% "
              f"maxDD {fr(st['dd']).strip()}% MAR {f2(st['mar'])}", flush=True)
    bb, be = ctx["btc"]["en"], ctx["eth"]["en"]

    # ---- 2) basket + variants
    setups = [("(a) F18 official", "F18", 0.01), ("(b) EMA30 pure", "EMA30", 0.01), ("(b) EMA30 pure", "EMA30", 0.005)]
    RES = []
    for label, key, w in setups:
        tb, te = VAR[key]["btc"]["trs"], VAR[key]["eth"]["trs"]
        tag = f"{label} {100*w:.1f}%"
        try:
            b, e, nb = eval_at(ctx, [(key, w, tb)], [(key, w, te)], MO, ctx["btc"]["base_st"], ctx["eth"]["base_st"])
            corr = nm.dcorr_full(nm.daily_full(tb, w, is_trades=True), bb["st"]["daily"])
            fails = nm.gate_fails(b, e, bb, be)
            RES.append(dict(tag=tag, key=key, w=w, b=b, e=e, nb=nb, corr=corr, tpy=VAR[key]["btc"]["solo"]["tpy"],
                            fails=fails, plc=NAN, tb=tb))
        except Exception as ex:
            print(f"  {tag} ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=2)
    ok = [r for r in RES if np.isfinite(r["b"]["st"]["mar"])]
    best = max(ok, key=lambda r: r["b"]["st"]["mar"]) if ok else None
    for r in RES:
        if r is best or not r["fails"]:
            seed = SEED + sum(ord(ch) for ch in r["key"]) + int(1000 * r["w"])
            r["plc"] = placebo_pct_mo(ctx["btc"]["units"], [(r["key"], r["w"], r["tb"])], ctx["btc"]["bars"],
                                      r["b"]["st"]["mar"], seed, n_plc, MO)
            if not (np.isfinite(r["plc"]) and r["plc"] >= 80):
                r["fails"] = r["fails"] + ["placebo"]
            r["plc_run"] = True
        if r.get("plc_run"):
            r["verd"] = "ADD_SMALL" if not r["fails"] else "NO (" + ",".join(r["fails"]) + ")"
        else:
            r["verd"] = "NO (" + ",".join(r["fails"]) + ")"

    print(f"\n=== 2) BASKET + ADDITION at maxOpen {MO} (cut30; years/halves vs the maxOpen-{MO} live baseline) ===", flush=True)
    print("  n+ = addition trades actually taken after cut30 / maxOpen. MAR1=2017-20, MAR2=2021-26. "
          "corr = daily PnL corr of the solo addition to the BTC basket.", flush=True)
    print(BASK_HDR, flush=True)
    print(bask_line("(c) no addition", MO, 0, bb, be, NAN, NAN, NAN, f"baseline mo{MO}"), flush=True)
    rec(section="2", setup="(c) no addition", mo=MO, n_taken=0, ret=bb["st"]["ret"], cagr=bb["st"]["cagr"],
        dd=bb["st"]["dd"], mar=bb["st"]["mar"], mar_17_20=bb["h1"]["mar"], mar_21_26=bb["h2"]["mar"],
        yrs_btc=bb["beats"], eth_ret=be["st"]["ret"], eth_dd=be["st"]["dd"], eth_mar=be["st"]["mar"],
        yrs_eth=be["beats"], corr=NAN, tpy=NAN, placebo=NAN, verdict=f"baseline mo{MO}")
    for r in RES:
        b, e = r["b"], r["e"]
        print(bask_line(r["tag"], MO, r["nb"], b, e, r["corr"], r["tpy"], r["plc"], r["verd"]), flush=True)
        rec(section="2", setup=r["tag"], mo=MO, n_taken=r["nb"], ret=b["st"]["ret"], cagr=b["st"]["cagr"],
            dd=b["st"]["dd"], mar=b["st"]["mar"], mar_17_20=b["h1"]["mar"], mar_21_26=b["h2"]["mar"],
            yrs_btc=b["beats"], eth_ret=e["st"]["ret"], eth_dd=e["st"]["dd"], eth_mar=e["st"]["mar"],
            yrs_eth=e["beats"], corr=r["corr"], tpy=r["tpy"], placebo=r["plc"], verdict=r["verd"])

    print("\n=== YEARS (BTC basket return % by year; baseline vs each setup) ===", flush=True)
    yrs = nm.YEARS
    print("  " + f"{'setup':<24}" + " ".join(f"{y:>7}" for y in yrs), flush=True)
    for tag, en in [("(c) no addition", bb)] + [(r["tag"], r["b"]) for r in RES]:
        print("  " + f"{tag:<24}" + " ".join(f"{fr(en['yrs'].get(y, NAN)):>7}" for y in yrs), flush=True)

    print("\n=== VERDICTS ===", flush=True)
    for r in RES:
        b = r["b"]
        print(f"  {r['tag']:<24} {r['verd']:<30} MAR {f2(b['st']['mar'])} vs {f2(bb['st']['mar'])}, "
              f"CAGR {fr(b['st']['cagr']).strip()}% vs {fr(bb['st']['cagr']).strip()}%, "
              f"DD {fr(b['st']['dd']).strip()}% vs {fr(bb['st']['dd']).strip()}%, "
              f"yrs {b['beats']}/7 BTC {r['e']['beats']}/7 ETH, plc {f2(r['plc'],0)}", flush=True)
    if best is not None:
        print(f"  Best by BTC MAR: {best['tag']} (placebo {f2(best['plc'],0)}, {n_plc} runs)", flush=True)
    print("  ADD_SMALL: MAR >= mo6 baseline both halves, maxDD <= 3 pts worse, >= 4/7 years BTC, >= 3/7 ETH, placebo >= 80.", flush=True)

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