# =============================================================================
# BATCH20 - EQUITY-CURVE GOVERNORS ON A SIZING DIAL   (self-contained, Colab)
# =============================================================================
# RUN (Colab): upload this file, then in a cell:  %run batch20_governors.py
#         (or paste the whole file into one cell and run). Runtime ~2-4 min.
#
# PROBLEM
#   The x1.5 macro boost (risk-on) raises returns but deepens ETH maxDD
#   (-34% -> -39.5%). Test a brake that cuts the boost when the account is
#   already losing.
#
# DATA (no Binance API calls anywhere in this script)
#   https://osom-boba.pages.dev/colab/btc_1h_full.csv.gz
#   https://osom-boba.pages.dev/colab/eth_1h_full.csv.gz
#   via pd.read_csv(url, storage_options={"User-Agent": "Mozilla/5.0"}),
#   time column = epoch ms. DXY comes from yfinance (DX-Y.NYB, fallback DX=F).
#
# STAND-IN STRATEGY (identical for every governor, only sizing differs)
#   - daily EMA20/50 trend, long when EMA20 > EMA50, short when below
#     (stop-and-reverse at the daily close = last hourly close of the day)
#   - stop = 2 x ATR(14, Wilder, daily) from entry, checked on hourly bars
#     (gap-through exits at the hourly open); trend-flip exit at daily close
#   - base risk 1.0% of equity; costs 0.12% per side on notional
#   - size dial (random-free, evaluated at entry): x1.5 when BTC daily close
#     > SMA50(BTC) AND DXY < SMA50(DXY), else x1.0. The dial is BTC/DXY based
#     for BOTH runs (market-level macro gate, like the live bot); set
#     DIAL_ON_TRADED = True to make the SMA50 leg use the traded asset.
#   - one position at a time; multiplier fixed for the trade once entered
#   - notional capped at MAX_LEV x equity (counted as lev-capped)
#
# GOVERNORS COMPARED (state evaluated at trade entry)
#   a) no governor (boost always allowed when dial says so)
#   b) boost capped to x1.0 while equity is >10% below its running peak
#   c) same with 15%
#   d) ALL risk halved while equity < its own 30-trade moving average
#      (moving average of trade-end equity values; needs >=10 closed trades)
#   e) boost only allowed after 2 winning trades in a row
#   ref) boost permanently OFF (x1.0 always) - reference only, not a candidate
#
# OUTPUT
#   [1] method, [2] per config x {BTC, ETH}: CAGR, maxDD, MAR, PF, WR,
#       trades/yr, boost share, brake counters, per-year returns,
#   [3] summary table + verdict: best governor = lowest ETH maxDD while
#       keeping >= 90% of the no-governor BTC MAR.
#
# No string in this file contains a raw line break; multi-line text uses \n.
# =============================================================================

import os
import sys
import time
import gzip
import io
import warnings

T0 = time.time()
warnings.filterwarnings("ignore")


def _ensure(pkg, pip_name=None):
    try:
        __import__(pkg)
        return
    except Exception:
        pn = pip_name or pkg
        print("[boot] pip install " + pn + " ...")
        os.system("pip install -q " + pn + " >/dev/null 2>&1")


_ensure("numpy")
_ensure("pandas")
_ensure("requests")
_ensure("yfinance")

import numpy as np
import pandas as pd
import requests as rq

try:
    import yfinance as yf
except Exception:
    yf = None

# ------------------------------- CONFIG --------------------------------------
BTC_URL = "https://osom-boba.pages.dev/colab/btc_1h_full.csv.gz"
ETH_URL = "https://osom-boba.pages.dev/colab/eth_1h_full.csv.gz"
UA = {"User-Agent": "Mozilla/5.0"}
SIM_START = "2018-01-01"
WARM_DAYS = 60
BASE_RISK = 0.01
COST_SIDE = 0.0012
ATR_N = 14
STOP_ATR = 2.0
BOOST_X = 1.5
MAX_LEV = 3.0
DD_CAP_B = 0.10
DD_CAP_C = 0.15
GOV_D_WINDOW = 30
GOV_D_MIN_TRADES = 10
DIAL_ON_TRADED = False   # False = dial always uses BTC>SMA50 & DXY<SMA50 (live-bot style)

