# ==========================================================================================
# batch18_macro_ideas.py  |  osib v1.1  |  10 NEW multi-day BTC-perp setup ideas
# Classes: macro triggers (gold / US10Y / DXY / oil), cross-asset lead-lag (NDX, ETH),
#          volatility structure (post-storm cool), price structure (SMA50 tap).
#
# HOW TO RUN IN COLAB:  upload this file, then run:  %run batch18_macro_ideas.py
#                       (or paste the whole content into one cell and run it)
#
# SIM SPEC
#   - BTC + ETH 1h data from osom-boba mirrors, aggregated to daily UTC bars
#   - signal computed on daily data up to close of day i -> entry at OPEN of day i+1
#     (no lookahead; macro series are daily closes, weekend/holiday gaps forward-filled)
#   - costs 0.12% per side (0.24% round trip), stops capped at 10% (daily close basis)
#   - one position per idea at a time; exits: early condition / max-hold / 10% stop
#   - equity for maxDD: 1% risk per trade scaled by 10% stop -> eq *= (1 + 0.1 * ret)
#   - placebo: 100 random-entry runs with same trade count and same hold lengths,
#     directions preserved; score = % of random runs the idea beats (higher = better)
#   - KEEP: PF > 1.3 in BOTH halves AND n >= 30 AND ETH PF > 1.0 AND placebo >= 90
#     NEAR: PF >= 1.1 AND n >= 60    (else NO, with failure reasons listed)
#   - every download wrapped in try/except; missing macro data -> idea reported n/a
# ==========================================================================================

import sys
import io
import time
import subprocess

import numpy as np
import pandas as pd
import requests

COST = 0.0012          # per side
STOP = 0.10            # stop cap, close basis, daily sim
RISK = 0.01            # 1% risk per trade for equity curve / maxDD scaling
SIZING = RISK / STOP   # equity multiplier per unit trade return
PF_CAP = 99.0
START = pd.Timestamp("2017-01-01")
SEED = 42
N_PLACEBO = 100
BASE = "https://osom-boba.pages.dev/colab/"

IDEA_ORDER = ["I01", "I02", "I03", "I04", "I05", "I06", "I07", "I08", "I09", "I10"]
IDEA_NAMES = {
    "I01": "gold-lead catch-up",
    "I02": "yield-down regime",
    "I03": "yield-spike washout",
    "I04": "dxy-breakdown long",
    "I05": "dxy-breakout short",
    "I06": "ndx-lead long",
    "I07": "eth-leader rotation",
    "I08": "vol-storm-cool long",
    "I09": "sma50-tap bull dip",
    "I10": "oil-shock rebound",
}


def print_defs():
    print("=== 0) IDEA DEFINITIONS (daily signals, entry next open, all stops 10%) ===")
    print("  I01 gold-lead catch-up L : gold30>+5% AND (gold30-btc30)>+10pp -> long 15d, exit spread<0")
    print("  I02 yield-down regime L  : TNX<SMA20(TNX) -> long until TNX>SMA20, max 30d")
    print("  I03 yield-spike washout L: TNX 5d chg>+0.25pp AND btc5d<-8% -> long 12d, exit new 10d high")
    print("  I04 dxy-breakdown L      : DXY<min(prior 50 closes) -> long 20d, exit DXY>SMA20(DXY)")
    print("  I05 dxy-breakout S       : DXY>max(prior 50 closes) -> short 15d, exit DXY<SMA20(DXY)")
    print("  I06 ndx-lead L           : QQQ10d>+4% AND btc10d<0 -> long 12d, exit btc10d>+8%")
    print("  I07 eth-leader rotation L: leader new 20d high AND base |10d ret|<3% -> long 10d")
    print("  I08 vol-storm-cool L     : RV5 was >90th pct(252d) within 10d, RV5<RV20 now, close>SMA20 -> long 12d")
    print("  I09 sma50-tap bull dip L : close>SMA200 AND low<=SMA50 AND close>=SMA50 -> long 12d, exit close<SMA50")
    print("  I10 oil-shock rebound L  : oil10d<-15% AND btc10d<-8% -> long 12d, exit new 15d high")


def ensure_yfinance():
    try:
        import yfinance  # noqa: F401
        return True
    except Exception:
        try:
            subprocess.run([sys.executable, "-m", "pip", "install", "-q", "yfinance"], check=False)
            import yfinance  # noqa: F401
            return True
        except Exception:
            return False


