# BTC / ETH multi-day idea lab, BATCH 3 (Colab, self-contained)
# Not executed by the author. Run it yourself: upload to Colab and run, or paste into one cell.
#
# ENGINE (same as batches 1 and 2, plus regime-hold trades)
# - Signal from the CLOSED daily bar i, entry at the OPEN of day i+1 (next bar open). No lookahead.
# - Entry fires only 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. After any daily close where the condition is
#   false, exit at the next open. Max hold H days (then exit at the open, no re-entry until the
#   condition turns false and true again).
# - 0.12% per side, 10% hard stop checked on daily high/low (fill at the stop), one position at a time.
# - Macro data lagged one extra day. 2Y yield uses 2YY=F if it has enough history, else ^FVX (5Y proxy).
# - Placebo: 100 runs of random entries using the SAME number of trades and the SAME hold lengths
#   as the idea (same direction, stop and costs). Score = % of runs the idea's PF beats.
#
# IDEAS (batch 3)
#  1 BTC_QQQ_BRK60       long  fixed 15d  BTC/QQQ ratio closes at a new 60d high
#  2 BTC_SPY_BRK120      long  fixed 20d  BTC/SPY ratio closes at a new 120d high
#  3 BTC_SILVER_BRK30    long  fixed 10d  BTC/silver ratio closes at a new 30d high
#  4 BTC_COPPER_BRK90    long  fixed 15d  BTC/copper ratio closes at a new 90d high
#  5 Y10_SMA50_LONG      long  state max30d  US10Y < its SMA50
#  6 Y2_SMA20_LONG       long  state max30d  2Y yield (or 5Y proxy) < its SMA20
#  7 REALYLD_EASE_LONG   long  state max30d  TIP > SMA50 and TIP/IEF ratio > its SMA50
#  8 BTC_GOLD_LOW90_SHORT short fixed 15d  BTC/gold ratio closes at a new 90d low
#  9 YLD_UP_BTC_WEAK_SHORT short state max20d  US10Y > its SMA20 and BTC < SMA50
# 10 BEAR_FLAT_SHORT     short state max20d  2Y > its SMA20, 10Y-2Y curve < its SMA50, BTC < SMA50

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 distance
RISK = 0.02              # risk per trade for drawdown sizing
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')   # a macro series must start before this date

MACRO_TICKERS = {
    'gold': ['GC=F'],
    'silver': ['SI=F'],
    'copper': ['HG=F'],
    'qqq': ['QQQ'],
    'spy': ['SPY'],
    'us10y': ['^TNX'],
    'us2y': ['2YY=F', '^FVX'],
    'tip': ['TIP'],
    'ief': ['IEF'],
}


# ----------------------------------------------------------------- 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 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 np.nan
    g = r[r > 0].sum()
    l = -r[r < 0].sum()
    if l == 0:
        return np.inf if g > 0 else np.nan
    return g / l


def max_dd(rets):
    if len(rets) == 0:
        return np.nan
    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 sma(s, n):
    return s.rolling(n).mean()


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


def ratio_low(num, den, n):
    r = num / den
    return r <= r.rolling(n).min()


# ----------------------------------------------------------------- idea rules
def f_btc_qqq_brk60(d, ctx):
    return ratio_high(ctx['btc'], ctx['qqq'], 60)


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


def f_btc_silver_brk30(d, ctx):
    return ratio_high(ctx['btc'], ctx['silver'], 30)


def f_btc_copper_brk90(d, ctx):
    return ratio_high(ctx['btc'], ctx['copper'], 90)


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


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


def f_realyld_ease_long(d, ctx):
    tip = ctx['tip']
    r = tip / ctx['ief']
    return (tip > sma(tip, 50)) & (r > sma(r, 50))


def f_btc_gold_low90_short(d, ctx):
    return ratio_low(ctx['btc'], ctx['gold'], 90)