# ----------------------------- FORMATTING ------------------------------------


def f1(x):
    return f"{x:.1f}"


def f2(x):
    return f"{x:.2f}"


def pctS(x):
    return ("+" if x >= 0 else "") + f"{100.0 * x:.1f}%"


def ddS(x):
    return f"{100.0 * x:.1f}%"


def dS(x):
    return ("+" if x >= 0 else "") + f"{x:.2f}"


# ------------------------------- DATA ----------------------------------------
def load_csv_gz(url):
    try:
        df = pd.read_csv(url, storage_options=UA)
        print("[data] " + url.split("/")[-1] + " loaded via read_csv")
        return df
    except Exception as e:
        print("[data] read_csv failed (" + str(e)[:120] + ") - requests fallback")
    r = rq.get(url, headers=UA, timeout=120)
    r.raise_for_status()
    try:
        raw = gzip.decompress(r.content)
    except Exception:
        raw = r.content
    df = pd.read_csv(io.BytesIO(raw))
    print("[data] " + url.split("/")[-1] + " loaded via requests fallback")
    return df


def load_1h(url):
    df = load_csv_gz(url)
    df.columns = [str(c).strip().lower() for c in df.columns]
    tcol = None
    for c in df.columns:
        if "time" in c or "date" in c:
            tcol = c
            break
    if tcol is None:
        for c in df.columns:
            v = pd.to_numeric(df[c], errors="coerce")
            if v.notna().mean() > 0.8 and float(v.dropna().abs().median()) > 1e11:
                tcol = c
                break
    if tcol is None:
        raise RuntimeError("no epoch-ms time column found in " + url)
    ts = pd.to_numeric(df[tcol], errors="coerce")
    if float(ts.dropna().abs().median()) < 1e11:
        ts = ts * 1000.0
    out = pd.DataFrame(index=pd.to_datetime(ts, unit="ms"))
    for c in ["open", "high", "low", "close"]:
        if c not in df.columns:
            raise RuntimeError("missing price column '" + c + "' in " + url)
        out[c] = pd.to_numeric(df[c], errors="coerce").values
    out = out.sort_index()
    out = out[~out.index.duplicated(keep="last")]
    return out.dropna(subset=["close"])


def yf_close(sym, start):
    if yf is None:
        print("[data] WARNING: yfinance unavailable - " + sym + " skipped")
        return None
    last_err = None
    for _ in range(3):
        try:
            df = yf.download(sym, start=start, progress=False, auto_adjust=False, threads=False)
            if df is None or len(df) == 0:
                raise ValueError("empty")
            if isinstance(df.columns, pd.MultiIndex):
                df.columns = df.columns.get_level_values(0)
            s = df["Close"].copy()
            s.index = pd.to_datetime(s.index)
            try:
                s.index = s.index.tz_localize(None)
            except Exception:
                pass
            s = s.dropna()
            s = s[~s.index.duplicated(keep="last")].sort_index()
            if len(s) > 200:
                print("[data] " + sym + ": " + str(len(s)) + " rows from " + str(s.index[0].date()))
                return s
            raise ValueError("too short")
        except Exception as e:
            last_err = e
            time.sleep(2)
    print("[data] WARNING: " + sym + " failed (" + str(last_err) + ")")
    return None


def to_daily(h1):
    agg = h1.resample("1D").agg({"open": "first", "high": "max", "low": "min", "close": "last"})
    return agg.dropna(subset=["close"])