def fetch_csv_gz(url, tag, retries=3):
    last = None
    for a in range(retries):
        try:
            r = requests.get(url, timeout=120, headers={"User-Agent": "Mozilla/5.0"})
            r.raise_for_status()
            df = pd.read_csv(io.BytesIO(r.content), compression="gzip")
            print("  " + tag + ": " + url + " | " + f"{len(df):,}" + " rows")
            return df
        except Exception as e:
            last = e
            time.sleep(2 + 2 * a)
    print("  FAIL " + tag + ": " + str(last))
    return None


def load_1h(url, tag):
    raw = fetch_csv_gz(url, tag)
    if raw is None:
        return None
    cols = [str(c) for c in raw.columns]
    low = [c.strip().lower() for c in cols]
    tcol = cols[0]
    for c, lc in zip(cols, low):
        if "time" in lc or "date" in lc:
            tcol = c
            break
    want = ["open", "high", "low", "close", "volume"]
    data = {"time": raw[tcol]}
    for w in want:
        hit = None
        for c, lc in zip(cols, low):
            if lc == w or lc.startswith(w):
                hit = c
                break
        data[w] = raw[hit] if hit is not None else pd.Series(np.nan, index=raw.index)
    df = pd.DataFrame(data)
    _t = pd.to_numeric(df["time"], errors="coerce")
    if _t.notna().mean() > 0.9:
        _unit = "ms" if _t.dropna().median() > 1e11 else "s"
        df["time"] = pd.to_datetime(_t, unit=_unit, utc=True, errors="coerce")
    else:
        df["time"] = pd.to_datetime(df["time"], utc=True, errors="coerce")
    for w in want:
        df[w] = pd.to_numeric(df[w], errors="coerce")
    df = df.dropna(subset=["time"]).sort_values("time").drop_duplicates(subset="time")
    df = df.set_index("time").dropna(subset=["close"])
    return df


def fix_bad_bars(df, tag):
    # repair isolated bad opens/lows/highs vs prior close (e.g. eth 2017-08-22 04:00 O 144.21)
    prev = df["close"].shift(1)
    bad_o = (df["open"] < 0.75 * prev) & (df["close"] > 0.75 * prev) & (df["high"] > 0.9 * prev)
    shown = 0
    for i in df.index[bad_o]:
        if shown < 5:
            print("  DATA FIX " + tag + " " + str(i) + ": O " + str(round(float(df.at[i, "open"]), 2)) + " -> " + str(round(float(prev.at[i]), 2)) + " (prior close)")
        shown += 1
    if shown > 5:
        print("  DATA FIX " + tag + ": ... (" + str(shown) + " bad opens total)")
    df.loc[bad_o, "open"] = prev[bad_o].values
    inner_low = df[["open", "close", "high"]].min(axis=1)
    bad_l = (df["low"] < 0.6 * prev) & (inner_low > 0.9 * prev)
    df.loc[bad_l, "low"] = inner_low[bad_l].values
    inner_high = df[["open", "close"]].max(axis=1)
    bad_h = (df["high"] > 1.5 * prev) & (df["high"] > 1.5 * inner_high) & (df["close"] < 1.2 * prev)
    df.loc[bad_h, "high"] = inner_high[bad_h].values
    n_fix = int(bad_o.sum() + bad_l.sum() + bad_h.sum())
    if n_fix:
        print("  DATA FIX " + tag + ": " + str(n_fix) + " bar(s) repaired")
    return df


def to_daily(df1h):
    x = df1h.copy()
    x.index = x.index.tz_localize(None)
    d = pd.DataFrame({
        "open": x["open"].resample("1D").first(),
        "high": x["high"].resample("1D").max(),
        "low": x["low"].resample("1D").min(),
        "close": x["close"].resample("1D").last(),
        "volume": x["volume"].resample("1D").sum(),
    })
    return d.dropna(subset=["close"])


MACRO_DEFS = [("gold", "GC=F"), ("tnx", "^TNX"), ("dxy", "DX-Y.NYB"), ("qqq", "QQQ"), ("oil", "CL=F")]


