# BTC / ETH multi-day idea lab, BATCH 4 (Colab, self-contained)
# Not executed by the author. Run it yourself: upload to Colab and run, or paste into one cell.
# Expect a few minutes of runtime (sweeps x placebo runs).
#
# ENGINE (same as batch 3)
# - Signal from the CLOSED daily bar i, entry at the OPEN of day i+1. No lookahead.
# - Entry fires on the first day a condition turns true (edge-triggered).
# - mode 'fixed': exit at the open H days after entry.
# - mode 'state': hold while the condition stays true, exit at the open after the first daily close
#   where it is false, or after H days (max hold).
# - 0.12% per side. Stop: 'cap' = 10% hard stop. 'atr' = 2.5 x ATR(14) stop (ATR known before entry),
#   floored at 2% and capped at 10%. Stops are checked on daily high/low and filled at the stop.
# - Macro data lagged one extra day.
# - Placebo: 100 runs of random entries with the SAME count, hold lengths, direction and stop style.
# - 0 trades => PF 0 (no crash).
#
# PART A: 10 ideas (6 shorts with ATR stop, 4 shorter-lookback breakout longs), full stats.
# PART B: plateau sweeps for the two rate shorts (BTC SMA 20/50/100 x yield SMA 10/20/50 x max hold 10/20/30)
#         plus a stop comparison (10% cap vs 2.5 ATR).
# PART C: breakout sweep: BTC/asset ratio high with lookback 20/30/45 and hold 10/15 for 5 assets.
# PART D: time in market and overlap matrix between the 10 ideas and 4 reference winners.
#
# IDEAS (part A)
#  1 YLD_UP_BTC_WEAK_ATR   short state max20  US10Y > SMA20 and BTC < SMA50
#  2 BEAR_FLAT_ATR         short state max20  2Y > SMA20, (10Y-2Y) < SMA50, BTC < SMA50
#  3 SPY_WEAK_YLD_UP       short state max20  BTC/SPY < SMA50 and US10Y > SMA20
#  4 GOLD_WEAK_YLD_UP      short state max20  BTC/gold < SMA50 and US10Y > SMA20
#  5 DXY_UP_BTC_WEAK       short state max20  DXY > SMA20 and BTC < SMA50
#  6 CREDIT_FALL_BTC_WEAK  short state max20  HYG/IEF < SMA20 and BTC < SMA50
#  7 BTC_SPY_BRK30         long  fixed 10     BTC/SPY ratio at a new 30d high
#  8 BTC_SPY_BRK45         long  fixed 15     BTC/SPY ratio at a new 45d high
#  9 BTC_SILVER_BRK20      long  fixed 10     BTC/silver ratio at a new 20d high
# 10 BTC_QQQ_BRK30         long  fixed 10     BTC/QQQ ratio at a new 30d high

import sys
import subprocess
import warnings
import numpy as np
import pandas as pd

warnings.filterwarnings('ignore')

try:
    import yfinance as yf
except Exception:
    try:
        subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', 'yfinance'], check=False)
        import yfinance as yf
    except Exception as e:
        yf = None
        print('yfinance unavailable:', e)

# ----------------------------------------------------------------- config
BASE_URL = 'https://osom-boba.pages.dev/colab/'
UA = {'User-Agent': 'Mozilla/5.0'}
START = pd.Timestamp('2017-01-01')
COST = 0.0012            # per side
STOP = 0.10              # hard stop cap
ATR_MULT = 2.5
ATR_LEN = 14
ATR_FLOOR = 0.02         # minimum ATR stop distance (2%)
RISK = 0.02
SIZE = RISK / STOP       # notional fraction used for the drawdown curve
PLACEBO_RUNS = 100
MACRO_LAG_DAYS = 1
SEED = 42
MACRO_MAX_START = pd.Timestamp('2018-01-01')

MACRO_TICKERS = {
    'gold': ['GC=F'],
    'silver': ['SI=F'],
    'copper': ['HG=F'],
    'qqq': ['QQQ'],
    'spy': ['SPY'],
    'us10y': ['^TNX'],
    'us2y': ['2YY=F', '^FVX'],
    'hyg': ['HYG'],
    'ief': ['IEF'],
    'dxy': ['DX-Y.NYB', 'UUP'],
}


# ----------------------------------------------------------------- helpers
def f2(x):
    if x is None:
        return 'nan'
    try:
        if np.isnan(x):
            return 'nan'
        if np.isinf(x):
            return 'inf'
    except Exception:
        return str(x)
    return '%.2f' % x


def r2(x, k=2):
    try:
        if np.isfinite(x):
            return round(float(x), k)
    except Exception:
        pass
    return x