def wilder_atr(df, n):
    h = df["high"]
    l = df["low"]
    c = df["close"]
    pc = c.shift(1)
    tr = pd.concat([(h - l), (h - pc).abs(), (l - pc).abs()], axis=1).max(axis=1)
    return tr.ewm(alpha=1.0 / n, adjust=False).mean()


def build_asset(name, url, dxy, dial_override=None):
    h1_full = load_1h(url)
    D_full = to_daily(h1_full)
    dc = D_full["close"]
    D_full["ema20"] = dc.ewm(span=20, adjust=False).mean()
    D_full["ema50"] = dc.ewm(span=50, adjust=False).mean()
    D_full["atr"] = wilder_atr(D_full, ATR_N)
    D_full["sma50"] = dc.rolling(50).mean()
    if dxy is not None:
        dxy_d = dxy.reindex(D_full.index).ffill()
        dxy_cond = (dxy_d < dxy_d.rolling(50).mean()).fillna(False)
    else:
        dxy_cond = pd.Series(False, index=D_full.index)
    dial_local = ((dc > D_full["sma50"]) & dxy_cond).fillna(False)
    use = dial_override if (dial_override is not None and not DIAL_ON_TRADED) else dial_local
    dial_used = use.reindex(D_full.index).ffill().fillna(False) if use is not None else pd.Series(False, index=D_full.index)

    h1 = h1_full[h1_full.index >= pd.Timestamp(SIM_START)]
    if len(h1) < 2000:
        raise RuntimeError(name + ": too few hourly rows after " + SIM_START + " (" + str(len(h1)) + ")")
    DS = to_daily(h1)
    ema20 = D_full["ema20"].reindex(DS.index).values.astype(float)
    ema50 = D_full["ema50"].reindex(DS.index).values.astype(float)
    atr = D_full["atr"].reindex(DS.index).values.astype(float)
    dial = dial_used.reindex(DS.index).fillna(False).values.astype(bool)
    dir_s = np.where(ema20 > ema50, 1, -1).astype(int)
    day_pos = pd.Series(np.arange(len(DS)), index=DS.index)
    hday = h1.index.normalize()
    didx = day_pos.reindex(hday).fillna(-1).values.astype(int)
    dates = hday.values
    is_last = np.empty(len(h1), dtype=bool)
    is_last[:-1] = dates[1:] != dates[:-1]
    is_last[-1] = True
    A = dict(
        name=name,
        dial_used_full=dial_used,
        o=h1["open"].values.astype(float),
        h=h1["high"].values.astype(float),
        l=h1["low"].values.astype(float),
        c=h1["close"].values.astype(float),
        idx=h1.index,
        didx=didx,
        is_last=is_last,
        dir=dir_s,
        dial=dial,
        atr=atr,
        n_hours=len(h1),
        n_days=len(DS),
        first=str(h1.index[0]),
        last=str(h1.index[-1]),
    )
    print("[data] " + name + ": " + str(len(h1_full)) + " hourly rows (" + str(h1_full.index[0]) + " -> " + str(h1_full.index[-1]) + "), sim " + str(len(h1)) + " hours / " + str(len(DS)) + " days from " + SIM_START)
    return A