def fetch_macro():
    out = {}
    ensure_yfinance()
    try:
        import yfinance as yf
    except Exception:
        print("  WARN: yfinance unavailable -> macro ideas will be n/a")
        for key, tic in MACRO_DEFS:
            out[key] = None
        return out
    for key, tic in MACRO_DEFS:
        got = None
        for attempt in range(2):
            try:
                df = yf.download(tic, start="2015-06-01", progress=False, auto_adjust=True)
                if df is not None and len(df) > 0:
                    if isinstance(df.columns, pd.MultiIndex):
                        df.columns = df.columns.get_level_values(0)
                    s = df["Close"].dropna().astype(float)
                    s.index = pd.to_datetime(s.index).tz_localize(None).normalize()
                    s = s[~s.index.duplicated(keep="last")].sort_index()
                    got = s
                    break
            except Exception:
                time.sleep(2)
        if got is None:
            print("  macro " + key + " (" + tic + "): FAILED -> dependent ideas n/a")
        else:
            if key == "tnx":
                got = got / 10.0  # yahoo quotes ^TNX as yield*10; normalize to %
                print("  macro tnx (^TNX): " + str(got.index[0].date()) + " .. " + str(got.index[-1].date()) + " | " + str(len(got)) + " rows (yields in %)")
            else:
                print("  macro " + key + " (" + tic + "): " + str(got.index[0].date()) + " .. " + str(got.index[-1].date()) + " | " + str(len(got)) + " rows")
        out[key] = got
    return out


def align_macro(mac, idx):
    out = {}
    for k, s in mac.items():
        out[k] = None if s is None else s.reindex(idx).ffill()
    return out


def bmask(s):
    return s.fillna(False).values.astype(bool)


def pct_rank(s, w=252):
    return s.rolling(w).apply(lambda a: float((a[-1] >= a).mean()), raw=True)


def build_ideas(d, lead_close, mac):
    # returns list of dicts: id, name, dir, mh (max hold days), cond (bool np array), early (np array or None)
    ideas = []
    cl = d["close"]
    b5 = cl.pct_change(5)
    b10 = cl.pct_change(10)
    b30 = cl.pct_change(30)
    sma20 = cl.rolling(20).mean()
    sma50 = cl.rolling(50).mean()
    sma200 = cl.rolling(200).mean()
    prev_high10 = cl.rolling(10).max().shift(1)
    prev_high15 = cl.rolling(15).max().shift(1)
    lr = np.log(cl / cl.shift(1))
    rv5 = lr.rolling(5).std() * np.sqrt(365.0)
    rv20 = lr.rolling(20).std() * np.sqrt(365.0)

    if mac.get("gold") is not None:
        g30 = mac["gold"].pct_change(30)
        spread = g30 - b30
        ideas.append(dict(id="I01", name=IDEA_NAMES["I01"], dir=1, mh=15,
                          cond=bmask((g30 > 0.05) & (spread > 0.10)), early=bmask(spread < 0.0)))
    if mac.get("tnx") is not None:
        y = mac["tnx"]
        ysma = y.rolling(20).mean()
        ideas.append(dict(id="I02", name=IDEA_NAMES["I02"], dir=1, mh=30,
                          cond=bmask(y < ysma), early=bmask(y > ysma)))
        dy5 = y - y.shift(5)
        ideas.append(dict(id="I03", name=IDEA_NAMES["I03"], dir=1, mh=12,
                          cond=bmask((dy5 > 0.25) & (b5 < -0.08)), early=bmask(cl > prev_high10)))
    if mac.get("dxy") is not None:
        dx = mac["dxy"]
        dxsma = dx.rolling(20).mean()
        ideas.append(dict(id="I04", name=IDEA_NAMES["I04"], dir=1, mh=20,
                          cond=bmask(dx < dx.rolling(50).min().shift(1)), early=bmask(dx > dxsma)))
        ideas.append(dict(id="I05", name=IDEA_NAMES["I05"], dir=-1, mh=15,
                          cond=bmask(dx > dx.rolling(50).max().shift(1)), early=bmask(dx < dxsma)))
    if mac.get("qqq") is not None:
        q10 = mac["qqq"].pct_change(10)
        ideas.append(dict(id="I06", name=IDEA_NAMES["I06"], dir=1, mh=12,
                          cond=bmask((q10 > 0.04) & (b10 < 0.0)), early=bmask(b10 > 0.08)))
    if lead_close is not None:
        lnewhigh = lead_close > lead_close.rolling(20).max().shift(1)
        bflat = (cl / cl.shift(10) - 1.0).abs() < 0.03
        ideas.append(dict(id="I07", name=IDEA_NAMES["I07"], dir=1, mh=10,
                          cond=bmask(lnewhigh & bflat), early=None))
    pctr = pct_rank(rv5)
    storm_recent = (pctr > 0.90).rolling(10).max().shift(1) > 0.5
    ideas.append(dict(id="I08", name=IDEA_NAMES["I08"], dir=1, mh=12,
                      cond=bmask(storm_recent & (rv5 < rv20) & (cl > sma20)), early=bmask(cl < sma20)))
    ideas.append(dict(id="I09", name=IDEA_NAMES["I09"], dir=1, mh=12,
                      cond=bmask((cl > sma200) & (d["low"] <= sma50) & (cl >= sma50)), early=bmask(cl < sma50)))
    if mac.get("oil") is not None:
        o10 = mac["oil"].pct_change(10)
        ideas.append(dict(id="I10", name=IDEA_NAMES["I10"], dir=1, mh=12,
                          cond=bmask((o10 < -0.15) & (b10 < -0.08)), early=bmask(cl > prev_high15)))
    return ideas


