# M35 macro-score robustness test (Colab, self-contained)
# Not executed by the author. Run it yourself: upload to Colab and run, or paste into one cell.
#
# STAND-IN STRATEGY (daily bars, UTC)
# - Trend: EMA20 vs EMA50 of the close. Signal known at the close of day t-1, trade at the OPEN of day t.
#   Long when EMA20 > EMA50, short otherwise. Reverses on a cross.
# - Stop: 2 x ATR(14) from entry (ATR known before entry), checked on daily high/low, filled at the stop
#   (or at the open if the open gaps through it). After a stop-out the strategy stays flat on that side
#   until the trend signal flips.
# - Sizing: risk 1% of equity per trade = 1% / (2 x ATR) units, times the M35 multiplier. Notional capped
#   at 3x equity. Costs 0.12% per side. Equity compounds and is marked to market daily.
# - The absolute CAGR of this stand-in will NOT match your live bot. Compare variants to each other.
#
# M35 SCORE (one point each, daily closes, lagged by LAG days)
#   US10Y (^TNX) < SMA20, DXY (DX-Y.NYB) < SMA50, TIP > SMA20, HYG > SMA50, Copper/Gold (HG=F/GC=F) > SMA50
#   SMAs are computed on each series' own trading-day closes, then forward-filled to the crypto calendar.
# MULTIPLIERS (up/down). High score: score >= ncomp-1 (4 of 5). Low score: score <= 1.
#   Longs: x up when high, x down when low. Shorts: x down when high, x up when low. Otherwise x1.
#   When a component is dropped, "high" becomes ncomp-1 (3 of 4) and "low" stays <= 1.
#
# TESTS: 1) SMA length x0.5 / x1.5 per component and for all together, 2) lag 1/2/3,
#        3) multipliers 1.25/0.75, 1.5/0.5, 2.0/0.5, 4) drop each component, 5) 2018-21 vs 2022-26 and
#        per year, 6) ETH max drawdown in every variant.

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('2018-01-01')
H1_END = pd.Timestamp('2021-12-31')
H2_START = pd.Timestamp('2022-01-01')
RISK = 0.01
ATR_LEN = 14
ATR_STOP = 2.0
COST = 0.0012            # per side
LEV_CAP = 3.0
BASE_LAG = 1
BASE_UP = 1.5
BASE_DOWN = 0.5
MACRO_MAX_START = pd.Timestamp('2017-06-01')
PRINT_ETH_YEARS = True

MACRO_TICKERS = {
    'us10y': ['^TNX'],
    'dxy': ['DX-Y.NYB', 'UUP'],
    'tip': ['TIP'],
    'hyg': ['HYG'],
    'copper': ['HG=F'],
    'gold': ['GC=F'],
}

# (component name, macro key, operator, base SMA length)
COMPS = [
    ('US10Y', 'us10y', 'below', 20),
    ('DXY', 'dxy', 'below', 50),
    ('TIP', 'tip', 'above', 20),
    ('HYG', 'hyg', 'above', 50),
    ('CUAU', 'cuau', 'above', 50),
]


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


def fmt(x, k=1):
    if x is None:
        return np.nan
    try:
        if np.isfinite(x):
            return round(float(x), k)
    except Exception:
        pass
    return x


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 comp_indicator(s, op, n):
    ma = s.rolling(n).mean()
    cond = (s < ma) if op == 'below' else (s > ma)
    out = cond.astype(float)
    out[ma.isna()] = np.nan
    return out


def build_score(idx, macro, lens, lag, drop):
    cols = []
    for (cname, key, op, base_len) in COMPS:
        if cname in drop:
            continue
        s = macro.get(key)
        if s is None:
            continue
        n = lens.get(cname, base_len)
        ind = comp_indicator(s, op, n)
        col = ind.reindex(idx, method='ffill').shift(lag)
        cols.append(col)
    if not cols:
        return None, 0
    df = pd.concat(cols, axis=1)
    sc = df.sum(axis=1, min_count=len(cols))
    return sc.values.astype(float), len(cols)