# ------------------------------ ENGINE ---------------------------------------
def run_engine(A, gov):
    o = A["o"]
    h = A["h"]
    l = A["l"]
    c = A["c"]
    didx = A["didx"]
    is_last = A["is_last"]
    dir_s = A["dir"]
    dial = A["dial"]
    atr = A["atr"]
    n = len(c)
    eq = 1.0
    eq_peak = 1.0
    eqc = np.ones(n, dtype=float)
    pos = None
    closed_rs = []
    trade_eq = []
    cnt = dict(boost=0, capped=0, blocked=0, halved=0, levcap=0, n=0)
    for i in range(n):
        prev_c = c[i - 1] if i > 0 else None
        if pos is not None and i > pos["i0"]:
            xp = None
            if pos["dir"] > 0:
                if o[i] <= pos["sp"]:
                    xp = o[i]
                elif l[i] <= pos["sp"]:
                    xp = pos["sp"]
            else:
                if o[i] >= pos["sp"]:
                    xp = o[i]
                elif h[i] >= pos["sp"]:
                    xp = pos["sp"]
            flip = False
            if xp is None and is_last[i]:
                t = didx[i]
                if t >= WARM_DAYS and dir_s[t] != pos["dir"]:
                    flip = True
            if xp is not None or flip:
                xprice = xp if xp is not None else c[i]
                eq += pos["u"] * (xprice - prev_c) * pos["dir"] - pos["u"] * xprice * COST_SIDE
                r = (pos["u"] * (xprice - pos["ep"]) * pos["dir"] - pos["u"] * xprice * COST_SIDE - pos["ec"]) / pos["ru"]
                closed_rs.append(r)
                trade_eq.append(eq)
                pos = None
            else:
                eq += pos["u"] * (c[i] - prev_c) * pos["dir"]
        if is_last[i] and pos is None and i < n - 1:
            t = didx[i]
            if t >= WARM_DAYS:
                desired = int(dir_s[t])
                price = c[i]
                sd = STOP_ATR * float(atr[t])
                if desired != 0 and np.isfinite(sd) and sd > 0:
                    mult = BOOST_X if bool(dial[t]) else 1.0
                    mult_eff = mult
                    halved = False
                    if gov == "ref":
                        mult_eff = 1.0
                    elif gov == "b":
                        if mult > 1.0 and eq / eq_peak - 1.0 <= -DD_CAP_B:
                            mult_eff = 1.0
                            cnt["capped"] += 1
                    elif gov == "c":
                        if mult > 1.0 and eq / eq_peak - 1.0 <= -DD_CAP_C:
                            mult_eff = 1.0
                            cnt["capped"] += 1
                    elif gov == "d":
                        if len(trade_eq) >= GOV_D_MIN_TRADES:
                            ma = float(np.mean(trade_eq[-GOV_D_WINDOW:]))
                            if eq < ma:
                                halved = True
                                cnt["halved"] += 1
                    elif gov == "e":
                        if mult > 1.0 and not (len(closed_rs) >= 2 and closed_rs[-1] > 0 and closed_rs[-2] > 0):
                            mult_eff = 1.0
                            cnt["blocked"] += 1
                    risk = BASE_RISK * mult_eff * (0.5 if halved else 1.0)
                    lev = risk / (sd / price)
                    if lev > MAX_LEV:
                        lev = MAX_LEV
                        cnt["levcap"] += 1
                    notional = eq * lev
                    units = notional / price
                    ru = notional * (sd / price)
                    sp = price - sd if desired > 0 else price + sd
                    pos = dict(dir=desired, ep=price, u=units, sp=sp, ru=ru, i0=i, ec=notional * COST_SIDE)
                    eq -= pos["ec"]
                    if mult_eff > 1.0:
                        cnt["boost"] += 1
                    cnt["n"] += 1
        eqc[i] = eq
        if eq > eq_peak:
            eq_peak = eq
    if pos is not None:
        xprice = c[n - 1]
        eq += -pos["u"] * xprice * COST_SIDE
        r = (pos["u"] * (xprice - pos["ep"]) * pos["dir"] - pos["u"] * xprice * COST_SIDE - pos["ec"]) / pos["ru"]
        closed_rs.append(r)
        trade_eq.append(eq)
        pos = None
        eqc[n - 1] = eq
    return finish(A, eqc, closed_rs, cnt)