def simulate(d, cond, direction, maxhold, early, start_i):
    # entries: cond True at close of day i -> enter at open of day i+1 (next bar open)
    # exits:   stop (10% close basis) / early condition at close j -> exit at open j+1 / max-hold timeout
    n = len(d)
    op = d["open"].values
    cl = d["close"].values
    trades = []
    in_pos = False
    sig_i = -1
    entry_px = 0.0
    for i in range(start_i, n):
        if in_pos:
            exit_i = None
            if direction * (cl[i] / entry_px - 1.0) <= -STOP:
                exit_i = i
            elif early is not None and bool(early[i]):
                exit_i = i
            elif i - sig_i >= maxhold:
                exit_i = i
            if exit_i is not None:
                eb = sig_i + 1
                if exit_i + 1 <= n - 1:
                    xpx = op[exit_i + 1]
                    xb = exit_i + 1
                else:
                    xpx = cl[n - 1]
                    xb = n - 1
                ret = direction * (xpx / op[eb] - 1.0) - 2 * COST
                trades.append({"eb": eb, "xb": xb, "dir": direction, "ret": ret})
                in_pos = False
        if (not in_pos) and bool(cond[i]) and i + 1 < n:
            in_pos = True
            sig_i = i
            entry_px = op[i + 1]
    return trades


def pf_of(rets):
    if len(rets) == 0:
        return None
    p = sum(r for r in rets if r > 0)
    l = -sum(r for r in rets if r < 0)
    if l <= 1e-12:
        return PF_CAP if p > 0 else None
    return p / l


def maxdd_of(rets):
    eq = 1.0
    peak = 1.0
    dd = 0.0
    for r in rets:
        eq *= (1.0 + r * SIZING)
        if eq > peak:
            peak = eq
        d = eq / peak - 1.0
        if d < dd:
            dd = d
    return dd * 100.0


def half_pfs(trades, idx):
    r1 = [t["ret"] for t in trades if idx[t["eb"]] <= pd.Timestamp("2020-12-31")]
    r2 = [t["ret"] for t in trades if idx[t["eb"]] >= pd.Timestamp("2021-01-01")]
    return (pf_of(r1) if r1 else None), (pf_of(r2) if r2 else None)


def yearly_pf(trades, idx):
    out = {}
    for t in trades:
        out.setdefault(idx[t["eb"]].year, []).append(t["ret"])
    return {y: pf_of(v) for y, v in sorted(out.items())}


def year_str(ypf):
    parts = []
    for y, p in ypf.items():
        parts.append(str(y % 100) + ":" + ("n/a" if p is None else f"{p:.2f}"))
    return " ".join(parts)


def placebo_score(d, trades, start_i, rng):
    n = len(trades)
    if n == 0:
        return 0.0
    nb = len(d)
    op = d["open"].values
    pool = np.arange(max(start_i, 30), nb - 2)
    if len(pool) < 2:
        return 0.0
    replace_flag = len(pool) < n
    holds = np.array([max(1, t["xb"] - t["eb"]) for t in trades])
    dirs = np.array([t["dir"] for t in trades])
    base = pf_of([t["ret"] for t in trades])
    if base is None:
        return 0.0
    cnt = 0
    for _ in range(N_PLACEBO):
        perm = rng.permutation(n)
        ent = rng.choice(pool, size=n, replace=replace_flag)
        rets = []
        for k in range(n):
            e = int(ent[k])
            x = min(e + int(holds[perm[k]]), nb - 1)
            rets.append(dirs[perm[k]] * (op[x] / op[e] - 1.0) - 2 * COST)
        pr = pf_of(rets)
        if pr is not None and pr <= base:
            cnt += 1
    return 100.0 * cnt / N_PLACEBO