def prep_asset(d):
    c = d['close']
    ema20 = c.ewm(span=20, adjust=False).mean()
    ema50 = c.ewm(span=50, adjust=False).mean()
    sig = np.where(ema20.values > ema50.values, 1, -1).astype(int)
    sig[:60] = 0
    pc = c.shift(1)
    tr = pd.concat([d['high'] - d['low'], (d['high'] - pc).abs(), (d['low'] - pc).abs()], axis=1).max(axis=1)
    atr = tr.rolling(ATR_LEN).mean().values.astype(float)
    return {'idx': d.index, 'o': d['open'].values.astype(float), 'h': d['high'].values.astype(float),
            'l': d['low'].values.astype(float), 'c': d['close'].values.astype(float), 'sig': sig, 'atr': atr}


def mult_for(side, score, ncomp, up, down):
    if score is None or np.isnan(score):
        return 1.0
    hi = score >= ncomp - 1
    lo = score <= 1
    if side > 0:
        return up if hi else (down if lo else 1.0)
    return down if hi else (up if lo else 1.0)


def backtest(a, score, ncomp, up, down):
    idx = a['idx']
    o = a['o']
    h = a['h']
    l = a['l']
    c = a['c']
    sig = a['sig']
    atr = a['atr']
    n = len(c)
    i0 = int(idx.searchsorted(START))
    if i0 < 60:
        i0 = 60
    E = 1.0
    units = 0.0
    side = 0
    stop = 0.0
    blocked = 0
    eq = np.full(n, np.nan)
    for t in range(i0, n):
        prev_c = c[t - 1]
        # 1) mark the carried position to the open, check a gap through the stop
        if units != 0.0:
            E += units * (o[t] - prev_c)
            if (side > 0 and o[t] <= stop) or (side < 0 and o[t] >= stop):
                E -= abs(units) * o[t] * COST
                units = 0.0
                blocked = side
                side = 0
        desired = int(sig[t - 1])
        if blocked != 0 and desired != blocked:
            blocked = 0
        # 2) trend flip: close at the open
        if units != 0.0 and desired != side:
            E -= abs(units) * o[t] * COST
            units = 0.0
            side = 0
        # 3) entry at the open
        if units == 0.0 and desired != 0 and desired != blocked:
            a_prev = atr[t - 1]
            if a_prev == a_prev and a_prev > 0:
                stop_dist = ATR_STOP * a_prev
                sc = score[t - 1] if score is not None else np.nan
                m = mult_for(desired, sc, ncomp, up, down)
                u = (RISK * m * E) / stop_dist
                u = min(u, LEV_CAP * E / o[t])
                units = desired * u
                side = desired
                stop = o[t] - desired * stop_dist
                E -= abs(units) * o[t] * COST
        # 4) intraday: stop or mark to close
        if units != 0.0:
            if side > 0 and l[t] <= stop:
                E += units * (stop - o[t])
                E -= abs(units) * stop * COST
                units = 0.0
                blocked = side
                side = 0
            elif side < 0 and h[t] >= stop:
                E += units * (stop - o[t])
                E -= abs(units) * stop * COST
                units = 0.0
                blocked = side
                side = 0
            else:
                E += units * (c[t] - o[t])
        if E <= 0.0:
            eq[t] = 0.0
            break
        eq[t] = E
    s = pd.Series(eq[i0:], index=idx[i0:])
    return s.fillna(0.0)


def period_stats(eq, start, end):
    res = {'cagr': np.nan, 'mar': np.nan, 'dd': np.nan, 'ret': np.nan}
    if eq is None:
        return res
    sub = eq[(eq.index >= start) & (eq.index <= end)]
    if len(sub) < 30:
        return res
    before = eq[eq.index < start]
    base = float(before.iloc[-1]) if len(before) else 1.0
    if base <= 0:
        return res
    path = sub.values / base
    days = max((sub.index[-1] - sub.index[0]).days + 1, 1)
    total = float(path[-1])
    cagr = (total ** (365.25 / days) - 1.0) if total > 0 else -1.0
    vals = np.concatenate(([1.0], path))
    peak = np.maximum.accumulate(vals)
    dd = float((vals / peak - 1.0).min())
    mar = cagr / abs(dd) if dd < 0 else np.nan
    return {'cagr': cagr * 100.0, 'mar': mar, 'dd': dd * 100.0, 'ret': (total - 1.0) * 100.0}


def year_returns(eq):
    if eq is None or len(eq) == 0:
        return pd.Series(dtype=float)
    last = eq.groupby(eq.index.year).last()
    prev = last.shift(1)
    prev.iloc[0] = 1.0
    return (last / prev - 1.0) * 100.0