def finish(A, eqc, closed_rs, cnt):
    idx = A["idx"]
    n = len(eqc)
    years = max(1e-9, (idx[-1] - idx[0]).total_seconds() / (365.25 * 86400.0))
    end = float(eqc[-1])
    cagr = end ** (1.0 / years) - 1.0 if end > 0 else -1.0
    peak = np.maximum.accumulate(eqc)
    dd = float((eqc / peak - 1.0).min())
    mar = (cagr / abs(dd)) if dd < 0 else 999.0
    rs = np.array(closed_rs, dtype=float)
    if len(rs) > 0:
        w = rs[rs > 0]
        lo = rs[rs < 0]
        pf = (w.sum() / abs(lo.sum())) if (lo.size > 0 and lo.sum() != 0) else (999.0 if w.size > 0 else 0.0)
        wr = 100.0 * float((rs > 0).sum()) / len(rs)
    else:
        pf = 0.0
        wr = 0.0
    yend = {}
    yv = idx.year.values
    for i in range(n):
        yend[int(yv[i])] = i
    pyr = []
    prev = 1.0
    for y in sorted(yend):
        e = float(eqc[yend[y]])
        pyr.append((y, e / prev - 1.0))
        prev = e
    return dict(eqc=eqc, end=end, cagr=cagr, dd=dd, mar=min(mar, 999.0), pf=min(pf, 999.0),
                wr=wr, n=len(rs), years=years, pyr=pyr, cnt=cnt)


# ------------------------------ REPORT ---------------------------------------
def asset_line(tag, res):
    bs = 100.0 * res["cnt"]["boost"] / max(1, res["cnt"]["n"])
    return ("  " + tag + " : CAGR " + pctS(res["cagr"]) + "  maxDD " + ddS(res["dd"]) + "  MAR " + f2(res["mar"]) + "  PF " + f2(res["pf"]) + "  WR " + f1(res["wr"]) + "%  trades " + str(res["n"]) + " (" + f1(res["n"] / res["years"]) + "/yr)  end " + f2(res["end"]) + "x  boost " + f1(bs) + "%")


def pyr_line(res):
    parts = []
    for (y, r) in res["pyr"]:
        parts.append(str(y) + " " + pctS(r))
    s = "    per-year: " + "  ".join(parts)
    if res["pyr"] and res["pyr"][-1][0] == 2026:
        s += "  (2026 partial)"
    return s


def diag_line(res_b, res_e):
    def seg(res):
        c = res["cnt"]
        return "capped " + str(c["capped"]) + " halved " + str(c["halved"]) + " blocked " + str(c["blocked"]) + " levcap " + str(c["levcap"])
    return "    brake: BTC[" + seg(res_b) + "]  ETH[" + seg(res_e) + "]"


