# BTC / ETH multi-day idea lab, BATCH 2 (Colab, self-contained)
# Not executed by the author. Run it yourself: upload to Colab and run, or paste into one cell.
#
# Same engine as batch 1:
# - Signal from the CLOSED daily bar i, entry at the OPEN of day i+1, exit at the open H days later.
# - Edge-triggered signals, one position at a time per idea, 0.12% per side, 10% hard stop.
# - Macro data lagged one extra day. Placebo = 100 random-entry runs (same count/hold/direction).
#
# IDEAS (batch 2)
#  1 BTC_GOLD_BRK   long  15d  BTC/gold ratio closes at a new 90-day high
#  2 AU_AG_DROP     long  15d  gold/silver ratio 20d change <= -4%
#  3 USDJPY_UNWIND  short  7d  USDJPY 10d change <= -3% (yen carry unwind)
#  4 TIP_IEF_UP     long  15d  TIP/IEF ratio 20d change >= +1% (inflation expectations rising)
#  5 OIL_UP_LONG    long  10d  oil 10d return >= +15% (POST-HOC mirror of failed OIL_SHOCK short)
#  6 BTC_DOM_UP     long  10d  ETH/BTC 20d change <= -8% and BTC close > SMA50
#  7 RV_EXP_UP      long  10d  7d realized vol / 60d realized vol >= 1.6 and close > SMA50
#  8 WEEKLY_HL3     long  14d  3 straight completed weeks of higher low and higher close
#  9 OBV_LEAD       long  15d  OBV at 90d high while price is >= 5% below its 90d high
# 10 DD_RECLAIM     long  20d  90d drawdown reached <= -25% in last 20 days, then close > prior 20d 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/'
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',
    'silver': 'SI=F',
    'usdjpy': 'JPY=X',
    'oil': 'CL=F',
    '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={'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_btc_gold_brk(d, ctx):
    r = ctx['btc'] / ctx['gold']
    return r >= r.rolling(90).max()


def f_au_ag_drop(d, ctx):
    r = ctx['gold'] / ctx['silver']
    return (r / r.shift(20) - 1.0) <= -0.04


def f_usdjpy_unwind(d, ctx):
    u = ctx['usdjpy']
    return (u / u.shift(10) - 1.0) <= -0.03


def f_tip_ief_up(d, ctx):
    r = ctx['tip'] / ctx['ief']
    return (r / r.shift(20) - 1.0) >= 0.01


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


def f_btc_dom_up(d, ctx):
    r = ctx['eth'] / ctx['btc']
    weak_eth = (r / r.shift(20) - 1.0) <= -0.08
    btc_up = ctx['btc'] > ctx['btc'].rolling(50).mean()
    return weak_eth & btc_up


def f_rv_exp_up(d, ctx):
    ret = d['close'].pct_change()
    rv7 = ret.rolling(7).std()
    rv60 = ret.rolling(60).std()
    return ((rv7 / rv60) >= 1.6) & (d['close'] > d['close'].rolling(50).mean())


def f_weekly_hl3(d, ctx):
    agg = {'high': 'max', 'low': 'min', 'close': 'last'}
    w = d[['high', 'low', 'close']].resample('W-SUN').agg(agg)
    up = (w['low'] > w['low'].shift(1)) & (w['close'] > w['close'].shift(1))
    three = up & up.shift(1, fill_value=False) & up.shift(2, fill_value=False)
    x = three.astype(float).reindex(d.index, method='ffill')
    return x > 0.5


def f_obv_lead(d, ctx):
    obv = (np.sign(d['close'].diff()) * d['volume']).fillna(0.0).cumsum()
    obv_hi = obv >= obv.rolling(90).max()
    px_far = d['close'] <= 0.95 * d['close'].rolling(90).max()
    return obv_hi & px_far


def f_dd_reclaim(d, ctx):
    dd = d['close'] / d['close'].rolling(90).max() - 1.0
    deep = dd.rolling(20).min() <= -0.25
    brk = d['close'] > d['close'].shift(1).rolling(20).max()
    return deep & brk


IDEAS = [
    ('BTC_GOLD_BRK', 1, 15, f_btc_gold_brk, ['gold'], 'BTC/gold ratio at new 90d high -> long'),
    ('AU_AG_DROP', 1, 15, f_au_ag_drop, ['gold', 'silver'], 'gold/silver 20d change <= -4% -> long'),
    ('USDJPY_UNWIND', -1, 7, f_usdjpy_unwind, ['usdjpy'], 'USDJPY 10d change <= -3% -> short'),
    ('TIP_IEF_UP', 1, 15, f_tip_ief_up, ['tip', 'ief'], 'TIP/IEF 20d change >= +1% -> long'),
    ('OIL_UP_LONG', 1, 10, f_oil_up_long, ['oil'], 'oil 10d >= +15% -> long (post-hoc mirror of OIL_SHOCK)'),
    ('BTC_DOM_UP', 1, 10, f_btc_dom_up, ['eth', 'btc'], 'ETH/BTC 20d <= -8% and BTC > SMA50 -> long'),
    ('RV_EXP_UP', 1, 10, f_rv_exp_up, [], 'RV7/RV60 >= 1.6 and close > SMA50 -> long'),
    ('WEEKLY_HL3', 1, 14, f_weekly_hl3, [], '3 weeks of higher lows and higher closes -> long'),
    ('OBV_LEAD', 1, 15, f_obv_lead, [], 'OBV 90d high with price >= 5% under 90d high -> long'),
    ('DD_RECLAIM', 1, 20, f_dd_reclaim, [], 'drawdown <= -25% in last 20d, then close > prior 20d high -> 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()