def make_variants(avail):
    V = []
    V.append({'name': 'BASELINE (no score)', 'no_score': True, 'lens': {}, 'lag': BASE_LAG,
              'up': 1.0, 'down': 1.0, 'drop': set(), 'group': 'ref'})
    V.append({'name': 'M35 base', 'no_score': False, 'lens': {}, 'lag': BASE_LAG,
              'up': BASE_UP, 'down': BASE_DOWN, 'drop': set(), 'group': 'base'})
    for (cname, key, op, base_len) in COMPS:
        if cname not in avail:
            continue
        for f in [0.5, 1.5]:
            n = int(round(base_len * f))
            V.append({'name': 'sma ' + cname + ' x' + str(f) + ' (' + str(n) + ')', 'no_score': False,
                      'lens': {cname: n}, 'lag': BASE_LAG, 'up': BASE_UP, 'down': BASE_DOWN,
                      'drop': set(), 'group': 'neighbor'})
    for f in [0.5, 1.5]:
        lens = {}
        for (cname, key, op, base_len) in COMPS:
            if cname in avail:
                lens[cname] = int(round(base_len * f))
        V.append({'name': 'sma ALL x' + str(f), 'no_score': False, 'lens': lens, 'lag': BASE_LAG,
                  'up': BASE_UP, 'down': BASE_DOWN, 'drop': set(), 'group': 'neighbor'})
    for lg in [2, 3]:
        V.append({'name': 'lag ' + str(lg), 'no_score': False, 'lens': {}, 'lag': lg,
                  'up': BASE_UP, 'down': BASE_DOWN, 'drop': set(), 'group': 'neighbor'})
    for (up, down) in [(1.25, 0.75), (2.0, 0.5)]:
        V.append({'name': 'mult ' + str(up) + '/' + str(down), 'no_score': False, 'lens': {}, 'lag': BASE_LAG,
                  'up': up, 'down': down, 'drop': set(), 'group': 'neighbor'})
    for (cname, key, op, base_len) in COMPS:
        if cname not in avail:
            continue
        V.append({'name': 'drop ' + cname, 'no_score': False, 'lens': {}, 'lag': BASE_LAG,
                  'up': BASE_UP, 'down': BASE_DOWN, 'drop': set([cname]), 'group': 'drop'})
    return V