def main():
    SEP = "=" * 100
    SEP2 = "-" * 100
    print(SEP)
    print("[0] DATA")
    print("dial: x" + f"{BOOST_X:.1f}" + " when " + ("traded asset" if DIAL_ON_TRADED else "BTC") + " > SMA50 and DXY < SMA50 (yfinance), else x1.0 - same dial for both assets unless DIAL_ON_TRADED=True")
    print(SEP2)

    print("[0] loading DXY via yfinance ...")
    dxy = yf_close("DX-Y.NYB", "2014-01-01")
    if dxy is None:
        dxy = yf_close("DX=F", "2014-01-01")
    if dxy is None:
        print("[data] WARNING: DXY unavailable -> dial permanently OFF (mult always x1.0); governor comparison degenerate - fix yfinance and rerun")

    A_BTC = build_asset("BTC", BTC_URL, dxy, dial_override=None)
    print("[0] building ETH (same BTC+DXY macro dial as the live bot) ...")
    A_ETH = build_asset("ETH", ETH_URL, dxy, dial_override=A_BTC["dial_used_full"])
    print(SEP)
    print("[1] METHOD - stand-in strategy: daily EMA20/50 stop-and-reverse, 2xATR(14) stop (hourly checks), 1% base risk, 0.12%/side costs; governors evaluated at entry only")
    print("    a) no governor | b) boost capped x1.0 while DD>10% | c) same 15% | d) all risk halved while equity < 30-trade MA | e) boost needs 2 wins in a row | ref) boost off")
    print(SEP)
    print("[2] RESULTS  (BTC = traded on BTC daily EMAs, ETH = same rules on ETH; dial identical per [0])")
    print(SEP2)
    GOVS = [
        ("a) NO GOVERNOR (boost always allowed when dial on)", "a"),
        ("b) boost capped to x1.0 while equity >10% below peak", "b"),
        ("c) boost capped to x1.0 while equity >15% below peak", "c"),
        ("d) all risk halved while equity < 30-trade MA of equity", "d"),
        ("e) boost only allowed after 2 winning trades in a row", "e"),
        ("ref) BOOST PERMANENTLY OFF (x1.0 always) - reference only", "ref"),
    ]
    RES = {}
    for label, gid in GOVS:
        print(label)
        for tag, A in (("BTC", A_BTC), ("ETH", A_ETH)):
            res = run_engine(A, gid)
            RES[(gid, tag)] = res
            print(asset_line(tag, res))
            print(pyr_line(res))
        print(diag_line(RES[(gid, "BTC")], RES[(gid, "ETH")]))
        print(SEP2)

    print("[3] SUMMARY + VERDICT")
    print("gov".ljust(6) + "BTC MAR".rjust(9) + " BTC maxDD".rjust(11) + " ETH MAR".rjust(9) + " ETH maxDD".rjust(11) + "   qual(>=90% x a)")
    print(SEP2)
    mar_a = RES[("a", "BTC")]["mar"]
    thr = 0.90 * mar_a
    for gid in ["a", "b", "c", "d", "e", "ref"]:
        rb = RES[(gid, "BTC")]
        re_ = RES[(gid, "ETH")]
        if gid == "a":
            q = "(reference)"
        elif gid == "ref":
            q = "-"
        else:
            q = "YES" if rb["mar"] >= thr else "no"
        print(gid.ljust(6) + f2(rb["mar"]).rjust(9) + " " + ddS(rb["dd"]).rjust(10) + " " + f2(re_["mar"]).rjust(9) + " " + ddS(re_["dd"]).rjust(10) + "   " + q)
    print(SEP2)
    print("threshold: 90% of no-governor BTC MAR = " + f2(thr) + "  (no-gov BTC MAR " + f2(mar_a) + ")")
    qual = [g for g in ["b", "c", "d", "e"] if RES[(g, "BTC")]["mar"] >= thr]
    if qual:
        best = min(qual, key=lambda g: RES[(g, "ETH")]["dd"])
        print("qualified (BTC MAR >= threshold): " + ", ".join(qual))
        print("lowest ETH maxDD among qualified: governor '" + best + "'  ETH maxDD " + ddS(RES[(best, "ETH")]["dd"]) + "  ETH MAR " + f2(RES[(best, "ETH")]["mar"]) + "  BTC MAR " + f2(RES[(best, "BTC")]["mar"]))
        print("VERDICT: deploy governor " + best)
    else:
        best = min(["b", "c", "d", "e"], key=lambda g: RES[(g, "ETH")]["dd"])
        print("no governor keeps >=90% of the no-governor BTC MAR")
        print("lowest ETH maxDD anyway: governor '" + best + "' (fails the MAR constraint)")
        print("VERDICT: no governor satisfies both constraints - compare with the ref row (boost fully off) and consider a hybrid (e.g. b+d)")
    print("reference: BOOST OFF has ETH maxDD " + ddS(RES[("ref", "ETH")]["dd"]) + " and BTC MAR " + f2(RES[("ref", "BTC")]["mar"]) + " (what dropping the boost entirely costs)")
    print(SEP2)
    print("done in " + f1(time.time() - T0) + "s. Paste the full output back for interpretation + deployment sizing.")
    print("notes: governors act at entry only (size fixed for the trade); governor d needs >= " + str(GOV_D_MIN_TRADES) + " closed trades before it can halve; MAX_LEV " + f"{MAX_LEV:.1f}" + "x caps notional per position")


main()