def f_yld_up_btc_weak_short(d, ctx):
    y = ctx['us10y']
    b = ctx['btc']
    return (y > sma(y, 20)) & (b < sma(b, 50))


def f_bear_flat_short(d, ctx):
    y2 = ctx['us2y']
    curve = ctx['us10y'] - y2
    b = ctx['btc']
    return (y2 > sma(y2, 20)) & (curve < sma(curve, 50)) & (b < sma(b, 50))


# (name, direction, mode, H (fixed hold or state max hold), function, needed data, description)
IDEAS = [
    ('BTC_QQQ_BRK60', 1, 'fixed', 15, f_btc_qqq_brk60, ['qqq'], 'BTC/QQQ at new 60d high -> long 15d'),
    ('BTC_SPY_BRK120', 1, 'fixed', 20, f_btc_spy_brk120, ['spy'], 'BTC/SPY at new 120d high -> long 20d'),
    ('BTC_SILVER_BRK30', 1, 'fixed', 10, f_btc_silver_brk30, ['silver'], 'BTC/silver at new 30d high -> long 10d'),
    ('BTC_COPPER_BRK90', 1, 'fixed', 15, f_btc_copper_brk90, ['copper'], 'BTC/copper at new 90d high -> long 15d'),
    ('Y10_SMA50_LONG', 1, 'state', 30, f_y10_sma50_long, ['us10y'], 'long while US10Y < SMA50 (max 30d)'),
    ('Y2_SMA20_LONG', 1, 'state', 30, f_y2_sma20_long, ['us2y'], 'long while 2Y yield < SMA20 (max 30d)'),
    ('REALYLD_EASE_LONG', 1, 'state', 30, f_realyld_ease_long, ['tip', 'ief'], 'long while TIP > SMA50 and TIP/IEF > SMA50 (max 30d)'),
    ('BTC_GOLD_LOW90_SHORT', -1, 'fixed', 15, f_btc_gold_low90_short, ['gold'], 'BTC/gold at new 90d low -> short 15d'),
    ('YLD_UP_BTC_WEAK_SHORT', -1, 'state', 20, f_yld_up_btc_weak_short, ['us10y'], 'short while US10Y > SMA20 and BTC < SMA50 (max 20d)'),
    ('BEAR_FLAT_SHORT', -1, 'state', 20, f_bear_flat_short, ['us2y', 'us10y'], 'short while 2Y > SMA20, curve < SMA50, BTC < SMA50 (max 20d)'),
]


# ----------------------------------------------------------------- engine
def trade_ret(o, hi, lo, j, dur, direction):
    # entry at open[j], exit at open[j+dur], stop 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 - STOP):
            g = -STOP
        else:
            g = o[e] / entry - 1.0
    else:
        if hi[j:e].max() >= entry * (1.0 + STOP):
            g = -STOP
        else:
            g = -(o[e] / entry - 1.0)
    return g - 2.0 * COST


def gen_trades(cond, d, direction, mode, H):
    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)
        if not np.isnan(r):
            trades.append((idx[j], float(r), int(e - j)))
        i = e - 1
    return trades


def placebo_score(strat_pf, durs, d, direction, 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)
            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 empty_row(name, dir_s, mode, H, tag):
    return {'idea': name, 'dir': dir_s, 'mode': mode, 'avgH': H, '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': tag}