# ----------------------------------------------------------------- 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)
    if macro.get('copper') is not None and macro.get('gold') is not None:
        both = pd.concat([macro['copper'], macro['gold']], axis=1, join='inner')
        both.columns = ['cu', 'au']
        macro['cuau'] = both['cu'] / both['au']
    else:
        macro['cuau'] = None

    avail = [c[0] for c in COMPS if macro.get(c[1]) is not None]
    missing = [c[0] for c in COMPS if c[0] not in avail]
    if missing:
        print('WARNING: components without data: ' + ', '.join(missing))
    if len(avail) < 3:
        print('Too few macro components available. Stopping.')
        raise SystemExit

    prep = {'btc': prep_asset(btc_d), 'eth': prep_asset(eth_d) if eth_d is not None else None}
    variants = make_variants(avail)

    print('')
    print('Running ' + str(len(variants)) + ' variants on BTC' + (' and ETH' if eth_d is not None else '') + '...')
    stats = {}
    order = []
    for v in variants:
        name = v['name']
        order.append(name)
        entry = {'group': v['group']}
        for asset in ['btc', 'eth']:
            a = prep[asset]
            if a is None:
                entry[asset] = None
                continue
            if v['no_score']:
                score, ncomp = None, 0
            else:
                score, ncomp = build_score(a['idx'], macro, v['lens'], v['lag'], v['drop'])
            eq = backtest(a, score, ncomp, v['up'], v['down'])
            entry[asset] = eq
        end_b = btc_d.index[-1]
        entry['btc_full'] = period_stats(entry['btc'], START, end_b)
        entry['btc_h1'] = period_stats(entry['btc'], START, H1_END)
        entry['btc_h2'] = period_stats(entry['btc'], H2_START, end_b)
        if entry['eth'] is not None:
            end_e = eth_d.index[-1]
            entry['eth_full'] = period_stats(entry['eth'], START, end_e)
            entry['eth_h2'] = period_stats(entry['eth'], H2_START, end_e)
        else:
            entry['eth_full'] = period_stats(None, START, START)
            entry['eth_h2'] = period_stats(None, START, START)
        entry['yr_btc'] = year_returns(entry['btc'])
        entry['yr_eth'] = year_returns(entry['eth']) if entry['eth'] is not None else pd.Series(dtype=float)
        stats[name] = entry

    b0 = stats['BASELINE (no score)']
    base = stats['M35 base']

    # ---------------- table A
    rows = []
    for name in order:
        s = stats[name]
        rows.append({
            'variant': name,
            'CAGR%': fmt(s['btc_full']['cagr']), 'MAR': fmt(s['btc_full']['mar'], 2), 'DD%': fmt(s['btc_full']['dd']),
            'CAGR18-21': fmt(s['btc_h1']['cagr']), 'MAR18-21': fmt(s['btc_h1']['mar'], 2),
            'CAGR22-26': fmt(s['btc_h2']['cagr']), 'MAR22-26': fmt(s['btc_h2']['mar'], 2),
            'DD22-26': fmt(s['btc_h2']['dd']),
            'ETH_CAGR%': fmt(s['eth_full']['cagr']), 'ETH_MAR': fmt(s['eth_full']['mar'], 2),
            'ETH_DD%': fmt(s['eth_full']['dd']),
            'ETH_DD_vs_base': fmt(s['eth_full']['dd'] - b0['eth_full']['dd']),
        })
    pd.set_option('display.width', 300)
    pd.set_option('display.max_columns', 60)
    pd.set_option('display.max_rows', 200)
    print('')
    print('=' * 100)
    print('TABLE A: BTC stand-in strategy (EMA20/50, 2 ATR stop, 1% risk) with each M35 variant; ETH drawdown')
    print('ETH_DD_vs_base = ETH max drawdown minus the no-score baseline ETH max drawdown (negative = worse)')
    print('=' * 100)
    print(pd.DataFrame(rows).to_string(index=False))

    # ---------------- table B (per year)
    yr = {}
    for name in order:
        yr[name] = stats[name]['yr_btc']
    ydf = pd.DataFrame(yr).T
    ydf.columns = [str(c) for c in ydf.columns]
    print('')
    print('=' * 100)
    print('TABLE B: BTC return % per calendar year (2026 is partial)')
    print('=' * 100)
    print(ydf.round(1).to_string())

    if PRINT_ETH_YEARS and eth_d is not None:
        yre = {}
        for name in order:
            yre[name] = stats[name]['yr_eth']
        edf = pd.DataFrame(yre).T
        edf.columns = [str(c) for c in edf.columns]
        print('')
        print('=' * 100)
        print('TABLE C: ETH return % per calendar year (2026 is partial)')
        print('=' * 100)
        print(edf.round(1).to_string())

    # ---------------- checks
    print('')
    print('=' * 100)
    print('ROBUSTNESS CHECKS (M35 base vs no-score baseline, BTC unless noted)')
    print('=' * 100)
    checks = []

    c1 = gt(base['btc_h1']['mar'], b0['btc_h1']['mar']) and gt(base['btc_h2']['mar'], b0['btc_h2']['mar'])
    checks.append(('benefit in BOTH halves (MAR 2018-21 and 2022-26)', c1))
    print('1) MAR 2018-21: baseline ' + str(fmt(b0['btc_h1']['mar'], 2)) + ' -> M35 ' + str(fmt(base['btc_h1']['mar'], 2))
          + ' | MAR 2022-26: baseline ' + str(fmt(b0['btc_h2']['mar'], 2)) + ' -> M35 ' + str(fmt(base['btc_h2']['mar'], 2))
          + ' => ' + ('PASS' if c1 else 'FAIL'))

    neigh = [n for n in order if stats[n]['group'] == 'neighbor']
    beat_h2 = [gt(stats[n]['btc_h2']['mar'], b0['btc_h2']['mar']) for n in neigh]
    beat_full = [gt(stats[n]['btc_full']['mar'], b0['btc_full']['mar']) for n in neigh]
    share_h2 = float(np.mean(beat_h2)) if beat_h2 else 0.0
    share_full = float(np.mean(beat_full)) if beat_full else 0.0
    c2 = share_h2 >= 0.70 and share_full >= 0.70
    checks.append(('plateau: >=70% of SMA/lag/multiplier neighbors beat baseline MAR (2022-26 and full)', c2))
    nm = [stats[n]['btc_h2']['mar'] for n in neigh if not np.isnan(stats[n]['btc_h2']['mar'])]
    print('2) neighbors beating baseline MAR: 2022-26 ' + str(int(round(share_h2 * 100))) + '%, full '
          + str(int(round(share_full * 100))) + '% (' + str(len(neigh)) + ' neighbors). 2022-26 MAR base '
          + str(fmt(base['btc_h2']['mar'], 2)) + ' vs neighbors median '
          + (str(fmt(float(np.median(nm)), 2)) if nm else 'nan') + ' min '
          + (str(fmt(float(np.min(nm)), 2)) if nm else 'nan') + ' max '
          + (str(fmt(float(np.max(nm)), 2)) if nm else 'nan') + ' => ' + ('PASS' if c2 else 'FAIL'))

    drops = [n for n in order if stats[n]['group'] == 'drop']
    drop_ok = [gt(stats[n]['btc_h2']['mar'], b0['btc_h2']['mar']) for n in drops]
    c3 = len(drops) > 0 and all(drop_ok)
    checks.append(('no single-component dependence: every drop-one variant still beats baseline MAR 2022-26', c3))
    print('3) drop-one variants beating baseline MAR 2022-26: ' + str(int(sum(drop_ok))) + '/' + str(len(drops)) + ' => '
          + ('PASS' if c3 else 'FAIL'))

    yb = base['yr_btc']
    y0 = b0['yr_btc']
    yrs = [y for y in yb.index if y in y0.index]
    wins = [y for y in yrs if yb[y] > y0[y]]
    losses = [y for y in yrs if yb[y] <= y0[y]]
    frac = (len(wins) / len(yrs)) if yrs else 0.0
    c4 = frac >= 0.60
    checks.append(('year consistency: M35 beats baseline in >=60% of years', c4))
    print('4) M35 beats baseline in ' + str(len(wins)) + '/' + str(len(yrs)) + ' years. Worse in: '
          + (', '.join([str(y) for y in losses]) if losses else 'none') + ' => ' + ('PASS' if c4 else 'FAIL'))

    if eth_d is not None:
        d_eth = base['eth_full']['dd'] - b0['eth_full']['dd']
        c5 = (not np.isnan(d_eth)) and d_eth >= -2.0
        checks.append(('ETH max drawdown not worse than baseline by more than 2 points', c5))
        print('5) ETH max drawdown: baseline ' + str(fmt(b0['eth_full']['dd'])) + '% -> M35 ' + str(fmt(base['eth_full']['dd']))
              + '% (change ' + str(fmt(d_eth)) + ' pts) => ' + ('PASS' if c5 else 'FAIL'))
    else:
        print('5) ETH data missing, check skipped')

    passes = sum(1 for (_, ok) in checks if ok)
    total = len(checks)
    if passes >= total - 1:
        verdict = 'ROBUST'
    elif passes <= 1:
        verdict = 'FRAGILE'
    else:
        verdict = 'MIXED'

    best_name = None
    best_mar = -1e9
    for name in order:
        m = stats[name]['btc_h2']['mar']
        if not np.isnan(m) and m > best_mar:
            best_mar = m
            best_name = name
    top = sorted([(stats[n]['btc_h2']['mar'], n) for n in order if not np.isnan(stats[n]['btc_h2']['mar'])], reverse=True)[:3]
    print('')
    print('Top 3 by MAR 2022-26: ' + ', '.join([n + ' (' + str(fmt(m, 2)) + ')' for (m, n) in top]))
    print('')
    failed = [t for (t, ok) in checks if not ok]
    line = ('VERDICT: ' + verdict + ' (' + str(passes) + '/' + str(total) + ' checks passed'
            + ('; failed: ' + ' | '.join(failed) if failed else '') + ') | Best on 2022-26 by MAR: ' + str(best_name)
            + ' (MAR ' + str(fmt(best_mar, 2)) + ', CAGR ' + str(fmt(stats[best_name]['btc_h2']['cagr'])) + '%, M35 base MAR '
            + str(fmt(base['btc_h2']['mar'], 2)) + ')')
    print(line)


if __name__ == '__main__':
    main()
