# BTC / ETH multi-day idea lab (Colab, self-contained)
# Not executed by the author. Run it yourself: upload to Colab and run, or paste into one cell.
#
# DESIGN
# - Data: 1h BTC and ETH from osom-boba.pages.dev, resampled to UTC daily bars.
# - Free macro data via yfinance, lagged one extra day (MACRO_LAG_DAYS) to be safe.
# - Signal is computed from the CLOSED daily bar i, entry is the OPEN of day i+1 (next bar open),
#   exit is the open H days later. No lookahead.
# - Every signal is edge-triggered (fires on the first day the condition turns true).
# - One position at a time per idea (non-overlapping), 0.12% per side, 10% hard stop checked
#   against daily high/low (fill at the stop).
# - Max drawdown uses compounded trades at 2% risk per trade (20% notional with a 10% stop).
# - Placebo: 100 runs of random entries (same count, same hold, same direction, same stop and costs),
#   score = % of runs where the idea's PF beats the random PF.
#
# IDEAS (all multi-day, none duplicate the live engines)
#  1 GOLD_BRK       long  15d  gold close makes a new 55-day high
#  2 US10Y_DROP     long  10d  US 10y yield 10-day change <= -6%
#  3 OIL_SHOCK      short 10d  crude oil 10-day return >= +15%
#  4 CU_AU          long  15d  copper/gold ratio 20d change >= +4% and ratio above its 100d SMA
#  5 ETHBTC_RS      long  10d  ETH/BTC ratio 20d change >= +10%
#  6 SEMIVOL        long  15d  30d upside/downside semivariance >= 1.5 and close > SMA50
#  7 MONTH_BRK      long  20d  close above the prior calendar month's high
#  8 DEEP_DISC      long  25d  close / SMA200 <= 0.78
#  9 CREDIT_STRESS  short 10d  HYG/IEF ratio 20d change <= -2%
# 10 VOL_SURGE      long  10d  5d avg volume / 60d avg volume >= 1.5, 5d return > 0, close > SMA100

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/'
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_TICKERS = {
    'gold': 'GC=F',
    'us10y': '^TNX',
    'oil': 'CL=F',
    'copper': 'HG=F',
    'hyg': 'HYG',
    '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={'User-Agent': 'Mozilla/5.0'})
    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()
        print('Loaded', ticker, 'rows:', len(s), 'to', s.index[-1].date())
        return s
    except Exception as e:
        print('yfinance FAILED', ticker, '->', e)
        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 edge(cond):
    s = cond.fillna(False).astype(bool)
    return s & ~s.shift(1, fill_value=False)


# ----------------------------------------------------------------- idea rules
def f_gold_brk(d, ctx):
    g = ctx['gold']
    return g >= g.rolling(55).max()


def f_us10y_drop(d, ctx):
    y = ctx['us10y']
    return (y / y.shift(10) - 1.0) <= -0.06


def f_oil_shock(d, ctx):
    o = ctx['oil']
    base = o.shift(10)
    return (o > 0) & (base > 0) & ((o / base - 1.0) >= 0.15)


def f_cu_au(d, ctx):
    r = ctx['copper'] / ctx['gold']
    return ((r / r.shift(20) - 1.0) >= 0.04) & (r > r.rolling(100).mean())


def f_ethbtc_rs(d, ctx):
    r = ctx['eth'] / ctx['btc']
    return (r / r.shift(20) - 1.0) >= 0.10


def f_semivol(d, ctx):
    ret = d['close'].pct_change()
    up = (ret.clip(lower=0.0) ** 2).rolling(30).sum()
    dn = ((-ret).clip(lower=0.0) ** 2).rolling(30).sum()
    return ((up / dn) >= 1.5) & (d['close'] > d['close'].rolling(50).mean())


def f_month_brk(d, ctx):
    per = pd.Series(d.index.to_period('M'), index=d.index)
    mh = d['high'].groupby(per).max()
    prev = mh.shift(1)
    ph = per.map(prev.to_dict())
    return d['close'] > ph


def f_deep_disc(d, ctx):
    return (d['close'] / d['close'].rolling(200).mean()) <= 0.78


def f_credit_stress(d, ctx):
    r = ctx['hyg'] / ctx['ief']
    return (r / r.shift(20) - 1.0) <= -0.02


def f_vol_surge(d, ctx):
    v5 = d['volume'].rolling(5).mean()
    v60 = d['volume'].rolling(60).mean()
    ret5 = d['close'] / d['close'].shift(5) - 1.0
    return ((v5 / v60) >= 1.5) & (ret5 > 0) & (d['close'] > d['close'].rolling(100).mean())


IDEAS = [
    ('GOLD_BRK', 1, 15, f_gold_brk, ['gold'], 'gold close at new 55d high -> long'),
    ('US10Y_DROP', 1, 10, f_us10y_drop, ['us10y'], 'US10Y 10d change <= -6% -> long'),
    ('OIL_SHOCK', -1, 10, f_oil_shock, ['oil'], 'oil 10d return >= +15% -> short'),
    ('CU_AU', 1, 15, f_cu_au, ['copper', 'gold'], 'copper/gold 20d >= +4% and > SMA100 -> long'),
    ('ETHBTC_RS', 1, 10, f_ethbtc_rs, ['eth', 'btc'], 'ETH/BTC 20d change >= +10% -> long'),
    ('SEMIVOL', 1, 15, f_semivol, [], 'up/down semivariance 30d >= 1.5 and close > SMA50 -> long'),
    ('MONTH_BRK', 1, 20, f_month_brk, [], 'close above prior calendar month high -> long'),
    ('DEEP_DISC', 1, 25, f_deep_disc, [], 'close / SMA200 <= 0.78 -> long'),
    ('CREDIT_STRESS', -1, 10, f_credit_stress, ['hyg', 'ief'], 'HYG/IEF 20d change <= -2% -> short'),
    ('VOL_SURGE', 1, 10, f_vol_surge, [], '5d/60d volume >= 1.5, 5d ret > 0, close > SMA100 -> long'),
]


# ----------------------------------------------------------------- engine
def trade_returns(d, H, direction):
    # net return of a trade entered at open[j], held H daily bars, exited at open[j+H]
    o = d['open']
    exit_o = o.shift(-H)
    if direction > 0:
        wmin = d['low'].rolling(H).min().shift(-(H - 1))
        hit = (wmin <= o * (1.0 - STOP)).values
        gross = np.where(hit, -STOP, (exit_o / o - 1.0).values)
    else:
        wmax = d['high'].rolling(H).max().shift(-(H - 1))
        hit = (wmax >= o * (1.0 + STOP)).values
        gross = np.where(hit, -STOP, (-(exit_o / o - 1.0)).values)
    net = gross - 2.0 * COST
    return pd.Series(net, index=d.index)


def run_trades(sig, ret_all, H, idx):
    trades = []
    next_free = 0
    pos = np.flatnonzero(sig.values)
    for i in pos:
        j = int(i) + 1
        if j >= len(idx):
            break
        if j < next_free:
            continue
        if idx[j] < START:
            continue
        r = ret_all.iloc[j]
        if np.isnan(r):
            continue
        trades.append((idx[j], float(r)))
        next_free = j + H
    return trades


def evaluate(d, ctx, fn, direction, H, cache, key):
    cond = fn(d, ctx)
    sig = edge(cond)
    ck = (key, H, direction)
    if ck not in cache:
        cache[ck] = trade_returns(d, H, direction)
    ret_all = cache[ck]
    return run_trades(sig, ret_all, H, d.index), ret_all


def placebo_score(strat_pf, n, ret_all, idx, rng):
    if n == 0 or strat_pf is None or np.isnan(strat_pf):
        return np.nan
    vals = ret_all.values
    ok = np.flatnonzero((~np.isnan(vals)) & (idx >= START))
    if ok.size == 0:
        return np.nan
    k = min(n, ok.size)
    beats = 0
    for _ in range(PLACEBO_RUNS):
        pick = rng.choice(ok, size=k, replace=False)
        p = pf(vals[pick])
        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'


# ----------------------------------------------------------------- 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, tk in MACRO_TICKERS.items():
        macro[k] = load_yf(tk)

    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)
    rng = np.random.default_rng(SEED)
    cache_b = {}
    cache_e = {}
    rows = []

    for (name, direction, H, fn, needs, logic) in IDEAS:
        dir_s = 'LONG' if direction > 0 else 'SHORT'
        print('')
        print('=' * 78)
        print(name + '  [' + dir_s + ', 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({'idea': name, 'dir': dir_s, 'hold': H, 'n': 0, 'tr/yr': 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'})
            continue
        try:
            trades_b, ret_b = evaluate(btc_d, ctx_b, fn, direction, H, cache_b, 'btc')
            dates = [t[0] for t in trades_b]
            rets = np.array([t[1] for t in trades_b], dtype=float)
            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
            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, n, ret_b, btc_d.index, rng)

            pf_eth = np.nan
            n_eth = 0
            if eth_d is not None and ctx_e is not None:
                try:
                    trades_e, _ = evaluate(eth_d, ctx_e, fn, direction, H, cache_e, 'eth')
                    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) + '  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, 'hold': H, 'n': n, 'tr/yr': round(tpy, 1),
                         '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({'idea': name, 'dir': dir_s, 'hold': H, 'n': 0, 'tr/yr': 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'})

    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()