# ----------------------------------------------------------------- main
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)
    span_days = span_years * 365.25
    rng = np.random.default_rng(SEED)
    rows = []

    for (name, direction, mode, H, fn, needs, logic) in IDEAS:
        dir_s = 'LONG' if direction > 0 else 'SHORT'
        print('')
        print('=' * 78)
        print(name + '  [' + dir_s + ', ' + mode + ', ' + ('hold ' if mode == 'fixed' else 'max hold ') + str(H) + 'd]  ' + logic)
        miss = [k for k in needs if (k not in ctx_b) or ctx_b[k].isna().all()]
        if miss:
            print('  SKIPPED - missing data: ' + ', '.join(miss))
            rows.append(empty_row(name, dir_s, mode, H, 'SKIP'))
            continue
        try:
            cond_b = fn(btc_d, ctx_b)
            trades_b = gen_trades(cond_b, btc_d, direction, mode, H)
            dates = [t[0] for t in trades_b]
            rets = np.array([t[1] for t in trades_b], dtype=float)
            durs = [t[2] for t in trades_b]
            yrs = np.array([dt.year for dt in dates], dtype=int)
            n = len(rets)
            pf_all = pf(rets)
            pf_a = pf(rets[yrs <= 2020])
            pf_b = pf(rets[yrs >= 2021])
            dd = max_dd(rets)
            tpy = n / span_years
            avg_h = float(np.mean(durs)) if n else np.nan
            expo = (float(np.sum(durs)) / span_days * 100.0) if n else np.nan
            winp = float((rets > 0).mean() * 100.0) if n else np.nan
            avg = float(rets.mean() * 100.0) if n else np.nan
            plc = placebo_score(pf_all, durs, btc_d, direction, rng)

            pf_eth = np.nan
            n_eth = 0
            if eth_d is not None and ctx_e is not None:
                try:
                    cond_e = fn(eth_d, ctx_e)
                    trades_e = gen_trades(cond_e, eth_d, direction, mode, H)
                    rets_e = np.array([t[1] for t in trades_e], dtype=float)
                    n_eth = len(rets_e)
                    pf_eth = pf(rets_e)
                except Exception as e:
                    print('  ETH test failed:', e)

            by_year = []
            for y in sorted(set(yrs.tolist())):
                sel = rets[yrs == y]
                by_year.append(str(y) + ':' + f2(pf(sel)) + '(' + str(len(sel)) + ')')

            v = verdict(n, pf_a, pf_b, pf_all, pf_eth, plc)
            print('  n=' + str(n) + '  trades/yr=' + f2(tpy) + '  avg hold=' + f2(avg_h) + 'd  time in market='
                  + f2(expo) + '%')
            print('  PF=' + f2(pf_all) + '  PF17-20=' + f2(pf_a) + '  PF21-26=' + f2(pf_b)
                  + '  ETH PF=' + f2(pf_eth) + ' (n=' + str(n_eth) + ')')
            print('  maxDD=' + f2(dd) + '% (2% risk/trade)  win%=' + f2(winp)
                  + '  avg trade=' + f2(avg) + '%  placebo=' + f2(plc) + '%')
            print('  PF by year (n): ' + ('  '.join(by_year) if by_year else 'no trades'))
            print('  VERDICT: ' + v)
            rows.append({'idea': name, 'dir': dir_s, 'mode': mode,
                         'avgH': round(avg_h, 1) if n else np.nan, 'n': n, 'tr/yr': round(tpy, 1),
                         'expo%': round(expo, 1) if n else np.nan,
                         'PF': round(pf_all, 2) if np.isfinite(pf_all) else pf_all,
                         'PF17-20': round(pf_a, 2) if np.isfinite(pf_a) else pf_a,
                         'PF21-26': round(pf_b, 2) if np.isfinite(pf_b) else pf_b,
                         'ETH_PF': round(pf_eth, 2) if np.isfinite(pf_eth) else pf_eth,
                         'maxDD%': round(dd, 1) if np.isfinite(dd) else dd,
                         'placebo': plc, 'verdict': v})
        except Exception as e:
            print('  ERROR while testing ' + name + ': ' + str(e))
            rows.append(empty_row(name, dir_s, mode, H, 'ERROR'))

    print('')
    print('=' * 78)
    print('SUMMARY (BTC unless noted; 0.12%/side, 10% stop, 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 '-'))
    print('')
    print('Paste this whole output back for ranking and exact rules of the best 3.')


if __name__ == '__main__':
    main()