def gt(x, t):
    return x is not None and not np.isnan(x) and x > t


def ge(x, t):
    return x is not None and not np.isnan(x) and x >= t


def pf(rets):
    r = np.asarray(rets, dtype=float)
    if r.size == 0:
        return 0.0
    g = r[r > 0].sum()
    l = -r[r < 0].sum()
    if l == 0:
        return np.inf if g > 0 else 0.0
    return g / l


def max_dd(rets):
    if len(rets) == 0:
        return 0.0
    eq = np.cumprod(1.0 + SIZE * np.asarray(rets, dtype=float))
    peak = np.maximum.accumulate(eq)
    return float(((eq / peak) - 1.0).min() * 100.0)


def load_daily_from_1h(fname):
    url = BASE_URL + fname
    try:
        raw = pd.read_csv(url, compression='gzip', storage_options=UA)
    except Exception as e:
        print('DOWNLOAD FAILED', fname, '->', e)
        return None
    try:
        raw.columns = [str(c).strip().lower() for c in raw.columns]
        tcol = None
        for c in raw.columns:
            if 'time' in c or 'date' in c:
                tcol = c
                break
        if tcol is None:
            tcol = raw.columns[0]
        t = raw[tcol]
        if pd.api.types.is_numeric_dtype(t):
            unit = 'ms' if float(t.iloc[0]) > 1e11 else 's'
            ts = pd.to_datetime(t, unit=unit, utc=True)
        else:
            ts = pd.to_datetime(t, utc=True, errors='coerce')
        raw.index = ts.dt.tz_convert(None)
        raw = raw.loc[raw.index.notna()]
        for c in ['open', 'high', 'low', 'close']:
            if c not in raw.columns:
                raise ValueError('missing column ' + c)
            raw[c] = pd.to_numeric(raw[c], errors='coerce')
        if 'volume' not in raw.columns:
            raw['volume'] = 0.0
        raw['volume'] = pd.to_numeric(raw['volume'], errors='coerce')
        raw = raw[['open', 'high', 'low', 'close', 'volume']].sort_index()
        raw = raw[~raw.index.duplicated(keep='first')]
        agg = {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'}
        d = raw.resample('1D').agg(agg).dropna(subset=['open', 'high', 'low', 'close'])
        print('Loaded', fname, 'daily bars:', len(d), 'from', d.index[0].date(), 'to', d.index[-1].date())
        return d
    except Exception as e:
        print('PARSE FAILED', fname, '->', e)
        return None


def load_yf(ticker):
    if yf is None:
        return None
    try:
        df = yf.download(ticker, start='2016-01-01', progress=False, auto_adjust=True)
        if df is None or len(df) == 0:
            raise ValueError('empty download')
        if isinstance(df.columns, pd.MultiIndex):
            df.columns = df.columns.get_level_values(0)
        s = df['Close'].astype(float).dropna()
        s.index = pd.to_datetime(s.index).tz_localize(None)
        s = s[~s.index.duplicated(keep='first')].sort_index()
        return s
    except Exception as e:
        print('yfinance FAILED', ticker, '->', e)
        return None


def load_first(key, tickers):
    for tk in tickers:
        s = load_yf(tk)
        if s is None or len(s) < 500:
            print('  ' + key + ': ' + tk + ' unusable, trying next')
            continue
        if s.index[0] > MACRO_MAX_START:
            print('  ' + key + ': ' + tk + ' starts ' + str(s.index[0].date()) + ' (too late), trying next')
            continue
        print('Loaded ' + key + ' from ' + tk + ' rows=' + str(len(s)) + ' to ' + str(s.index[-1].date()))
        return s
    print('  ' + key + ': no usable source')
    return None


def align(s, idx, lag):
    out = s.reindex(idx, method='ffill')
    if lag:
        out = out.shift(lag)
    return out


def make_ctx(d, macro, btc_d, eth_d):
    idx = d.index
    ctx = {}
    for k, s in macro.items():
        if s is not None:
            ctx[k] = align(s, idx, MACRO_LAG_DAYS)
    ctx['btc'] = align(btc_d['close'], idx, 0)
    if eth_d is not None:
        ctx['eth'] = align(eth_d['close'], idx, 0)
    return ctx


def make_stops(d):
    # per-bar stop distance (fraction of entry). ATR known at the previous close.
    h = d['high']
    l = d['low']
    c = d['close']
    pc = c.shift(1)
    tr = pd.concat([h - l, (h - pc).abs(), (l - pc).abs()], axis=1).max(axis=1)
    atr = tr.rolling(ATR_LEN).mean().shift(1)
    s = (ATR_MULT * atr / d['open']).clip(lower=ATR_FLOOR, upper=STOP)
    s = s.fillna(STOP).values.astype(float)
    return {'cap': np.full(len(d), STOP, dtype=float), 'atr': s}


def sma(s, n):
    return s.rolling(n).mean()


def ratio_high(num, den, n):
    r = num / den
    return r >= r.rolling(n).max()


# ----------------------------------------------------------------- idea rules
def cond_yld_up(ctx, bsma, ysma):
    y = ctx['us10y']
    b = ctx['btc']
    return (y > sma(y, ysma)) & (b < sma(b, bsma))


def cond_bear_flat(ctx, bsma, ysma):
    y2 = ctx['us2y']
    curve = ctx['us10y'] - y2
    b = ctx['btc']
    return (y2 > sma(y2, ysma)) & (curve < sma(curve, 50)) & (b < sma(b, bsma))


def f_yld_up_btc_weak(d, ctx):
    return cond_yld_up(ctx, 50, 20)


def f_bear_flat(d, ctx):
    return cond_bear_flat(ctx, 50, 20)


def f_spy_weak_yld_up(d, ctx):
    r = ctx['btc'] / ctx['spy']
    y = ctx['us10y']
    return (r < sma(r, 50)) & (y > sma(y, 20))


def f_gold_weak_yld_up(d, ctx):
    r = ctx['btc'] / ctx['gold']
    y = ctx['us10y']
    return (r < sma(r, 50)) & (y > sma(y, 20))


def f_dxy_up_btc_weak(d, ctx):
    x = ctx['dxy']
    b = ctx['btc']
    return (x > sma(x, 20)) & (b < sma(b, 50))


def f_credit_fall_btc_weak(d, ctx):
    r = ctx['hyg'] / ctx['ief']
    b = ctx['btc']
    return (r < sma(r, 20)) & (b < sma(b, 50))


def f_btc_spy_brk30(d, ctx):
    return ratio_high(ctx['btc'], ctx['spy'], 30)


def f_btc_spy_brk45(d, ctx):
    return ratio_high(ctx['btc'], ctx['spy'], 45)


def f_btc_silver_brk20(d, ctx):
    return ratio_high(ctx['btc'], ctx['silver'], 20)


def f_btc_qqq_brk30(d, ctx):
    return ratio_high(ctx['btc'], ctx['qqq'], 30)


# reference winners from earlier batches (used only for the overlap matrix)
def f_ref_btc_gold_brk90(d, ctx):
    return ratio_high(ctx['btc'], ctx['gold'], 90)


def f_ref_btc_dom_up(d, ctx):
    r = ctx['eth'] / ctx['btc']
    return ((r / r.shift(20) - 1.0) <= -0.08) & (ctx['btc'] > sma(ctx['btc'], 50))


def f_ref_btc_spy_brk120(d, ctx):
    return ratio_high(ctx['btc'], ctx['spy'], 120)


def f_ref_y10_lt_sma20(d, ctx):
    y = ctx['us10y']
    return y < sma(y, 20)


# (name, direction, mode, H, fn, needs, use_atr, description)
IDEAS = [
    ('YLD_UP_BTC_WEAK_ATR', -1, 'state', 20, f_yld_up_btc_weak, ['us10y'], True, 'short while US10Y > SMA20 and BTC < SMA50'),
    ('BEAR_FLAT_ATR', -1, 'state', 20, f_bear_flat, ['us2y', 'us10y'], True, 'short while 2Y > SMA20, curve < SMA50, BTC < SMA50'),
    ('SPY_WEAK_YLD_UP', -1, 'state', 20, f_spy_weak_yld_up, ['spy', 'us10y'], True, 'short while BTC/SPY < SMA50 and US10Y > SMA20'),
    ('GOLD_WEAK_YLD_UP', -1, 'state', 20, f_gold_weak_yld_up, ['gold', 'us10y'], True, 'short while BTC/gold < SMA50 and US10Y > SMA20'),
    ('DXY_UP_BTC_WEAK', -1, 'state', 20, f_dxy_up_btc_weak, ['dxy'], True, 'short while DXY > SMA20 and BTC < SMA50'),
    ('CREDIT_FALL_BTC_WEAK', -1, 'state', 20, f_credit_fall_btc_weak, ['hyg', 'ief'], True, 'short while HYG/IEF < SMA20 and BTC < SMA50'),
    ('BTC_SPY_BRK30', 1, 'fixed', 10, f_btc_spy_brk30, ['spy'], False, 'BTC/SPY at new 30d high -> long 10d'),
    ('BTC_SPY_BRK45', 1, 'fixed', 15, f_btc_spy_brk45, ['spy'], False, 'BTC/SPY at new 45d high -> long 15d'),
    ('BTC_SILVER_BRK20', 1, 'fixed', 10, f_btc_silver_brk20, ['silver'], False, 'BTC/silver at new 20d high -> long 10d'),
    ('BTC_QQQ_BRK30', 1, 'fixed', 10, f_btc_qqq_brk30, ['qqq'], False, 'BTC/QQQ at new 30d high -> long 10d'),
]

REFS = [
    ('REF_BTC_GOLD_BRK90', 1, 'fixed', 15, f_ref_btc_gold_brk90, ['gold'], False, 'batch 2 winner'),
    ('REF_BTC_DOM_UP', 1, 'fixed', 10, f_ref_btc_dom_up, ['eth', 'btc'], False, 'batch 2 winner'),
    ('REF_BTC_SPY_BRK120', 1, 'fixed', 20, f_ref_btc_spy_brk120, ['spy'], False, 'batch 3 winner'),
    ('REF_Y10_LT_SMA20', 1, 'state', 30, f_ref_y10_lt_sma20, ['us10y'], False, 'other script long regime'),
]


# ----------------------------------------------------------------- engine
def trade_ret(o, hi, lo, j, dur, direction, s):
    # entry at open[j], exit at open[j+dur], stop distance s (fraction), checked on bars j .. j+dur-1
    e = j + dur
    if dur <= 0 or e >= len(o):
        return np.nan
    entry = o[j]
    if direction > 0:
        if lo[j:e].min() <= entry * (1.0 - s):
            g = -s
        else:
            g = o[e] / entry - 1.0
    else:
        if hi[j:e].max() >= entry * (1.0 + s):
            g = -s
        else:
            g = -(o[e] / entry - 1.0)
    return g - 2.0 * COST


def gen_trades(cond, d, direction, mode, H, stops):
    n = len(d)
    o = d['open'].values
    hi = d['high'].values
    lo = d['low'].values
    idx = d.index
    c = cond.fillna(False).values.astype(bool)
    trades = []
    i = 0
    while i < n - 1:
        fire = bool(c[i]) and (i == 0 or not bool(c[i - 1]))
        j = i + 1
        if (not fire) or idx[j] < START:
            i += 1
            continue
        if mode == 'fixed':
            e = j + H
        else:
            e = None
            t = j
            while t < n:
                if (not bool(c[t])) or (t + 1 - j >= H):
                    e = t + 1
                    break
                t += 1
            if e is None:
                break
        if e >= n:
            break
        r = trade_ret(o, hi, lo, j, e - j, direction, stops[j])
        if not np.isnan(r):
            trades.append((idx[j], float(r), int(e - j), int(j)))
        i = e - 1
    return trades


def placebo_score(strat_pf, durs, d, direction, stops, rng):
    if len(durs) == 0 or strat_pf is None or np.isnan(strat_pf):
        return np.nan
    n = len(d)
    o = d['open'].values
    hi = d['high'].values
    lo = d['low'].values
    jmin = int(d.index.searchsorted(START))
    beats = 0
    for _ in range(PLACEBO_RUNS):
        rs = []
        for dur in durs:
            top = n - dur - 1
            if top <= jmin:
                continue
            j = int(rng.integers(jmin, top + 1))
            r = trade_ret(o, hi, lo, j, dur, direction, stops[j])
            if not np.isnan(r):
                rs.append(r)
        p = pf(rs)
        if strat_pf > p:
            beats += 1
    return 100.0 * beats / PLACEBO_RUNS


def verdict(n, pf_a, pf_b, pf_all, pf_eth, plc):
    keep = (n >= 30 and gt(pf_a, 1.3) and gt(pf_b, 1.3) and gt(pf_eth, 1.0) and ge(plc, 90))
    if keep:
        return 'KEEP'
    if n >= 60 and ge(pf_all, 1.1):
        return 'NEAR'
    return 'REJECT'


def h2_pass(n, pf_b, pf_eth, plc):
    return n >= 30 and gt(pf_b, 1.3) and gt(pf_eth, 1.0) and ge(plc, 90)


def build_mask(n, js, durs):
    m = np.zeros(n, dtype=bool)
    for j, dur in zip(js, durs):
        m[j:j + dur] = True
    return m


def run_idea(env, direction, mode, H, fn, use_atr, with_placebo=True):
    key = 'atr' if use_atr else 'cap'
    btc_d = env['btc']
    cond_b = fn(btc_d, env['ctx_b'])
    tb = gen_trades(cond_b, btc_d, direction, mode, H, env['stop_b'][key])
    rets = np.array([t[1] for t in tb], dtype=float)
    durs = [t[2] for t in tb]
    js = [t[3] for t in tb]
    yrs = np.array([t[0].year for t in tb], dtype=int)
    n = len(rets)
    out = {}
    out['n'] = n
    out['rets'] = rets
    out['durs'] = durs
    out['js'] = js
    out['yrs'] = yrs
    out['pf'] = pf(rets)
    out['pf_a'] = pf(rets[yrs <= 2020])
    out['pf_b'] = pf(rets[yrs >= 2021])
    out['dd'] = max_dd(rets)
    out['tpy'] = n / env['span_years']
    out['avg_h'] = float(np.mean(durs)) if n else 0.0
    out['expo'] = (float(np.sum(durs)) / env['span_days'] * 100.0) if n else 0.0
    out['win'] = float((rets > 0).mean() * 100.0) if n else 0.0
    out['avg'] = float(rets.mean() * 100.0) if n else 0.0
    out['plc'] = placebo_score(out['pf'], durs, btc_d, direction, env['stop_b'][key], env['rng']) if with_placebo else np.nan
    pf_eth = np.nan
    n_eth = 0
    if env['eth'] is not None and env['ctx_e'] is not None:
        try:
            cond_e = fn(env['eth'], env['ctx_e'])
            te = gen_trades(cond_e, env['eth'], direction, mode, H, env['stop_e'][key])
            rets_e = np.array([t[1] for t in te], dtype=float)
            n_eth = len(rets_e)
            pf_eth = pf(rets_e)
        except Exception as e:
            print('  ETH test failed:', e)
            pf_eth = 0.0
    out['pf_eth'] = pf_eth
    out['n_eth'] = n_eth
    return out


def missing_data(env, needs):
    return [k for k in needs if (k not in env['ctx_b']) or env['ctx_b'][k].isna().all()]


def year_string(res):
    parts = []
    for y in sorted(set(res['yrs'].tolist())):
        sel = res['rets'][res['yrs'] == y]
        parts.append(str(y) + ':' + f2(pf(sel)) + '(' + str(len(sel)) + ')')
    return '  '.join(parts) if parts else 'no trades'


# ----------------------------------------------------------------- parts
def part_a(env):
    print('')
    print('#' * 78)
    print('PART A: 10 IDEAS')
    print('#' * 78)
    rows = []
    masks = {}
    dirs = {}
    for (name, direction, mode, H, fn, needs, use_atr, logic) in IDEAS:
        dir_s = 'LONG' if direction > 0 else 'SHORT'
        stop_s = 'ATR2.5' if use_atr else 'cap10'
        print('')
        print('=' * 78)
        print(name + '  [' + dir_s + ', ' + mode + ', ' + ('hold ' if mode == 'fixed' else 'max hold ') + str(H) + 'd, stop ' + stop_s + ']  ' + logic)
        miss = missing_data(env, needs)
        if miss:
            print('  SKIPPED - missing data: ' + ', '.join(miss))
            rows.append({'idea': name, 'dir': dir_s, 'mode': mode, 'stop': stop_s, 'avgH': np.nan, 'n': 0,
                         'tr/yr': np.nan, 'expo%': np.nan, 'PF': np.nan, 'PF17-20': np.nan, 'PF21-26': np.nan,
                         'ETH_PF': np.nan, 'maxDD%': np.nan, 'placebo': np.nan, 'verdict': 'SKIP', 'H2_PASS': False})
            continue
        try:
            res = run_idea(env, direction, mode, H, fn, use_atr, True)
            v = verdict(res['n'], res['pf_a'], res['pf_b'], res['pf'], res['pf_eth'], res['plc'])
            hp = h2_pass(res['n'], res['pf_b'], res['pf_eth'], res['plc'])
            print('  n=' + str(res['n']) + '  trades/yr=' + f2(res['tpy']) + '  avg hold=' + f2(res['avg_h'])
                  + 'd  time in market=' + f2(res['expo']) + '%')
            print('  PF=' + f2(res['pf']) + '  PF17-20=' + f2(res['pf_a']) + '  PF21-26=' + f2(res['pf_b'])
                  + '  ETH PF=' + f2(res['pf_eth']) + ' (n=' + str(res['n_eth']) + ')')
            print('  maxDD=' + f2(res['dd']) + '% (2% risk/trade)  win%=' + f2(res['win'])
                  + '  avg trade=' + f2(res['avg']) + '%  placebo=' + f2(res['plc']) + '%')
            print('  PF by year (n): ' + year_string(res))
            print('  VERDICT: ' + v + '   H2_PASS (n>=30, PF21-26>1.3, ETH>1, placebo>=90): ' + str(hp))
            rows.append({'idea': name, 'dir': dir_s, 'mode': mode, 'stop': stop_s,
                         'avgH': r2(res['avg_h'], 1), 'n': res['n'], 'tr/yr': r2(res['tpy'], 1),
                         'expo%': r2(res['expo'], 1), 'PF': r2(res['pf']), 'PF17-20': r2(res['pf_a']),
                         'PF21-26': r2(res['pf_b']), 'ETH_PF': r2(res['pf_eth']), 'maxDD%': r2(res['dd'], 1),
                         'placebo': res['plc'], 'verdict': v, 'H2_PASS': bool(hp)})
            masks[name] = build_mask(len(env['btc']), res['js'], res['durs'])
            dirs[name] = direction
        except Exception as e:
            print('  ERROR while testing ' + name + ': ' + str(e))
            rows.append({'idea': name, 'dir': dir_s, 'mode': mode, 'stop': stop_s, 'avgH': np.nan, 'n': 0,
                         'tr/yr': np.nan, 'expo%': np.nan, 'PF': np.nan, 'PF17-20': np.nan, 'PF21-26': np.nan,
                         'ETH_PF': np.nan, 'maxDD%': np.nan, 'placebo': np.nan, 'verdict': 'ERROR', 'H2_PASS': False})
    return rows, masks, dirs


def part_b(env):
    print('')
    print('#' * 78)
    print('PART B: PLATEAU SWEEPS FOR THE TWO RATE SHORTS (2.5 ATR stop, state mode)')
    print('#' * 78)
    specs = [
        ('YLD_UP_BTC_WEAK', cond_yld_up, ['us10y'], 'US10Y > yieldSMA and BTC < btcSMA'),
        ('BEAR_FLAT', cond_bear_flat, ['us2y', 'us10y'], '2Y > yieldSMA, curve < SMA50, BTC < btcSMA'),
    ]
    for (label, builder, needs, desc) in specs:
        print('')
        print('=' * 78)
        print(label + ' sweep: ' + desc)
        miss = missing_data(env, needs)
        if miss:
            print('  SKIPPED - missing data: ' + ', '.join(miss))
            continue
        rows = []
        for bs in [20, 50, 100]:
            for ys in [10, 20, 50]:
                for mh in [10, 20, 30]:
                    fn = (lambda d_, c_, bs=bs, ys=ys: builder(c_, bs, ys))
                    try:
                        res = run_idea(env, -1, 'state', mh, fn, True, True)
                    except Exception as e:
                        print('  combo failed', bs, ys, mh, str(e))
                        continue
                    rows.append({'btcSMA': bs, 'yldSMA': ys, 'maxH': mh, 'n': res['n'], 'tr/yr': r2(res['tpy'], 1),
                                 'expo%': r2(res['expo'], 1), 'PF': r2(res['pf']), 'PF17-20': r2(res['pf_a']),
                                 'PF21-26': r2(res['pf_b']), 'ETH_PF': r2(res['pf_eth']), 'placebo': res['plc'],
                                 'base': '*' if (bs == 50 and ys == 20 and mh == 20) else ''})
        if not rows:
            print('  no sweep rows')
            continue
        table = pd.DataFrame(rows)
        print(table.to_string(index=False))
        print('')
        for mh in [10, 20, 30]:
            sub = table[table['maxH'] == mh]
            if len(sub) == 0:
                continue
            piv = sub.pivot_table(index='btcSMA', columns='yldSMA', values='PF21-26', aggfunc='first')
            print('PF 2021-26, max hold ' + str(mh) + 'd (rows: BTC SMA, cols: yield SMA)')
            print(piv.round(2).to_string())
        pf_b_vals = table['PF21-26'].astype(float).values
        pf_vals = table['PF'].astype(float).values
        plc_vals = table['placebo'].astype(float).values
        print('')
        print('PLATEAU CHECK ' + label + ': combos=' + str(len(table))
              + '  PF21-26>1.3: ' + str(int(np.sum(pf_b_vals > 1.3))) + '/' + str(len(table))
              + '  PF>1.3: ' + str(int(np.sum(pf_vals > 1.3))) + '/' + str(len(table))
              + '  placebo>=90: ' + str(int(np.sum(plc_vals >= 90))) + '/' + str(len(table))
              + '  median PF21-26=' + f2(float(np.median(pf_b_vals)))
              + '  min PF21-26=' + f2(float(np.min(pf_b_vals))))
        print('')
        print('STOP COMPARISON at base setting (BTC SMA50, yield SMA20, max hold 20d):')
        fn0 = (lambda d_, c_: builder(c_, 50, 20))
        for lab, use in [('10% cap', False), ('2.5 ATR (cap 10%)', True)]:
            try:
                res = run_idea(env, -1, 'state', 20, fn0, use, True)
                print('  ' + lab + ': n=' + str(res['n']) + '  PF=' + f2(res['pf']) + '  PF17-20=' + f2(res['pf_a'])
                      + '  PF21-26=' + f2(res['pf_b']) + '  ETH PF=' + f2(res['pf_eth'])
                      + '  maxDD=' + f2(res['dd']) + '%  win%=' + f2(res['win']) + '  placebo=' + f2(res['plc']) + '%')
            except Exception as e:
                print('  ' + lab + ' failed: ' + str(e))


def part_c(env):
    print('')
    print('#' * 78)
    print('PART C: BTC/ASSET RATIO-HIGH BREAKOUT SWEEP (long, fixed hold, 10% stop)')
    print('#' * 78)
    assets = ['spy', 'qqq', 'gold', 'silver', 'copper']
    rows = []
    for key in assets:
        if missing_data(env, [key]):
            print('  SKIPPED asset ' + key + ' (no data)')
            continue
        for lb in [20, 30, 45]:
            for H in [10, 15]:
                fn = (lambda d_, c_, k=key, lb=lb: ratio_high(c_['btc'], c_[k], lb))
                try:
                    res = run_idea(env, 1, 'fixed', H, fn, False, True)
                except Exception as e:
                    print('  combo failed', key, lb, H, str(e))
                    continue
                ok_h2 = gt(res['pf_b'], 1.3)
                rows.append({'asset': key, 'lookback': lb, 'hold': H, 'n': res['n'], 'tr/yr': r2(res['tpy'], 1),
                             'expo%': r2(res['expo'], 1), 'PF': r2(res['pf']), 'PF17-20': r2(res['pf_a']),
                             'PF21-26': r2(res['pf_b']), 'ETH_PF': r2(res['pf_eth']), 'placebo': res['plc'],
                             'H2>1.3': bool(ok_h2),
                             'PASS': bool(h2_pass(res['n'], res['pf_b'], res['pf_eth'], res['plc']))})
    if not rows:
        print('  no sweep rows')
        return
    table = pd.DataFrame(rows)
    table = table.sort_values(by='PF21-26', ascending=False)
    print(table.to_string(index=False))
    print('')
    print('BREAKOUT SWEEP: combos=' + str(len(table)) + '  with PF21-26>1.3: ' + str(int(table['H2>1.3'].sum()))
          + '  PASS (n>=30, PF21-26>1.3, ETH>1, placebo>=90): ' + str(int(table['PASS'].sum())))
    passed = table[table['PASS']]
    if len(passed):
        print('PASSING COMBOS: ' + ', '.join([str(r['asset']) + '/' + str(r['lookback']) + 'd/hold' + str(r['hold'])
                                              for _, r in passed.iterrows()]))
    else:
        print('PASSING COMBOS: none')


def part_d(env, masks, dirs):
    print('')
    print('#' * 78)
    print('PART D: TIME IN MARKET AND OVERLAP')
    print('#' * 78)
    all_masks = dict(masks)
    all_dirs = dict(dirs)
    print('')
    print('Reference winners (BTC only, for overlap):')
    for (name, direction, mode, H, fn, needs, use_atr, logic) in REFS:
        miss = missing_data(env, needs)
        if miss:
            print('  ' + name + ' SKIPPED - missing data: ' + ', '.join(miss))
            continue
        try:
            res = run_idea(env, direction, mode, H, fn, use_atr, False)
            print('  ' + name + ': n=' + str(res['n']) + '  tr/yr=' + f2(res['tpy']) + '  PF=' + f2(res['pf'])
                  + '  time in market=' + f2(res['expo']) + '%')
            all_masks[name] = build_mask(len(env['btc']), res['js'], res['durs'])
            all_dirs[name] = direction
        except Exception as e:
            print('  ' + name + ' failed: ' + str(e))

    names = list(all_masks.keys())
    if len(names) < 2:
        print('Not enough ideas with trades for an overlap matrix.')
        return
    print('')
    print('Time in market (% of days in a position, 2017+):')
    for nm in names:
        print('  ' + nm + ': ' + f2(100.0 * all_masks[nm].sum() / env['span_days']) + '%')

    mat = []
    for a in names:
        row = []
        sa = all_masks[a].sum()
        for b in names:
            row.append(100.0 * (all_masks[a] & all_masks[b]).sum() / sa if sa > 0 else 0.0)
        mat.append(row)
    labels = [str(i + 1) + ' ' + nm for i, nm in enumerate(names)]
    cols = [str(i + 1) for i in range(len(names))]
    df = pd.DataFrame(mat, index=labels, columns=cols).round(0).astype(int)
    print('')
    print('OVERLAP MATRIX: row A, column B = % of A\'s days in position where B is also in position')
    pd.set_option('display.width', 250)
    pd.set_option('display.max_columns', 50)
    print(df.to_string())

    print('')
    print('High-overlap pairs (>= 50% of days, either direction):')
    found = False
    for ia in range(len(names)):
        for ib in range(ia + 1, len(names)):
            a = names[ia]
            b = names[ib]
            both = float((all_masks[a] & all_masks[b]).sum())
            pa = 100.0 * both / all_masks[a].sum() if all_masks[a].sum() > 0 else 0.0
            pb = 100.0 * both / all_masks[b].sum() if all_masks[b].sum() > 0 else 0.0
            if max(pa, pb) >= 50.0:
                tag = 'OPPOSITE SIDES' if all_dirs[a] != all_dirs[b] else 'same side'
                print('  ' + a + ' / ' + b + ': ' + f2(pa) + '% / ' + f2(pb) + '%  (' + tag + ')')
                found = True
    if not found:
        print('  none')

    print('')
    print('Long vs short conflicts (days where a long and a short idea are open together):')
    found = False
    for a in names:
        for b in names:
            if all_dirs[a] > 0 and all_dirs[b] < 0:
                days = int((all_masks[a] & all_masks[b]).sum())
                if days > 0:
                    print('  LONG ' + a + ' vs SHORT ' + b + ': ' + str(days) + ' days')
                    found = True
    if not found:
        print('  none')

    short_names = [nm for nm in names if all_dirs[nm] < 0]
    if short_names:
        count = np.zeros(len(env['btc']), dtype=int)
        for nm in short_names:
            count += all_masks[nm].astype(int)
        print('')
        print('SHORT BOOK COVERAGE (% of days): at least 1 short open = ' + f2(100.0 * (count >= 1).sum() / env['span_days'])
              + '%   2 or more = ' + f2(100.0 * (count >= 2).sum() / env['span_days'])
              + '%   3 or more = ' + f2(100.0 * (count >= 3).sum() / env['span_days']) + '%')


def main():
    print('Downloading data...')
    btc_d = load_daily_from_1h('btc_1h_full.csv.gz')
    eth_d = load_daily_from_1h('eth_1h_full.csv.gz')
    if btc_d is None:
        print('BTC data is required. Stopping.')
        raise SystemExit
    macro = {}
    for k, tks in MACRO_TICKERS.items():
        macro[k] = load_first(k, tks)

    ctx_b = make_ctx(btc_d, macro, btc_d, eth_d)
    ctx_e = make_ctx(eth_d, macro, btc_d, eth_d) if eth_d is not None else None
    span_years = max((btc_d.index[-1] - max(START, btc_d.index[0])).days / 365.25, 0.1)

    env = {
        'btc': btc_d,
        'eth': eth_d,
        'ctx_b': ctx_b,
        'ctx_e': ctx_e,
        'stop_b': make_stops(btc_d),
        'stop_e': make_stops(eth_d) if eth_d is not None else None,
        'span_years': span_years,
        'span_days': span_years * 365.25,
        'rng': np.random.default_rng(SEED),
    }

    rows, masks, dirs = part_a(env)
    part_b(env)
    part_c(env)
    part_d(env, masks, dirs)

    print('')
    print('=' * 78)
    print('SUMMARY (part A ideas; BTC unless noted; 0.12%/side, next-bar-open entries)')
    print('=' * 78)
    table = pd.DataFrame(rows)
    pd.set_option('display.width', 250)
    pd.set_option('display.max_columns', 50)
    print(table.to_string(index=False))

    print('')
    print('VERDICTS')
    print('-' * 78)
    for label in ['KEEP', 'NEAR', 'REJECT', 'SKIP', 'ERROR']:
        names = [r['idea'] for r in rows if r['verdict'] == label]
        if names or label in ['KEEP', 'NEAR', 'REJECT']:
            print(label + ': ' + (', '.join(names) if names else '-'))
    h2 = [r['idea'] for r in rows if r['H2_PASS']]
    print('H2_PASS (fails only the 2017-20 half is allowed): ' + (', '.join(h2) if h2 else '-'))
    print('')
    print('Paste this whole output back for ranking and exact rules of the best 3.')


if __name__ == '__main__':
    main()