def stats_for(d, tr, start_i):
    idx = d.index
    n = len(tr)
    yrs = max(0.25, (idx[-1] - idx[start_i]).days / 365.25)
    rets = [t["ret"] for t in tr]
    pf1, pf2 = half_pfs(tr, idx)
    return dict(n=n, tryr=n / yrs, pf=pf_of(rets), pf1=pf1, pf2=pf2,
                mdd=maxdd_of(rets), ypf=yearly_pf(tr, idx))


def fmt0(x):
    return "n/a" if x is None else f"{x:.0f}"


def fmt1(x):
    return "n/a" if x is None else f"{x:.1f}"


def fmt2(x):
    return "n/a" if x is None else f"{x:.2f}"


def verdict_for(r):
    if r.get("note"):
        return "NO (data)"
    pf, pf1, pf2, n = r["pf"], r["pf1"], r["pf2"], r["n"]
    ethpf = r.get("ethpf")
    ethn = r.get("ethn") or 0
    eth_eff = ethpf if (ethpf is not None and ethn >= 10) else None
    plac = r.get("plac")
    why = []
    if pf is None or pf1 is None or pf2 is None or pf1 <= 1.3 or pf2 <= 1.3:
        why.append("halves")
    if n < 30:
        why.append("n")
    if eth_eff is None or eth_eff <= 1.0:
        why.append("eth")
    if plac is None or plac < 90:
        why.append("plac")
    if not why:
        return "KEEP"
    if pf is not None and pf >= 1.1 and n >= 60:
        return "NEAR"
    return "NO (" + ",".join(why) + ")"


def run_all(btc_d, eth_d, mac):
    assets = [("BTC", btc_d)]
    if eth_d is not None:
        assets.append(("ETH", eth_d))
    store = {}
    t0 = time.time()
    for asset, d in assets:
        m = align_macro(mac, d.index)
        if asset == "BTC":
            lead_close = eth_d["close"].reindex(d.index).ffill() if eth_d is not None else None
        else:
            lead_close = btc_d["close"].reindex(d.index).ffill()
        ideas = build_ideas(d, lead_close, m)
        start_i = int(np.searchsorted(d.index, START))
        print("=== pass " + asset + " | " + str(len(d)) + " daily bars | sim from " + str(d.index[start_i].date()) + " ===")
        for idea in ideas:
            tr = simulate(d, idea["cond"], idea["dir"], idea["mh"], idea["early"], start_i)
            st = stats_for(d, tr, start_i)
            if asset == "BTC":
                st["plac"] = placebo_score(d, tr, start_i, np.random.default_rng(SEED))
                store[idea["id"]] = dict(id=idea["id"], name=idea["name"], dir=idea["dir"], **st)
                print("  " + idea["id"] + " " + idea["name"] + ": n=" + str(st["n"]) + " PF=" + fmt2(st["pf"]) + " plac=" + fmt0(st["plac"]) + " (" + f"{time.time() - t0:.0f}" + "s)")
            else:
                if idea["id"] in store:
                    store[idea["id"]]["ethpf"] = st["pf"]
                    store[idea["id"]]["ethn"] = st["n"]
        if asset == "ETH" and eth_d is not None:
            for iid in IDEA_ORDER:
                if iid in store and "ethpf" not in store[iid]:
                    store[iid]["ethpf"] = None
                    store[iid]["ethn"] = 0
    return store


def main():
    t0 = time.time()
    print("osib v1.1 | batch18: 10 macro/cross-asset/vol/structure ideas | cost 0.12%/side | daily sim, next-open entries, 2017+")
    print_defs()
    print("=== downloads ===")
    btc1h = load_1h(BASE + "btc_1h_full.csv.gz", "btc 1h")
    if btc1h is None:
        raise RuntimeError("btc 1h download failed - aborting")
    btc1h = fix_bad_bars(btc1h, "btc")
    btc_d = to_daily(btc1h)
    print("  btc daily: " + str(btc_d.index[0].date()) + " .. " + str(btc_d.index[-1].date()) + " | " + str(len(btc_d)) + " days")
    eth_d = None
    try:
        eth1h = load_1h(BASE + "eth_1h_full.csv.gz", "eth 1h")
        if eth1h is not None:
            eth1h = fix_bad_bars(eth1h, "eth")
            eth_d = to_daily(eth1h)
            print("  eth daily: " + str(eth_d.index[0].date()) + " .. " + str(eth_d.index[-1].date()) + " | " + str(len(eth_d)) + " days")
    except Exception as e:
        print("  eth load failed (" + str(e) + ") -> ETH PF columns n/a")
    print("=== macro downloads (yfinance) ===")
    mac = fetch_macro()
    store = run_all(btc_d, eth_d, mac)

    rows = []
    for iid in IDEA_ORDER:
        r = store.get(iid)
        if r is None:
            r = {"id": iid, "name": IDEA_NAMES[iid], "dir": 1, "n": 0, "tryr": 0.0, "pf": None,
                 "pf1": None, "pf2": None, "mdd": 0.0, "ypf": {}, "plac": None,
                 "ethpf": None, "ethn": 0, "note": "data/macro missing"}
        r.setdefault("ethpf", None)
        r.setdefault("ethn", 0)
        r.setdefault("plac", None)
        r.setdefault("note", "")
        r["verdict"] = verdict_for(r)
        rows.append(r)

    print("")
    print("=== 2) IDEAS ON BTC (headline) + ETH (robustness) | daily | 0.12%/side | next-open entries ===")
    for r in rows:
        dch = "+" if r["dir"] == 1 else "-"
        note = "  [" + r["note"] + "]" if r.get("note") else ""
        print("  " + r["id"] + " " + r["name"].ljust(21) + dch + "  n=" + str(r["n"]).rjust(4) + "  " + fmt1(r["tryr"]).rjust(5) + "/yr  PF=" + fmt2(r["pf"]).rjust(6) + "  [17-20 " + fmt2(r["pf1"]).rjust(6) + " | 21-26 " + fmt2(r["pf2"]).rjust(6) + "]  ETH PF=" + fmt2(r["ethpf"]) + " (n=" + str(r["ethn"]) + ")  mDD=" + fmt1(r["mdd"]) + "%  plac=" + fmt0(r["plac"]) + "  yr " + year_str(r["ypf"]) + note)

    print("")
    print("=== SUMMARY (sorted by PF) ===")
    print("  idea name                    n  tr/yr     PF    PF1    PF2  ETHPF  ETHn    mDD%  plac  verdict")
    srt = sorted(rows, key=lambda r: (r["pf"] is None, -(r["pf"] or 0)))
    for r in srt:
        print("  " + r["id"] + " " + r["name"].ljust(21) + str(r["n"]).rjust(5) + fmt1(r["tryr"]).rjust(7) + fmt2(r["pf"]).rjust(7) + fmt2(r["pf1"]).rjust(7) + fmt2(r["pf2"]).rjust(7) + fmt2(r["ethpf"]).rjust(7) + str(r["ethn"]).rjust(6) + fmt1(r["mdd"]).rjust(8) + fmt0(r["plac"]).rjust(6) + "  " + r["verdict"])

    print("")
    print("=== VERDICTS ===")
    for r in rows:
        print("  " + r["id"] + " " + r["name"] + ": " + r["verdict"])
    print("")
    keep = [r["id"] for r in rows if r["verdict"] == "KEEP"]
    near = [r["id"] for r in rows if r["verdict"] == "NEAR"]
    print("=== FINDINGS ===")
    print("  KEEP: " + (", ".join(keep) if keep else "none") + " | NEAR: " + (", ".join(near) if near else "none"))
    print("  - PLACEBO = % of 100 random-entry runs (same n, same holds, directions kept) that the idea beats")
    print("  - next step: paste this full output back into the chat for STEP 3 ranking + exact rules for the best 3")

    out = pd.DataFrame([{
        "id": r["id"], "name": r["name"], "dir": "long" if r["dir"] == 1 else "short",
        "n": r["n"], "tr_yr": round(r["tryr"], 2), "pf": r["pf"], "pf1": r["pf1"], "pf2": r["pf2"],
        "eth_pf": r["ethpf"], "eth_n": r["ethn"], "mdd_pct": round(r["mdd"], 2),
        "placebo": r["plac"], "verdict": r["verdict"], "year_pf": year_str(r["ypf"]), "note": r["note"],
    } for r in rows])
    out.to_csv("batch18_results.csv", index=False)
    print("")
    print("Saved /content/batch18_results.csv (" + str(len(out)) + " rows). Total " + f"{time.time() - t0:.0f}" + "s")


if __name__ == "__main__":
    main()
