diff --git a/.gitignore b/.gitignore index 6c3a077..0b92919 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ __pycache__/ *.pyc .venv/ .DS_Store +logs/ diff --git a/astro_trade_analysis.py b/astro_trade_analysis.py new file mode 100644 index 0000000..b4e19be --- /dev/null +++ b/astro_trade_analysis.py @@ -0,0 +1,582 @@ +""" +Astrology-filtered shape confirmation strategy. + +1. Run shape confirmation backtest across all configs +2. Record every trade with 15 astro features +3. Find astro COMBINATIONS that predict winning trades +4. Validate on out-of-sample split +5. Final backtest with astro filter +""" + +from __future__ import annotations + +import time +import warnings +from datetime import date, timedelta +from itertools import combinations + +import numpy as np +import torch +import torch.nn as nn +from scipy import stats +from sklearn.tree import DecisionTreeClassifier + +from data_v2 import fetch_asset +from models import EnhancedRemizovNet +from retest_all import curated_astro_features + +warnings.filterwarnings("ignore") + +# -- Config ------------------------------------------------------------------ + +ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"] +WINDOW_SIZE = 64 +N_STEPS = 20 +TOTAL_TIME = 0.5 +EPOCHS = 200 +FINETUNE_EPOCHS = 50 +LR = 3e-3 +SHIFT = 7 + +INITIAL_EQUITY = 10000.0 +RISK_PER_TRADE = 0.02 +COMMISSION = 0.001 +STOP_MULT = 1.5 + +ASTRO_NAMES = [ + "lunar_sin", "lunar_cos", + "mercury_retro", "venus_retro", "mars_retro", "saturn_retro", "n_retro", + "jup_sat_sin", "jup_sat_cos", + "sun_jup_sin", "sun_jup_cos", + "ven_mars_sin", "ven_mars_cos", + "mercury_speed", "mars_speed", +] + +# Strategy configs to test +CONFIGS = [ + (2, 0.5), (2, 0.7), (2, 0.9), + (3, 0.5), (3, 0.7), (3, 0.9), +] + + +# -- Model ------------------------------------------------------------------- + +def create_model(): + return EnhancedRemizovNet( + grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME, + dx=1.0 / WINDOW_SIZE, use_sde=True, + ) + + +def train_model(model, windows, targets, epochs): + g = torch.tensor(windows, dtype=torch.float32) + y = torch.tensor(targets, dtype=torch.float32) + opt = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4) + crit = nn.MSELoss() + bs = min(64, len(windows)) + for _ in range(epochs): + model.train() + perm = torch.randperm(len(g)) + for i in range(0, len(g), bs): + idx = perm[i:i + bs] + opt.zero_grad() + loss = crit(model(g[idx], stochastic=True), y[idx]) + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + + +# -- Data -------------------------------------------------------------------- + +def prepare_data(prices): + n = len(prices) + data = [] + for t in range(WINDOW_SIZE, n - SHIFT, SHIFT): + w = prices[t - WINDOW_SIZE:t].copy() + future = prices[t:t + SHIFT].copy() + if len(future) < SHIFT: + continue + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + s = prices[t - WINDOW_SIZE + SHIFT:t + SHIFT].copy() + data.append({ + "price_at_entry": prices[t - 1], + "future_prices": future, + "norm_input": (w - mu) / std, + "norm_target": (s - mu) / std, + "mu": mu, "std": std, + }) + return data + + +# -- Shape Confirmation + Full Trade Recording ------------------------------- + +def run_full_backtest( + data: list[dict], + dates: list[date], + model, + confirm_days: int, + corr_threshold: float, + train_size: int = 80, +) -> list[dict]: + """Run backtest and return detailed trade list with astro features.""" + n = len(data) + if n < train_size + 5: + return [] + + windows = np.array([d["norm_input"] for d in data[:train_size]]) + targets = np.array([d["norm_target"] for d in data[:train_size]]) + train_model(model, windows, targets, EPOCHS) + + trades = [] + equity = INITIAL_EQUITY + retrain_ctr = 0 + + for i in range(train_size, n): + d = data[i] + + model.eval() + with torch.no_grad(): + inp = torch.tensor(d["norm_input"], dtype=torch.float32).unsqueeze(0) + pred = model(inp, stochastic=False).squeeze(0).numpy() + + # Shape confirmation + if confirm_days >= SHIFT: + continue + + pred_new = pred[-SHIFT:] + pred_confirm = pred_new[:confirm_days] + + if len(pred_confirm) < 2: + continue + + actual_norm = (d["future_prices"][:confirm_days] - d["mu"]) / d["std"] + corr = np.corrcoef(pred_confirm, actual_norm)[0, 1] + + if np.isnan(corr) or corr < corr_threshold: + retrain_ctr += 1 + if retrain_ctr >= 10: + ws = np.array([dd["norm_input"] for dd in data[:i + 1]]) + ts = np.array([dd["norm_target"] for dd in data[:i + 1]]) + train_model(model, ws, ts, FINETUNE_EPOCHS) + retrain_ctr = 0 + continue + + entry_price = d["future_prices"][confirm_days - 1] + pred_end_norm = pred_new[-1] + pred_at_confirm = pred_new[confirm_days - 1] + pred_direction = pred_end_norm - pred_at_confirm + + if abs(pred_direction) < 1e-10: + continue + + direction = 1 if pred_direction > 0 else -1 + pred_range = np.max(np.abs(pred_new[confirm_days:] - pred_at_confirm)) + stop_dist = max(pred_range * d["std"] * STOP_MULT, entry_price * 0.005) + + risk_amount = equity * RISK_PER_TRADE + pos_size = risk_amount / stop_dist + pos_value = pos_size * entry_price + if pos_value > equity: + pos_size = equity / entry_price + pos_value = equity + + exit_idx = SHIFT - 1 + exit_price = d["future_prices"][exit_idx] + stop_price = entry_price - direction * stop_dist + + stopped = False + for hp in d["future_prices"][confirm_days:exit_idx + 1]: + if direction == 1 and hp <= stop_price: + exit_price = stop_price + stopped = True + break + elif direction == -1 and hp >= stop_price: + exit_price = stop_price + stopped = True + break + + pnl_gross = pos_size * (exit_price - entry_price) * direction + commission_cost = pos_value * COMMISSION * 2 + pnl_net = pnl_gross - commission_cost + equity += pnl_net + + # Get trade date and astro features + # Approximate trade date from index + price_idx = WINDOW_SIZE + i * SHIFT + if price_idx < len(dates): + trade_date = dates[price_idx] + else: + trade_date = dates[-1] + + astro = curated_astro_features(trade_date) + + trades.append({ + "idx": i, + "date": trade_date, + "direction": direction, + "entry": entry_price, + "exit": exit_price, + "pnl_pct": (pnl_net / pos_value * 100) if pos_value > 0 else 0, + "pnl_net": pnl_net, + "win": pnl_net > 0, + "stopped": stopped, + "correlation": corr, + "equity": equity, + "astro": astro, + }) + + retrain_ctr += 1 + if retrain_ctr >= 10: + ws = np.array([dd["norm_input"] for dd in data[:i + 1]]) + ts = np.array([dd["norm_target"] for dd in data[:i + 1]]) + train_model(model, ws, ts, FINETUNE_EPOCHS) + retrain_ctr = 0 + + return trades + + +# -- Astro Pattern Mining ---------------------------------------------------- + +def discretize_astro(astro: np.ndarray) -> dict: + """Convert continuous astro features to discrete categories.""" + d = {} + + # Lunar phase quadrant + lunar_angle = np.degrees(np.arctan2(astro[0], astro[1])) % 360 + if lunar_angle < 90: + d["lunar_q"] = "new_wax" + elif lunar_angle < 180: + d["lunar_q"] = "wax_full" + elif lunar_angle < 270: + d["lunar_q"] = "full_wan" + else: + d["lunar_q"] = "wan_new" + + # Retrogrades (already binary) + d["merc_retro"] = astro[2] > 0.5 + d["venus_retro"] = astro[3] > 0.5 + d["mars_retro"] = astro[4] > 0.5 + d["saturn_retro"] = astro[5] > 0.5 + d["n_retro_high"] = astro[6] >= 3 # 3+ planets retrograde + + # Jupiter-Saturn angle quadrant + js_angle = np.degrees(np.arctan2(astro[7], astro[8])) % 360 + d["jup_sat_q"] = int(js_angle // 90) + + # Mercury speed (fast/slow/retrograde) + if astro[13] < -0.1: + d["merc_speed"] = "retro" + elif astro[13] < 0.8: + d["merc_speed"] = "slow" + else: + d["merc_speed"] = "fast" + + # Mars speed + if astro[14] < 0: + d["mars_speed"] = "retro" + elif astro[14] < 0.3: + d["mars_speed"] = "slow" + else: + d["mars_speed"] = "fast" + + return d + + +def find_astro_rules(trades: list[dict]) -> list[dict]: + """Find combinations of astro conditions that predict winning trades. + + Uses decision tree + manual rule mining. + """ + if len(trades) < 20: + return [] + + # Prepare feature matrix + X = np.array([t["astro"] for t in trades]) + y = np.array([1 if t["win"] else 0 for t in trades]) + + base_wr = y.mean() + + # Add discretized features + disc_features = [discretize_astro(t["astro"]) for t in trades] + + rules = [] + + # 1. Single feature thresholds + for j, name in enumerate(ASTRO_NAMES): + vals = X[:, j] + for q in [25, 50, 75]: + thresh = np.percentile(vals, q) + mask_hi = vals >= thresh + mask_lo = vals < thresh + + for mask, label in [(mask_hi, f"{name}>p{q}"), (mask_lo, f"{name} 0.08: + # Binomial test + binom = stats.binomtest(int(y[mask].sum()), n, base_wr) + rules.append({ + "rule": label, + "win_rate": wr, + "n_trades": n, + "coverage": n / len(trades), + "lift": wr - base_wr, + "p_value": binom.pvalue, + }) + + # 2. Discrete combinations (2-way) + disc_keys = list(disc_features[0].keys()) + for k1, k2 in combinations(disc_keys, 2): + # Get unique value combos + combos_seen = set() + for df in disc_features: + combos_seen.add((str(df[k1]), str(df[k2]))) + + for v1, v2 in combos_seen: + mask = np.array([ + str(disc_features[i][k1]) == v1 and str(disc_features[i][k2]) == v2 + for i in range(len(trades)) + ]) + if mask.sum() < 8: + continue + wr = y[mask].mean() + n = mask.sum() + if abs(wr - base_wr) > 0.10: + binom = stats.binomtest(int(y[mask].sum()), n, base_wr) + rules.append({ + "rule": f"{k1}={v1} & {k2}={v2}", + "win_rate": wr, + "n_trades": n, + "coverage": n / len(trades), + "lift": wr - base_wr, + "p_value": binom.pvalue, + }) + + # 3. Decision tree (finds multi-feature splits automatically) + if len(trades) > 30: + dt = DecisionTreeClassifier( + max_depth=3, min_samples_leaf=10, random_state=42, + ) + dt.fit(X, y) + dt_preds = dt.predict(X) + + # Extract leaf nodes where WR differs from base + leaves = dt.apply(X) + for leaf in np.unique(leaves): + mask = leaves == leaf + if mask.sum() < 8: + continue + wr = y[mask].mean() + if abs(wr - base_wr) > 0.10: + binom = stats.binomtest(int(y[mask].sum()), int(mask.sum()), base_wr) + rules.append({ + "rule": f"tree_leaf_{leaf}", + "win_rate": wr, + "n_trades": int(mask.sum()), + "coverage": mask.sum() / len(trades), + "lift": wr - base_wr, + "p_value": binom.pvalue, + }) + + # Sort by lift + rules.sort(key=lambda r: r["lift"], reverse=True) + return rules + + +# -- Out-of-Sample Validation ----------------------------------------------- + +def validate_rules(trades: list[dict], rules: list[dict]) -> list[dict]: + """Split trades in half, check if rules from first half work on second.""" + n = len(trades) + split = n // 2 + train_trades = trades[:split] + test_trades = trades[split:] + + if len(test_trades) < 15: + return [] + + X_test = np.array([t["astro"] for t in test_trades]) + y_test = np.array([1 if t["win"] else 0 for t in test_trades]) + base_wr_test = y_test.mean() + + disc_test = [discretize_astro(t["astro"]) for t in test_trades] + + validated = [] + for rule in rules: + rname = rule["rule"] + + # Reconstruct mask for test data + if rname.startswith("tree_leaf"): + continue # tree leaves don't transfer + + if " & " in rname: + # Combination rule + parts = rname.split(" & ") + k1, v1 = parts[0].split("=", 1) + k2, v2 = parts[1].split("=", 1) + mask = np.array([ + str(disc_test[i].get(k1)) == v1 and str(disc_test[i].get(k2)) == v2 + for i in range(len(test_trades)) + ]) + elif ">" in rname: + fname, pstr = rname.split(">") + j = ASTRO_NAMES.index(fname) + q = int(pstr[1:]) + thresh = np.percentile(X_test[:, j], q) + mask = X_test[:, j] >= thresh + elif "<" in rname: + fname, pstr = rname.split("<") + j = ASTRO_NAMES.index(fname) + q = int(pstr[1:]) + thresh = np.percentile(X_test[:, j], q) + mask = X_test[:, j] < thresh + else: + continue + + if mask.sum() < 5: + continue + + wr_test = y_test[mask].mean() + lift_test = wr_test - base_wr_test + + validated.append({ + **rule, + "wr_test": wr_test, + "lift_test": lift_test, + "n_test": int(mask.sum()), + "confirmed": lift_test > 0.05, + }) + + return validated + + +# -- Main -------------------------------------------------------------------- + +def main(): + t0 = time.time() + + print("=" * 75) + print("ASTRO-FILTERED SHAPE CONFIRMATION STRATEGY") + print("=" * 75) + + for asset in ASSETS: + time.sleep(2) + try: + prices, dates = fetch_asset(asset) + except Exception as e: + print(f"\n {asset}: FETCH ERROR ({e})") + continue + + data = prepare_data(prices) + print(f"\n{'=' * 75}") + print(f" {asset}: {len(data)} decisions ({dates[WINDOW_SIZE]}→{dates[-1]})") + print(f"{'=' * 75}") + + # Run best config for this asset + best_trades = None + best_equity = 0 + best_config = None + + for K, thresh in CONFIGS: + model = create_model() + trades = run_full_backtest(data, dates, model, K, thresh) + + if not trades: + continue + + final_eq = trades[-1]["equity"] if trades else INITIAL_EQUITY + n_trades = len(trades) + wins = sum(1 for t in trades if t["win"]) + wr = wins / n_trades if n_trades > 0 else 0 + ret = (final_eq / INITIAL_EQUITY - 1) * 100 + + print(f" K={K} corr>{thresh}: ${final_eq:>9,.0f} ({ret:>+6.1f}%) " + f"{n_trades} trades WR={wr:.0%}") + + if final_eq > best_equity: + best_equity = final_eq + best_trades = trades + best_config = (K, thresh) + + if not best_trades or len(best_trades) < 20: + print(f" [SKIP] Not enough trades for analysis") + continue + + K, thresh = best_config + n_trades = len(best_trades) + wins = sum(1 for t in best_trades if t["win"]) + base_wr = wins / n_trades + + print(f"\n BEST CONFIG: K={K} corr>{thresh}") + print(f" {n_trades} trades, WR={base_wr:.1%}") + + # ── Astro Pattern Mining ── + print(f"\n ASTRO PATTERN MINING (base WR={base_wr:.1%}):") + rules = find_astro_rules(best_trades) + + if not rules: + print(f" No significant astro patterns found") + continue + + # Top rules by lift + top_rules = [r for r in rules if r["p_value"] < 0.10][:15] + if top_rules: + print(f" {'Rule':<40s} {'WR':>5s} {'Lift':>6s} {'N':>4s} " + f"{'Cover':>6s} {'p':>7s}") + print(f" {'─' * 72}") + for r in top_rules: + sig = "**" if r["p_value"] < 0.05 else "" + print(f" {r['rule']:<40s} {r['win_rate']:>4.0%} " + f"{r['lift']:>+5.0%} {r['n_trades']:>4d} " + f"{r['coverage']:>5.0%} {r['p_value']:>7.4f} {sig}") + + # ── Out-of-Sample Validation ── + print(f"\n OUT-OF-SAMPLE VALIDATION (first half→second half):") + validated = validate_rules(best_trades, top_rules) + + confirmed = [v for v in validated if v["confirmed"]] + if confirmed: + print(f" {'Rule':<40s} {'Train':>5s} {'Test':>5s} {'N_test':>6s}") + print(f" {'─' * 60}") + for v in confirmed: + print(f" {v['rule']:<40s} {v['win_rate']:>4.0%} " + f"{v['wr_test']:>4.0%} {v['n_test']:>6d}") + else: + print(f" No rules confirmed out-of-sample") + + # ── Winning vs Losing Trade Astro Profile ── + print(f"\n ASTRO PROFILE: WINNERS vs LOSERS") + win_trades = [t for t in best_trades if t["win"]] + lose_trades = [t for t in best_trades if not t["win"]] + + if win_trades and lose_trades: + X_win = np.array([t["astro"] for t in win_trades]) + X_lose = np.array([t["astro"] for t in lose_trades]) + + print(f" {'Feature':<18s} {'Winners':>8s} {'Losers':>8s} " + f"{'Diff':>7s} {'p':>7s}") + print(f" {'─' * 52}") + + for j, name in enumerate(ASTRO_NAMES): + w_mean = X_win[:, j].mean() + l_mean = X_lose[:, j].mean() + diff = w_mean - l_mean + _, p = stats.mannwhitneyu( + X_win[:, j], X_lose[:, j], alternative="two-sided", + ) if len(X_win[:, j]) > 5 and len(X_lose[:, j]) > 5 else (0, 1) + sig = "**" if p < 0.05 else "" + print(f" {name:<18s} {w_mean:>+7.3f} {l_mean:>+7.3f} " + f"{diff:>+6.3f} {p:>7.3f} {sig}") + + elapsed = time.time() - t0 + print(f"\n\n{'=' * 75}") + print(f"COMPLETED in {elapsed:.0f}s") + print(f"{'=' * 75}") + + +if __name__ == "__main__": + main() diff --git a/data_v2.py b/data_v2.py new file mode 100644 index 0000000..630165b --- /dev/null +++ b/data_v2.py @@ -0,0 +1,101 @@ +""" +Corrected data pipeline v2. + +Key fix: direction labels ALWAYS computed from prices, +even when model inputs are log-returns. +""" + +from __future__ import annotations + +from datetime import date + +import numpy as np +import yfinance as yf + + +def fetch_asset(ticker: str, period: str = "max") -> tuple[np.ndarray, list[date]]: + """Fetch daily close prices and dates.""" + hist = yf.Ticker(ticker).history(period=period) + prices = hist["Close"].dropna() + dates = [d.date() for d in prices.index] + vals = prices.values.astype(np.float64) + return vals, dates + + +def make_windows( + prices: np.ndarray, + dates: list[date], + window_size: int = 64, + shift: int = 7, + stride: int = 7, + use_returns: bool = False, +) -> dict: + """Create windows with CORRECT direction labels. + + Labels are ALWAYS based on price comparison: + label = 1 if prices[t-1+shift] > prices[t-1] else 0 + + Model inputs can be either raw prices or log-returns, + controlled by use_returns flag. + """ + n = len(prices) + W = window_size + + # Compute log-returns if needed (for model input) + if use_returns: + values = np.diff(np.log(prices)) + # Dates shift by 1 (returns[i] corresponds to dates[i+1]) + val_dates = dates[1:] + # Need to map from value index back to price index: + # values[i] = log(prices[i+1]/prices[i]), so values index i + # corresponds to the transition from day i to day i+1. + # A window of values ending at index t covers transitions + # [t-W, t), meaning price days [t-W, t+1). + # The "current price" at decision point is prices[t] (in original indexing). + # Future price is prices[t + shift]. + else: + values = prices + val_dates = dates + + windows, targets, labels, win_dates = [], [], [], [] + + for t in range(W, len(values) - shift, stride): + w = values[t - W: t].copy() + s = values[t - W + shift: t + shift].copy() + + # Normalize model input + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + + # Direction label from PRICES (always correct) + if use_returns: + # values index t corresponds to price index t+1 + # "now" = price at end of input window = prices[t] + # "future" = prices[t + shift] + price_idx_now = t # in original prices array + price_idx_future = t + shift + if price_idx_future >= len(prices): + continue + price_now = prices[price_idx_now] + price_future = prices[price_idx_future] + else: + price_now = prices[t - 1] + price_future = prices[t - 1 + shift] + + if abs(price_future - price_now) < 1e-12: + continue + + label = 1 if price_future > price_now else 0 + + windows.append((w - mu) / std) + targets.append((s - mu) / std) + labels.append(label) + win_dates.append(val_dates[t - 1]) + + return { + "windows": np.array(windows), + "targets": np.array(targets), + "labels": np.array(labels, dtype=np.int64), + "dates": win_dates, + } diff --git a/final_backtest.py b/final_backtest.py new file mode 100644 index 0000000..985b136 --- /dev/null +++ b/final_backtest.py @@ -0,0 +1,555 @@ +""" +Final backtest: shape confirmation + astro filters + money management. + +Per-asset best configs from analysis: + BTC: K=2, corr>0.7, filter: lunar_q=wan_new & merc_speed=retro + ETH: K=2, corr>0.5, filter: n_retro>=3 & merc_speed=fast (best OOS: 65%, N=23) + BNB: K=3, corr>0.5, filter: mars_retro=True (best OOS: 71%, N=7) + SOL: K=3, corr>0.5, no astro filter (nothing confirmed OOS) + +Reports: annual returns, Sharpe, drawdown, monthly breakdown. +""" + +from __future__ import annotations + +import json +import os +import time +import warnings +from datetime import date, datetime, timedelta + +import numpy as np +import torch +import torch.nn as nn + +from data_v2 import fetch_asset +from models import EnhancedRemizovNet +from retest_all import curated_astro_features + +warnings.filterwarnings("ignore") + +# -- Config ------------------------------------------------------------------ + +WINDOW_SIZE = 64 +N_STEPS = 20 +TOTAL_TIME = 0.5 +EPOCHS = 200 +FINETUNE_EPOCHS = 50 +LR = 3e-3 +SHIFT = 7 + +INITIAL_EQUITY = 10000.0 +RISK_PER_TRADE = 0.02 +COMMISSION = 0.001 +STOP_MULT = 1.5 + +# Per-asset strategy configs +ASSET_CONFIGS = { + "BTC-USD": {"K": 2, "corr_thresh": 0.7, "astro_filter": "btc"}, + "ETH-USD": {"K": 2, "corr_thresh": 0.5, "astro_filter": "eth"}, + "SOL-USD": {"K": 3, "corr_thresh": 0.5, "astro_filter": None}, + "BNB-USD": {"K": 3, "corr_thresh": 0.5, "astro_filter": "bnb"}, +} + + +# -- Astro Filters ----------------------------------------------------------- + +def discretize_astro(astro: np.ndarray) -> dict: + lunar_angle = np.degrees(np.arctan2(astro[0], astro[1])) % 360 + if lunar_angle < 90: + lunar_q = "new_wax" + elif lunar_angle < 180: + lunar_q = "wax_full" + elif lunar_angle < 270: + lunar_q = "full_wan" + else: + lunar_q = "wan_new" + + merc_speed = astro[13] + if merc_speed < -0.1: + merc_cat = "retro" + elif merc_speed < 0.8: + merc_cat = "slow" + else: + merc_cat = "fast" + + return { + "lunar_q": lunar_q, + "merc_retro": astro[2] > 0.5, + "mars_retro": astro[4] > 0.5, + "saturn_retro": astro[5] > 0.5, + "n_retro": astro[6], + "merc_speed_cat": merc_cat, + } + + +def passes_astro_filter(trade_date: date, filter_name: str | None) -> bool: + if filter_name is None: + return True + + astro = curated_astro_features(trade_date) + d = discretize_astro(astro) + + if filter_name == "btc": + # lunar_q=wan_new & merc_speed=retro (train 75%, test 83%) + return d["lunar_q"] == "wan_new" and d["merc_speed_cat"] == "retro" + + elif filter_name == "eth": + # n_retro>=3 & merc_speed=fast (train 69%, test 65%, N=23) + return d["n_retro"] >= 3 and d["merc_speed_cat"] == "fast" + + elif filter_name == "bnb": + # mars_retro=True (p=0.026, confirmed OOS 71%) + return d["mars_retro"] + + return True + + +# -- Model ------------------------------------------------------------------- + +def create_model(): + return EnhancedRemizovNet( + grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME, + dx=1.0 / WINDOW_SIZE, use_sde=True, + ) + + +def train_model(model, windows, targets, epochs): + g = torch.tensor(windows, dtype=torch.float32) + y = torch.tensor(targets, dtype=torch.float32) + opt = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4) + crit = nn.MSELoss() + bs = min(64, len(windows)) + for _ in range(epochs): + model.train() + perm = torch.randperm(len(g)) + for i in range(0, len(g), bs): + idx = perm[i:i + bs] + opt.zero_grad() + loss = crit(model(g[idx], stochastic=True), y[idx]) + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + + +# -- Data -------------------------------------------------------------------- + +def prepare_data(prices): + data = [] + n = len(prices) + for t in range(WINDOW_SIZE, n - SHIFT, SHIFT): + w = prices[t - WINDOW_SIZE:t].copy() + future = prices[t:t + SHIFT].copy() + if len(future) < SHIFT: + continue + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + s = prices[t - WINDOW_SIZE + SHIFT:t + SHIFT].copy() + data.append({ + "price_at_entry": prices[t - 1], + "future_prices": future, + "norm_input": (w - mu) / std, + "norm_target": (s - mu) / std, + "mu": mu, "std": std, + "price_idx": t, + }) + return data + + +# -- Backtest ---------------------------------------------------------------- + +def run_backtest( + asset: str, + prices: np.ndarray, + dates: list[date], + data: list[dict], + cfg: dict, +) -> dict: + K = cfg["K"] + corr_thresh = cfg["corr_thresh"] + astro_filter = cfg["astro_filter"] + train_size = 80 + + n = len(data) + if n < train_size + 5: + return {"trades": [], "equity_curve": []} + + model = create_model() + windows = np.array([d["norm_input"] for d in data[:train_size]]) + targets = np.array([d["norm_target"] for d in data[:train_size]]) + train_model(model, windows, targets, EPOCHS) + + equity = INITIAL_EQUITY + trades = [] + equity_history = [(dates[WINDOW_SIZE + train_size * SHIFT] if WINDOW_SIZE + train_size * SHIFT < len(dates) else dates[-1], equity)] + retrain_ctr = 0 + astro_filtered = 0 + corr_filtered = 0 + total_signals = 0 + + for i in range(train_size, n): + d = data[i] + + model.eval() + with torch.no_grad(): + inp = torch.tensor(d["norm_input"], dtype=torch.float32).unsqueeze(0) + pred = model(inp, stochastic=False).squeeze(0).numpy() + + pred_new = pred[-SHIFT:] + pred_confirm = pred_new[:K] + + if len(pred_confirm) < 2: + continue + + actual_norm = (d["future_prices"][:K] - d["mu"]) / d["std"] + corr = np.corrcoef(pred_confirm, actual_norm)[0, 1] + + if np.isnan(corr) or corr < corr_thresh: + corr_filtered += 1 + retrain_ctr += 1 + if retrain_ctr >= 10: + ws = np.array([dd["norm_input"] for dd in data[:i + 1]]) + ts = np.array([dd["norm_target"] for dd in data[:i + 1]]) + train_model(model, ws, ts, FINETUNE_EPOCHS) + retrain_ctr = 0 + continue + + total_signals += 1 + + # Astro filter + pidx = d["price_idx"] + trade_date = dates[min(pidx, len(dates) - 1)] + + if not passes_astro_filter(trade_date, astro_filter): + astro_filtered += 1 + continue + + # Direction + entry_price = d["future_prices"][K - 1] + pred_direction = pred_new[-1] - pred_new[K - 1] + if abs(pred_direction) < 1e-10: + continue + + direction = 1 if pred_direction > 0 else -1 + pred_range = np.max(np.abs(pred_new[K:] - pred_new[K - 1])) + stop_dist = max(pred_range * d["std"] * STOP_MULT, entry_price * 0.005) + + risk_amount = equity * RISK_PER_TRADE + pos_size = risk_amount / stop_dist + pos_value = pos_size * entry_price + if pos_value > equity: + pos_size = equity / entry_price + pos_value = equity + + exit_price = d["future_prices"][-1] + stop_price = entry_price - direction * stop_dist + stopped = False + + for hp in d["future_prices"][K:]: + if direction == 1 and hp <= stop_price: + exit_price = stop_price; stopped = True; break + elif direction == -1 and hp >= stop_price: + exit_price = stop_price; stopped = True; break + + pnl_gross = pos_size * (exit_price - entry_price) * direction + commission_cost = pos_value * COMMISSION * 2 + pnl_net = pnl_gross - commission_cost + equity += pnl_net + + trades.append({ + "date": trade_date, + "direction": "L" if direction == 1 else "S", + "entry": entry_price, + "exit": exit_price, + "pnl_pct": pnl_net / pos_value * 100 if pos_value > 0 else 0, + "pnl_net": pnl_net, + "win": pnl_net > 0, + "stopped": stopped, + "equity": equity, + }) + equity_history.append((trade_date, equity)) + + retrain_ctr += 1 + if retrain_ctr >= 10: + ws = np.array([dd["norm_input"] for dd in data[:i + 1]]) + ts = np.array([dd["norm_target"] for dd in data[:i + 1]]) + train_model(model, ws, ts, FINETUNE_EPOCHS) + retrain_ctr = 0 + + return { + "trades": trades, + "equity_history": equity_history, + "total_signals": total_signals, + "corr_filtered": corr_filtered, + "astro_filtered": astro_filtered, + } + + +# -- Analysis ---------------------------------------------------------------- + +def analyze(asset: str, result: dict, prices: np.ndarray, dates: list[date]): + trades = result["trades"] + if not trades: + print(f" NO TRADES") + return + + # Basic stats + n = len(trades) + wins = [t for t in trades if t["win"]] + losses = [t for t in trades if not t["win"]] + pnls = [t["pnl_pct"] for t in trades] + final_eq = trades[-1]["equity"] + total_ret = (final_eq / INITIAL_EQUITY - 1) * 100 + + wr = len(wins) / n + avg_win = np.mean([t["pnl_pct"] for t in wins]) if wins else 0 + avg_loss = np.mean([t["pnl_pct"] for t in losses]) if losses else 0 + pf = abs(sum(t["pnl_pct"] for t in wins) / sum(t["pnl_pct"] for t in losses)) \ + if losses and sum(t["pnl_pct"] for t in losses) != 0 else float("inf") + + # Max drawdown + peak = INITIAL_EQUITY + max_dd = 0 + for t in trades: + peak = max(peak, t["equity"]) + dd = (t["equity"] - peak) / peak + max_dd = min(max_dd, dd) + + # Annual return + first_date = trades[0]["date"] + last_date = trades[-1]["date"] + years = (last_date - first_date).days / 365.25 + if years > 0: + annual_ret = ((final_eq / INITIAL_EQUITY) ** (1 / years) - 1) * 100 + else: + annual_ret = 0 + + # Sharpe (annualized from weekly returns) + weekly_rets = [t["pnl_pct"] / 100 for t in trades] + if len(weekly_rets) > 2 and np.std(weekly_rets) > 0: + sharpe = np.mean(weekly_rets) / np.std(weekly_rets) * np.sqrt(52) + else: + sharpe = 0 + + stopped = sum(1 for t in trades if t["stopped"]) + longs = sum(1 for t in trades if t["direction"] == "L") + + print(f" Period: {first_date} → {last_date} ({years:.1f} years)") + print(f" Equity: ${INITIAL_EQUITY:,.0f} → ${final_eq:,.0f} ({total_ret:+.1f}%)") + print(f" Annual return: {annual_ret:+.1f}%") + print(f" Sharpe ratio: {sharpe:.2f}") + print(f" Max drawdown: {max_dd:.1%}") + print(f" Trades: {n} (L={longs}, S={n - longs})") + print(f" Win rate: {wr:.0%} (avg win={avg_win:+.2f}%, avg loss={avg_loss:+.2f}%)") + print(f" Profit factor: {pf:.2f}") + print(f" Stopped out: {stopped}/{n} ({stopped/n:.0%})") + + # Filter stats + ts = result.get("total_signals", 0) + af = result.get("astro_filtered", 0) + print(f" Signals: {ts} total, {af} filtered by astro → {n} trades") + + # Buy-and-hold comparison + pidx_start = WINDOW_SIZE + 80 * SHIFT + if pidx_start < len(prices): + bh_ret = (prices[-1] / prices[pidx_start] - 1) * 100 + bh_annual = ((prices[-1] / prices[pidx_start]) ** (1 / years) - 1) * 100 if years > 0 else 0 + print(f" Buy&Hold: {bh_ret:+.1f}% total, {bh_annual:+.1f}%/year") + + # Yearly breakdown + print(f"\n YEARLY BREAKDOWN:") + print(f" {'Year':>6s} {'Trades':>7s} {'WR':>5s} {'Return':>8s} {'Equity':>10s}") + print(f" {'─' * 40}") + + yearly = {} + eq_start_year = INITIAL_EQUITY + for t in trades: + y = t["date"].year + if y not in yearly: + yearly[y] = {"trades": 0, "wins": 0, "pnl": 0.0, "eq_start": eq_start_year} + yearly[y]["trades"] += 1 + if t["win"]: + yearly[y]["wins"] += 1 + yearly[y]["pnl"] += t["pnl_net"] + yearly[y]["eq_end"] = t["equity"] + eq_start_year = t["equity"] + + for y in sorted(yearly): + yd = yearly[y] + yr_wr = yd["wins"] / yd["trades"] if yd["trades"] > 0 else 0 + yr_ret = yd["pnl"] / yd["eq_start"] * 100 if yd["eq_start"] > 0 else 0 + print(f" {y:>6d} {yd['trades']:>7d} {yr_wr:>4.0%} {yr_ret:>+7.1f}% " + f"${yd['eq_end']:>9,.0f}") + + # Monthly returns heatmap (simplified) + print(f"\n BEST/WORST MONTHS:") + monthly = {} + for t in trades: + key = f"{t['date'].year}-{t['date'].month:02d}" + if key not in monthly: + monthly[key] = 0.0 + monthly[key] += t["pnl_net"] + + if monthly: + sorted_months = sorted(monthly.items(), key=lambda x: x[1]) + for m, pnl in sorted_months[:3]: + print(f" Worst: {m} ${pnl:+,.0f}") + for m, pnl in sorted_months[-3:]: + print(f" Best: {m} ${pnl:+,.0f}") + + +# -- Main -------------------------------------------------------------------- + +def main(): + t0 = time.time() + + print("=" * 70) + print("FINAL BACKTEST: Shape + Astro Filters + Money Management") + print("=" * 70) + print(f" Capital: ${INITIAL_EQUITY:,.0f}") + print(f" Risk/trade: {RISK_PER_TRADE:.0%}, Commission: {COMMISSION:.1%}/side") + print(f" Stop: {STOP_MULT}x predicted range") + + print(f"\n ASTRO FILTERS:") + print(f" BTC: lunar wan_new + mercury retrograde") + print(f" ETH: 3+ planets retrograde + mercury fast") + print(f" BNB: Mars retrograde") + print(f" SOL: no filter") + + portfolio_equity = 0 + all_results = [] + + for asset, cfg in ASSET_CONFIGS.items(): + time.sleep(2) + try: + prices, dates = fetch_asset(asset) + except Exception as e: + print(f"\n {asset}: FETCH ERROR ({e})") + continue + + data = prepare_data(prices) + + print(f"\n{'=' * 70}") + print(f" {asset} (K={cfg['K']}, corr>{cfg['corr_thresh']}, " + f"astro={cfg['astro_filter'] or 'none'})") + print(f"{'=' * 70}") + + # Run WITH astro filter + print(f"\n WITH ASTRO FILTER:") + result_filtered = run_backtest(asset, prices, dates, data, cfg) + analyze(asset, result_filtered, prices, dates) + + # Run WITHOUT astro filter for comparison + print(f"\n WITHOUT ASTRO FILTER (comparison):") + cfg_no_astro = {**cfg, "astro_filter": None} + result_raw = run_backtest(asset, prices, dates, data, cfg_no_astro) + analyze(asset, result_raw, prices, dates) + + # Comparison + if result_filtered["trades"] and result_raw["trades"]: + eq_f = result_filtered["trades"][-1]["equity"] + eq_r = result_raw["trades"][-1]["equity"] + n_f = len(result_filtered["trades"]) + n_r = len(result_raw["trades"]) + print(f"\n FILTER IMPACT: ${eq_f:,.0f} vs ${eq_r:,.0f} " + f"(trades: {n_f} vs {n_r})") + if eq_f > eq_r: + print(f" Astro filter IMPROVES by ${eq_f - eq_r:,.0f}") + else: + print(f" Astro filter HURTS by ${eq_r - eq_f:,.0f}") + + if result_filtered["trades"]: + portfolio_equity += result_filtered["trades"][-1]["equity"] + else: + portfolio_equity += INITIAL_EQUITY + + # Collect for log + def _trade_summary(trades): + if not trades: + return {"n_trades": 0} + wins = [t for t in trades if t["win"]] + losses = [t for t in trades if not t["win"]] + return { + "n_trades": len(trades), + "wins": len(wins), + "losses": len(losses), + "win_rate": len(wins) / len(trades), + "final_equity": trades[-1]["equity"], + "total_return_pct": (trades[-1]["equity"] / INITIAL_EQUITY - 1) * 100, + "avg_win_pct": float(np.mean([t["pnl_pct"] for t in wins])) if wins else 0, + "avg_loss_pct": float(np.mean([t["pnl_pct"] for t in losses])) if losses else 0, + "max_loss_pct": float(min(t["pnl_pct"] for t in losses)) if losses else 0, + "stopped_out": sum(1 for t in trades if t["stopped"]), + "trades": [ + { + "date": str(t["date"]), + "direction": t["direction"], + "entry": round(t["entry"], 2), + "exit": round(t["exit"], 2), + "pnl_pct": round(t["pnl_pct"], 4), + "pnl_net": round(t["pnl_net"], 2), + "equity": round(t["equity"], 2), + "correlation": round(t["correlation"], 4), + "stopped": t["stopped"], + "win": t["win"], + } + for t in trades + ], + } + + all_results.append({ + "asset": asset, + "config": {**cfg}, + "with_astro": _trade_summary(result_filtered["trades"]), + "without_astro": _trade_summary(result_raw["trades"]), + }) + + # Portfolio summary + total_invested = INITIAL_EQUITY * len(ASSET_CONFIGS) + print(f"\n\n{'=' * 70}") + print(f"PORTFOLIO SUMMARY (equal-weight, 4 assets)") + print(f"{'=' * 70}") + print(f" Total invested: ${total_invested:,.0f}") + print(f" Final equity: ${portfolio_equity:,.0f}") + print(f" Total return: {(portfolio_equity / total_invested - 1) * 100:+.1f}%") + + elapsed = time.time() - t0 + print(f"\n Completed in {elapsed:.0f}s") + print(f"{'=' * 70}") + + save_log(all_results, elapsed) + + +def save_log(all_results: list[dict], elapsed: float): + """Save backtest results to logs/backtest_YYYYMMDD_HHMMSS.json.""" + os.makedirs("logs", exist_ok=True) + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + path = f"logs/backtest_{ts}.json" + + log = { + "timestamp": datetime.now().isoformat(), + "config": { + "initial_equity": INITIAL_EQUITY, + "risk_per_trade": RISK_PER_TRADE, + "commission": COMMISSION, + "stop_mult": STOP_MULT, + "window_size": WINDOW_SIZE, + "shift": SHIFT, + "epochs": EPOCHS, + "finetune_epochs": FINETUNE_EPOCHS, + }, + "asset_configs": {k: {**v} for k, v in ASSET_CONFIGS.items()}, + "elapsed_seconds": elapsed, + "results": all_results, + } + + with open(path, "w") as f: + json.dump(log, f, indent=2, default=str) + + print(f"\n Log saved: {path}") + return path + + +if __name__ == "__main__": + main() diff --git a/regime_analysis.py b/regime_analysis.py new file mode 100644 index 0000000..ef9d33a --- /dev/null +++ b/regime_analysis.py @@ -0,0 +1,390 @@ +""" +Regime analysis: when does the model profit vs fail? + +For each asset, run walk-forward and for every fold record: + - date range + - accuracy + - market regime (trend direction, volatility, drawdown) + - which predictions were right/wrong + +Then segment into "profitable" vs "losing" folds and find patterns. +""" + +from __future__ import annotations + +import warnings +from datetime import date + +import numpy as np +from scipy import stats +from sklearn.linear_model import LogisticRegression +from sklearn.preprocessing import StandardScaler + +from data_v2 import fetch_asset, make_windows +from retest_all import ( + create_model, train_model, extract_sde, extract_technical, + WINDOW_SIZE, SHIFT, STRIDE, N_STEPS, TOTAL_TIME, LR, + INITIAL_TRAIN, TEST_CHUNK, FIRST_EPOCHS, FINETUNE_EPOCHS, + MC_SAMPLES, RANDOM_STATE, +) + +warnings.filterwarnings("ignore") + +ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"] + + +def classify_regime( + prices: np.ndarray, + dates: list[date], + start_date: date, + end_date: date, +) -> dict: + """Classify market regime for a date range.""" + date_to_idx = {d: i for i, d in enumerate(dates)} + + # Find indices + si = None + for offset in range(5): + from datetime import timedelta + for sign in [0, -1, 1]: + candidate = start_date + timedelta(days=sign * offset) + si = date_to_idx.get(candidate) + if si is not None: + break + if si is not None: + break + + ei = None + for offset in range(5): + from datetime import timedelta + for sign in [0, 1, -1]: + candidate = end_date + timedelta(days=sign * offset) + ei = date_to_idx.get(candidate) + if ei is not None: + break + if ei is not None: + break + + if si is None or ei is None or ei <= si: + return {"trend": "unknown", "vol": 0, "return_pct": 0, "drawdown": 0} + + # Extend context: look at prices from 30 days before to end + ctx_start = max(0, si - 30) + p = prices[ctx_start:ei + 1] + p_fold = prices[si:ei + 1] + + if len(p_fold) < 2: + return {"trend": "unknown", "vol": 0, "return_pct": 0, "drawdown": 0} + + # Return over fold period + ret = (p_fold[-1] / p_fold[0] - 1) * 100 + + # Trend: linear regression slope + x = np.arange(len(p_fold)) + slope = np.polyfit(x, p_fold, 1)[0] + slope_pct = slope / p_fold.mean() * 100 # % per day + + # Volatility: annualized from daily returns + daily_ret = np.diff(np.log(p_fold)) + vol = daily_ret.std() * np.sqrt(365) * 100 if len(daily_ret) > 1 else 0 + + # Max drawdown in fold + cummax = np.maximum.accumulate(p_fold) + drawdowns = (p_fold - cummax) / cummax * 100 + max_dd = drawdowns.min() + + # Classify trend + if ret > 5: + trend = "BULL" + elif ret < -5: + trend = "BEAR" + else: + trend = "FLAT" + + # Volatility regime + if vol > 80: + vol_regime = "HIGH_VOL" + elif vol > 40: + vol_regime = "MED_VOL" + else: + vol_regime = "LOW_VOL" + + return { + "trend": trend, + "vol_regime": vol_regime, + "vol": vol, + "return_pct": ret, + "slope_pct": slope_pct, + "drawdown": max_dd, + } + + +def walk_forward_detailed( + asset: str, + prices: np.ndarray, + all_dates: list[date], + data: dict, +) -> list[dict]: + """Walk-forward with detailed per-fold analysis.""" + labels = data["labels"] + n = len(labels) + n_folds = (n - INITIAL_TRAIN) // TEST_CHUNK + + if n_folds < 3: + return [] + + model = None + folds = [] + + for fold in range(n_folds): + bnd = INITIAL_TRAIN + fold * TEST_CHUNK + te = min(bnd + TEST_CHUNK, n) + tl = labels[bnd:te] + if len(tl) == 0: + break + + # Dates for this fold + fold_dates = data["dates"][bnd:te] + fold_start = fold_dates[0] + fold_end = fold_dates[-1] + + # Train / fine-tune + if model is None: + model = create_model(WINDOW_SIZE, use_sde=True) + ep = FIRST_EPOCHS + else: + ep = FINETUNE_EPOCHS + + train_model(model, data["windows"][:bnd], data["targets"][:bnd], ep) + + sigma_val = model.layer.sigma.mean().item() + + # Features + sde_tr = extract_sde(model, data["windows"][:bnd]) + sde_te = extract_sde(model, data["windows"][bnd:te]) + tech_tr = extract_technical(data["windows"][:bnd]) + tech_te = extract_technical(data["windows"][bnd:te]) + + X_tr = np.nan_to_num(np.hstack([sde_tr, tech_tr])) + X_te = np.nan_to_num(np.hstack([sde_te, tech_te])) + + sc = StandardScaler() + Xtr = sc.fit_transform(X_tr) + Xte = sc.transform(X_te) + + clf = LogisticRegression( + penalty="l1", solver="saga", C=1.0, l1_ratio=1.0, + max_iter=2000, random_state=RANDOM_STATE, + ) + clf.fit(Xtr, labels[:bnd]) + preds = clf.predict(Xte) + proba = clf.predict_proba(Xte) + + acc = np.mean(preds == tl) + n_correct = int(np.sum(preds == tl)) + + # Confidence: mean probability of predicted class + confidence = np.mean(np.max(proba, axis=1)) + + # Market regime + regime = classify_regime(prices, all_dates, fold_start, fold_end) + + # Per-prediction details + pred_details = [] + for j in range(len(tl)): + pred_details.append({ + "date": fold_dates[j], + "pred": int(preds[j]), + "true": int(tl[j]), + "correct": bool(preds[j] == tl[j]), + "confidence": float(np.max(proba[j])), + }) + + folds.append({ + "fold": fold, + "start": fold_start, + "end": fold_end, + "acc": acc, + "n_correct": n_correct, + "n_total": len(tl), + "sigma": sigma_val, + "confidence": confidence, + "predictions": pred_details, + **regime, + }) + + return folds + + +def analyze_regimes(asset: str, folds: list[dict]): + """Analyze which regimes produce profits vs losses.""" + if not folds: + return + + print(f"\n{'=' * 75}") + print(f" {asset} — REGIME ANALYSIS") + print(f"{'=' * 75}") + + # ── Per-fold table ── + print(f"\n {'Fold':>4s} {'Dates':>25s} {'Acc':>5s} {'Trend':>5s} " + f"{'Ret%':>6s} {'Vol':>5s} {'DD%':>6s} {'Sigma':>6s} {'Conf':>5s}") + print(f" {'─' * 75}") + + for f in folds: + print(f" {f['fold']:>4d} {str(f['start'])}→{str(f['end'])} " + f"{f['acc']:>4.0%} {f['trend']:>5s} " + f"{f['return_pct']:>+5.1f} {f['vol']:>5.0f} " + f"{f['drawdown']:>+5.1f} {f['sigma']:>6.3f} {f['confidence']:>4.1%}") + + # ── Group by trend ── + print(f"\n BY TREND:") + for trend in ["BULL", "BEAR", "FLAT"]: + tf = [f for f in folds if f["trend"] == trend] + if not tf: + continue + avg_acc = np.mean([f["acc"] for f in tf]) + n_folds_t = len(tf) + total_correct = sum(f["n_correct"] for f in tf) + total_preds = sum(f["n_total"] for f in tf) + avg_ret = np.mean([f["return_pct"] for f in tf]) + print(f" {trend:<5s}: {avg_acc:.1%} acc ({total_correct}/{total_preds}) " + f"across {n_folds_t} folds, avg return={avg_ret:+.1f}%") + + # ── Group by volatility ── + print(f"\n BY VOLATILITY:") + for vol_r in ["LOW_VOL", "MED_VOL", "HIGH_VOL"]: + vf = [f for f in folds if f.get("vol_regime") == vol_r] + if not vf: + continue + avg_acc = np.mean([f["acc"] for f in vf]) + n_folds_v = len(vf) + avg_vol = np.mean([f["vol"] for f in vf]) + print(f" {vol_r:<8s}: {avg_acc:.1%} acc across {n_folds_v} folds " + f"(avg vol={avg_vol:.0f}%)") + + # ── Profitable vs losing folds ── + profitable = [f for f in folds if f["acc"] > 0.55] + losing = [f for f in folds if f["acc"] < 0.45] + neutral = [f for f in folds if 0.45 <= f["acc"] <= 0.55] + + print(f"\n PROFITABLE FOLDS (acc > 55%): {len(profitable)}/{len(folds)}") + if profitable: + p_trends = [f["trend"] for f in profitable] + p_vols = [f["vol"] for f in profitable] + p_sigmas = [f["sigma"] for f in profitable] + p_dds = [f["drawdown"] for f in profitable] + p_rets = [f["return_pct"] for f in profitable] + print(f" Trends: {dict((t, p_trends.count(t)) for t in set(p_trends))}") + print(f" Avg vol: {np.mean(p_vols):.0f}%, avg return: {np.mean(p_rets):+.1f}%") + print(f" Avg sigma: {np.mean(p_sigmas):.3f}, avg DD: {np.mean(p_dds):.1f}%") + + print(f"\n LOSING FOLDS (acc < 45%): {len(losing)}/{len(folds)}") + if losing: + l_trends = [f["trend"] for f in losing] + l_vols = [f["vol"] for f in losing] + l_sigmas = [f["sigma"] for f in losing] + l_dds = [f["drawdown"] for f in losing] + l_rets = [f["return_pct"] for f in losing] + print(f" Trends: {dict((t, l_trends.count(t)) for t in set(l_trends))}") + print(f" Avg vol: {np.mean(l_vols):.0f}%, avg return: {np.mean(l_rets):+.1f}%") + print(f" Avg sigma: {np.mean(l_sigmas):.3f}, avg DD: {np.mean(l_dds):.1f}%") + + print(f"\n NEUTRAL FOLDS (45-55%): {len(neutral)}/{len(folds)}") + + # ── Statistical tests: does regime predict accuracy? ── + print(f"\n REGIME-ACCURACY CORRELATIONS:") + accs = np.array([f["acc"] for f in folds]) + rets = np.array([f["return_pct"] for f in folds]) + vols = np.array([f["vol"] for f in folds]) + sigmas = np.array([f["sigma"] for f in folds]) + dds = np.array([f["drawdown"] for f in folds]) + confs = np.array([f["confidence"] for f in folds]) + + for name, vals in [ + ("return%", rets), ("volatility", vols), ("sigma", sigmas), + ("drawdown", dds), ("confidence", confs), + ]: + if len(vals) > 3 and vals.std() > 1e-10: + r, p = stats.spearmanr(vals, accs) + sig = "**" if p < 0.05 else "" + print(f" {name:<12s} r={r:+.3f} p={p:.3f} {sig}") + + # ── Consecutive streaks ── + print(f"\n PREDICTION STREAKS:") + all_preds = [] + for f in folds: + all_preds.extend(f["predictions"]) + + correct_streak, wrong_streak = 0, 0 + max_correct, max_wrong = 0, 0 + streaks_correct, streaks_wrong = [], [] + + for p in all_preds: + if p["correct"]: + correct_streak += 1 + if wrong_streak > 0: + streaks_wrong.append(wrong_streak) + max_wrong = max(max_wrong, wrong_streak) + wrong_streak = 0 + else: + wrong_streak += 1 + if correct_streak > 0: + streaks_correct.append(correct_streak) + max_correct = max(max_correct, correct_streak) + correct_streak = 0 + + if correct_streak > 0: + streaks_correct.append(correct_streak) + max_correct = max(max_correct, correct_streak) + if wrong_streak > 0: + streaks_wrong.append(wrong_streak) + max_wrong = max(max_wrong, wrong_streak) + + print(f" Max correct streak: {max_correct}") + print(f" Max wrong streak: {max_wrong}") + if streaks_correct: + print(f" Avg correct streak: {np.mean(streaks_correct):.1f}") + if streaks_wrong: + print(f" Avg wrong streak: {np.mean(streaks_wrong):.1f}") + + # ── Time evolution ── + print(f"\n ACCURACY OVER TIME (quarters):") + # Group by quarters + quarters = {} + for f in folds: + q = f"{f['start'].year}Q{(f['start'].month - 1) // 3 + 1}" + if q not in quarters: + quarters[q] = {"correct": 0, "total": 0} + quarters[q]["correct"] += f["n_correct"] + quarters[q]["total"] += f["n_total"] + + for q in sorted(quarters): + qd = quarters[q] + qacc = qd["correct"] / qd["total"] if qd["total"] > 0 else 0 + bar = "█" * int(qacc * 20) + "░" * (20 - int(qacc * 20)) + print(f" {q}: {bar} {qacc:.0%} ({qd['correct']}/{qd['total']})") + + +def main(): + for asset in ASSETS: + prices, dates = fetch_asset(asset) + data = make_windows(prices, dates, WINDOW_SIZE, SHIFT, STRIDE, use_returns=False) + n = len(data["labels"]) + n_up = data["labels"].sum() + print(f"\n {asset}: {n} windows (up={n_up}, down={n - n_up})") + + folds = walk_forward_detailed(asset, prices, dates, data) + analyze_regimes(asset, folds) + + # ── Cross-asset summary ── + print(f"\n\n{'=' * 75}") + print(f" CROSS-ASSET PATTERNS") + print(f"{'=' * 75}") + print(f"\n Key questions:") + print(f" 1. Is there a regime where ALL models profit?") + print(f" 2. Is there a regime where ALL models fail?") + print(f" 3. Can we filter trades by regime to improve results?") + + +if __name__ == "__main__": + main() diff --git a/retest_all.py b/retest_all.py new file mode 100644 index 0000000..1a0d9ea --- /dev/null +++ b/retest_all.py @@ -0,0 +1,608 @@ +""" +Full retest with corrected labels. + +Re-runs all experiment types from scratch: + Phase 1: Baseline RemizovNet MSE (BTC, prices) — sanity check + Phase 2: 6 enhanced variants (BTC, prices) — ablation + Phase 3: Walk-forward per asset (prices input) + Phase 4: Walk-forward per asset (returns input, CORRECT price labels) + Phase 5: Sigma meta-signal analysis + Phase 6: Curated astrology + +All direction labels computed from PRICES via data_v2. +""" + +from __future__ import annotations + +import math +import time +import warnings +from datetime import date + +import ephem +import numpy as np +import torch +import torch.nn as nn +from scipy import stats +from sklearn.linear_model import LogisticRegression +from sklearn.preprocessing import StandardScaler + +from data_v2 import fetch_asset, make_windows +from models import EnhancedRemizovNet, gbm_augment + +warnings.filterwarnings("ignore") + +# -- Config ------------------------------------------------------------------ + +ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"] +WINDOW_SIZE = 64 +SHIFT = 7 +STRIDE = 7 +INITIAL_TRAIN = 80 +TEST_CHUNK = 20 +FIRST_EPOCHS = 200 +FINETUNE_EPOCHS = 50 +ENHANCED_EPOCHS = 400 +N_STEPS = 20 +TOTAL_TIME = 0.5 +MC_SAMPLES = 20 +LR = 3e-3 +RANDOM_STATE = 42 + + +# -- Feature Extraction ------------------------------------------------------ + +def extract_technical(windows: np.ndarray) -> np.ndarray: + n = len(windows) + feats = np.zeros((n, 7)) + for i, w in enumerate(windows): + d = w[-14:] + g = np.maximum(d, 0).mean() + lo = np.abs(np.minimum(d, 0)).mean() + rsi = 100 - 100 / (1 + g / (lo + 1e-10)) if lo > 1e-10 else 50.0 + ma_cross = w[-7:].mean() - w[-21:].mean() + s20, st20 = w[-20:].mean(), w[-20:].std() + bb = (w[-1] - s20) / (2 * st20 + 1e-10) + vr = w[-7:].std() / (w.std() + 1e-10) + rs = (w[-1] - w.mean()) / (w.std() + 1e-10) + macd = w[-12:].mean() - w[-26:].mean() + cum = w[-10:].sum() + feats[i] = [rsi, ma_cross, bb, vr, rs, macd, cum] + return feats + + +def extract_sde(model: EnhancedRemizovNet, windows: np.ndarray) -> np.ndarray: + g = torch.tensor(windows, dtype=torch.float32) + model.eval() + preds = [] + for _ in range(MC_SAMPLES): + with torch.no_grad(): + preds.append(model(g, stochastic=True)) + preds = torch.stack(preds) + mp = preds.mean(0).numpy() + sp = preds.std(0).numpy() + n, W = windows.shape + feats = np.zeros((n, 6)) + for i in range(n): + d = mp[i] - windows[i] + feats[i, 0] = d.mean() + feats[i, 1] = d[-1] + feats[i, 2] = sp[i].mean() + feats[i, 3] = sp[i, -1] + feats[i, 4] = np.polyfit(np.arange(W), mp[i], 1)[0] + feats[i, 5] = mp[i, -1] - mp[i].mean() + return feats + + +# -- Model Helpers ----------------------------------------------------------- + +def create_model(grid_size: int, use_sde=True, use_fno=False, use_ssm=False): + return EnhancedRemizovNet( + grid_size=grid_size, n_steps=N_STEPS, total_time=TOTAL_TIME, + dx=1.0 / grid_size, use_sde=use_sde, use_fno=use_fno, use_ssm=use_ssm, + ) + + +def train_model(model, g_train, y_train, epochs, lr=LR): + g_t = torch.tensor(g_train, dtype=torch.float32) + y_t = torch.tensor(y_train, dtype=torch.float32) + opt = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=1e-4) + sch = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, patience=20, factor=0.5, min_lr=1e-5) + crit = nn.MSELoss() + bs = min(64, len(g_train)) + for _ in range(epochs): + model.train() + perm = torch.randperm(len(g_t)) + tl, nb = 0.0, 0 + for i in range(0, len(g_t), bs): + idx = perm[i:i + bs] + opt.zero_grad() + loss = crit(model(g_t[idx], stochastic=model.layer.use_sde), y_t[idx]) + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + tl += loss.item(); nb += 1 + sch.step(tl / nb) + return tl / nb + + +# -- Astrology --------------------------------------------------------------- + +def _ecl_lon(body, d): + body.compute(d) + return np.degrees(float(ephem.Ecliptic(body).lon)) % 360.0 + + +def curated_astro_features(d: date) -> np.ndarray: + ed = ephem.Date(d.strftime("%Y/%m/%d")) + bodies = { + "Sun": ephem.Sun(), "Moon": ephem.Moon(), + "Mercury": ephem.Mercury(), "Venus": ephem.Venus(), + "Mars": ephem.Mars(), "Jupiter": ephem.Jupiter(), + "Saturn": ephem.Saturn(), + } + lons = {name: _ecl_lon(b, ed) for name, b in bodies.items()} + + phase = (lons["Moon"] - lons["Sun"]) % 360 + f1 = np.sin(np.radians(phase)) + f2 = np.cos(np.radians(phase)) + + def is_retro(cls): + b1, b2 = cls(), cls() + l1 = _ecl_lon(b1, ed) + l2 = _ecl_lon(b2, ed + 1) + return float(((l2 - l1 + 180) % 360 - 180) < 0) + + f3 = is_retro(ephem.Mercury) + f4 = is_retro(ephem.Venus) + f5 = is_retro(ephem.Mars) + f6 = is_retro(ephem.Saturn) + f7 = sum([f3, f4, f5, f6, is_retro(ephem.Jupiter), + is_retro(ephem.Uranus), is_retro(ephem.Neptune)]) + + jup_sat = (lons["Jupiter"] - lons["Saturn"]) % 360 + f8, f9 = np.sin(np.radians(jup_sat)), np.cos(np.radians(jup_sat)) + sun_jup = (lons["Sun"] - lons["Jupiter"]) % 360 + f10, f11 = np.sin(np.radians(sun_jup)), np.cos(np.radians(sun_jup)) + ven_mars = (lons["Venus"] - lons["Mars"]) % 360 + f12, f13 = np.sin(np.radians(ven_mars)), np.cos(np.radians(ven_mars)) + + def speed(cls): + b1, b2 = cls(), cls() + return (((_ecl_lon(b2, ed + 1) - _ecl_lon(b1, ed)) + 180) % 360 - 180) + + f14, f15 = speed(ephem.Mercury), speed(ephem.Mars) + return np.array([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15]) + + +def extract_astro_batch(dates: list[date]) -> np.ndarray: + return np.array([curated_astro_features(d) for d in dates]) + + +# -- Walk-Forward Engine ----------------------------------------------------- + +def walk_forward( + data: dict, + use_sde: bool = True, + use_astro: bool = False, +) -> dict | None: + """Walk-forward with online learning and sigma tracking.""" + labels = data["labels"] + n = len(labels) + n_folds = (n - INITIAL_TRAIN) // TEST_CHUNK + + if n_folds < 3: + return None + + model = None + all_preds, all_true = [], [] + fold_sigmas, fold_accs = [], [] + + for fold in range(n_folds): + bnd = INITIAL_TRAIN + fold * TEST_CHUNK + te = min(bnd + TEST_CHUNK, n) + tl = labels[bnd:te] + if len(tl) == 0: + break + + if model is None: + model = create_model(WINDOW_SIZE, use_sde=use_sde) + ep = FIRST_EPOCHS + else: + ep = FINETUNE_EPOCHS + + train_model(model, data["windows"][:bnd], data["targets"][:bnd], ep) + + sigma_val = model.layer.sigma.mean().item() if use_sde else 0.0 + fold_sigmas.append(sigma_val) + + # Features + sde_tr = extract_sde(model, data["windows"][:bnd]) + sde_te = extract_sde(model, data["windows"][bnd:te]) + tech_tr = extract_technical(data["windows"][:bnd]) + tech_te = extract_technical(data["windows"][bnd:te]) + + parts_tr = [sde_tr, tech_tr] + parts_te = [sde_te, tech_te] + + if use_astro: + parts_tr.append(extract_astro_batch(data["dates"][:bnd])) + parts_te.append(extract_astro_batch(data["dates"][bnd:te])) + + X_tr = np.nan_to_num(np.hstack(parts_tr)) + X_te = np.nan_to_num(np.hstack(parts_te)) + + sc = StandardScaler() + Xtr = sc.fit_transform(X_tr) + Xte = sc.transform(X_te) + + clf = LogisticRegression( + penalty="l1", solver="saga", C=1.0, l1_ratio=1.0, + max_iter=2000, random_state=RANDOM_STATE, + ) + clf.fit(Xtr, labels[:bnd]) + preds = clf.predict(Xte) + + acc = np.mean(preds == tl) + all_preds.extend(preds.tolist()) + all_true.extend(tl.tolist()) + fold_accs.append(acc) + + if (fold + 1) % 5 == 0 or fold == n_folds - 1: + print(f" Fold {fold + 1}/{n_folds}: acc={acc:.0%}" + + (f" sigma={sigma_val:.3f}" if use_sde else "")) + + all_preds = np.array(all_preds) + all_true = np.array(all_true) + n_total = len(all_true) + n_correct = int(np.sum(all_preds == all_true)) + total_acc = n_correct / n_total + majority = max(all_true.mean(), 1 - all_true.mean()) + + binom = stats.binomtest(n_correct, n_total, majority, alternative="greater") + + return { + "total_acc": total_acc, + "n_total": n_total, + "n_correct": n_correct, + "majority": majority, + "p_value": binom.pvalue, + "significant": binom.pvalue < 0.05, + "fold_accs": fold_accs, + "fold_sigmas": fold_sigmas, + "all_preds": all_preds, + "all_true": all_true, + } + + +# -- Sigma Analysis ---------------------------------------------------------- + +def analyze_sigma(result: dict) -> list[dict]: + sigmas = np.array(result["fold_sigmas"]) + preds = result["all_preds"] + true = result["all_true"] + + pred_sigmas = [] + for i in range(len(result["fold_accs"])): + n_p = TEST_CHUNK if i < len(result["fold_accs"]) - 1 else len(preds) - i * TEST_CHUNK + pred_sigmas.extend([sigmas[i]] * n_p) + pred_sigmas = np.array(pred_sigmas[:len(preds)]) + + delta_sigmas = np.diff(sigmas, prepend=sigmas[0]) + pred_deltas = [] + for i in range(len(result["fold_accs"])): + n_p = TEST_CHUNK if i < len(result["fold_accs"]) - 1 else len(preds) - i * TEST_CHUNK + pred_deltas.extend([delta_sigmas[i]] * n_p) + pred_deltas = np.array(pred_deltas[:len(preds)]) + + strategies = [] + for name, mask in [ + ("all", np.ones(len(preds), dtype=bool)), + ("sigma < median", pred_sigmas < np.median(pred_sigmas)), + ("sigma < p25", pred_sigmas < np.percentile(pred_sigmas, 25)), + ("|d_sigma| < median", np.abs(pred_deltas) < np.median(np.abs(pred_deltas))), + ]: + if mask.sum() == 0: + continue + strategies.append({ + "name": name, + "acc": np.mean(preds[mask] == true[mask]), + "coverage": mask.sum() / len(preds), + "n": int(mask.sum()), + }) + return strategies + + +# -- Phase 1: Baseline MSE -------------------------------------------------- + +def phase1_baseline(): + print("=" * 65) + print("PHASE 1: Baseline RemizovNet MSE (BTC, prices)") + print("=" * 65) + + prices, dates = fetch_asset("BTC-USD", period="5y") + data = make_windows(prices, dates, WINDOW_SIZE, SHIFT, STRIDE, use_returns=False) + n = len(data["labels"]) + split = int(n * 0.8) + + model = create_model(WINDOW_SIZE, use_sde=False, use_fno=False, use_ssm=False) + g_tr = torch.tensor(data["windows"][:split], dtype=torch.float32) + y_tr = torch.tensor(data["targets"][:split], dtype=torch.float32) + g_te = torch.tensor(data["windows"][split:], dtype=torch.float32) + y_te = torch.tensor(data["targets"][split:], dtype=torch.float32) + + # Train + loss = train_model(model, data["windows"][:split], data["targets"][:split], ENHANCED_EPOCHS) + + # MSE eval + model.eval() + with torch.no_grad(): + pred = model(g_te, stochastic=False) + mse_model = nn.MSELoss()(pred, y_te).item() + mse_rw = nn.MSELoss()(g_te, y_te).item() # random walk baseline + + # Direction from normalized endpoints + true_dir = np.sign((y_te[:, -1] - g_te[:, -1]).numpy()) + pred_dir = np.sign((pred[:, -1] - g_te[:, -1]).numpy()) + mask = true_dir != 0 + dir_acc = np.mean(pred_dir[mask] == true_dir[mask]) if mask.sum() > 0 else 0.5 + always_up = np.mean(true_dir[mask] == 1) if mask.sum() > 0 else 0.5 + + print(f" MSE model: {mse_model:.6f}") + print(f" MSE RW: {mse_rw:.6f} ({(1 - mse_model/mse_rw)*100:+.1f}%)") + print(f" Dir acc: {dir_acc:.1%} (always-up: {always_up:.1%})") + print(f" Samples: train={split}, test={n - split}") + return {"mse_model": mse_model, "mse_rw": mse_rw, "dir_acc": dir_acc} + + +# -- Phase 2: Enhanced Variants (BTC, prices) -------------------------------- + +def phase2_variants(): + print(f"\n{'=' * 65}") + print("PHASE 2: Enhanced variants (BTC, prices, train/test split)") + print("=" * 65) + + prices, dates = fetch_asset("BTC-USD", period="5y") + data = make_windows(prices, dates, WINDOW_SIZE, SHIFT, STRIDE, use_returns=False) + n = len(data["labels"]) + split = int(n * 0.8) + labels_tr = data["labels"][:split] + labels_te = data["labels"][split:] + + VARIANTS = { + "A.Baseline": dict(use_ssm=False, use_fno=False, use_sde=False), + "B.+SDE": dict(use_ssm=False, use_fno=False, use_sde=True), + "C.+FNO": dict(use_ssm=False, use_fno=True, use_sde=False), + "D.+SSM": dict(use_ssm=True, use_fno=False, use_sde=False), + "E.Full": dict(use_ssm=True, use_fno=True, use_sde=True), + } + + results = [] + for name, flags in VARIANTS.items(): + model = EnhancedRemizovNet( + grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME, + dx=1.0 / WINDOW_SIZE, **flags, + ) + train_model(model, data["windows"][:split], data["targets"][:split], ENHANCED_EPOCHS) + + is_stoch = flags["use_sde"] + feat_tr = extract_sde(model, data["windows"][:split]) if is_stoch else extract_sde(model, data["windows"][:split]) + feat_te = extract_sde(model, data["windows"][split:]) + + # Add technical + tech_tr = extract_technical(data["windows"][:split]) + tech_te = extract_technical(data["windows"][split:]) + X_tr = np.nan_to_num(np.hstack([feat_tr, tech_tr])) + X_te = np.nan_to_num(np.hstack([feat_te, tech_te])) + + sc = StandardScaler() + Xtr = sc.fit_transform(X_tr) + Xte = sc.transform(X_te) + + clf = LogisticRegression(penalty="l1", solver="saga", C=1.0, l1_ratio=1.0, + max_iter=2000, random_state=RANDOM_STATE) + clf.fit(Xtr, labels_tr) + test_acc = clf.score(Xte, labels_te) + train_acc = clf.score(Xtr, labels_tr) + + majority = max(labels_te.mean(), 1 - labels_te.mean()) + n_te = len(labels_te) + n_correct = int(test_acc * n_te) + binom = stats.binomtest(n_correct, n_te, majority, alternative="greater") + + results.append({ + "name": name, "test_acc": test_acc, "train_acc": train_acc, + "majority": majority, "p_value": binom.pvalue, + "overfit": train_acc - test_acc, "params": model.param_count(), + }) + sig = "**" if binom.pvalue < 0.05 else "" + print(f" {name:<12s} test={test_acc:.1%} train={train_acc:.1%} " + f"maj={majority:.1%} p={binom.pvalue:.4f} {sig} " + f"ofit={train_acc - test_acc:+.1%} params={model.param_count()}") + + return results + + +# -- Phase 3 & 4: Walk-Forward Per Asset ------------------------------------ + +def phase3_4_walkforward(): + print(f"\n{'=' * 65}") + print("PHASE 3: Walk-forward per asset (prices input)") + print("PHASE 4: Walk-forward per asset (returns input, CORRECT labels)") + print("=" * 65) + + all_results = {} + + for asset in ASSETS: + prices, dates = fetch_asset(asset) + print(f"\n {asset}: {len(prices)} prices ({dates[0]} to {dates[-1]})") + + for use_ret in [False, True]: + input_type = "returns" if use_ret else "prices" + data = make_windows(prices, dates, WINDOW_SIZE, SHIFT, STRIDE, use_returns=use_ret) + n = len(data["labels"]) + n_up = data["labels"].sum() + key = f"{asset} ({input_type})" + print(f"\n --- {key}: {n} windows (up={n_up}, down={n - n_up}) ---") + + r = walk_forward(data, use_sde=True, use_astro=False) + if r is None: + print(f" [SKIP] too few windows") + continue + + sig = "** SIG **" if r["significant"] else "" + print(f" Result: {r['total_acc']:.1%} ({r['n_correct']}/{r['n_total']}) " + f"p={r['p_value']:.4f} {sig}") + print(f" Majority: {r['majority']:.1%}") + + accs = r["fold_accs"] + if len(accs) >= 4: + h1, h2 = np.mean(accs[:len(accs)//2]), np.mean(accs[len(accs)//2:]) + print(f" Online: {h1:.1%} -> {h2:.1%} " + f"{'IMPROVING' if h2 > h1 + 0.02 else 'flat/declining'}") + + all_results[key] = r + + return all_results + + +# -- Phase 5: Sigma Meta-Signal -------------------------------------------- + +def phase5_sigma(results: dict): + print(f"\n{'=' * 65}") + print("PHASE 5: Sigma meta-signal (selective prediction)") + print("=" * 65) + + for key, r in results.items(): + if not r.get("fold_sigmas") or all(s == 0 for s in r["fold_sigmas"]): + continue + strats = analyze_sigma(r) + print(f"\n {key}:") + print(f" {'Strategy':<22s} {'Acc':>6s} {'Cover':>7s} {'N':>5s}") + for s in strats: + print(f" {s['name']:<22s} {s['acc']:>5.1%} {s['coverage']:>6.1%} {s['n']:>5d}") + + +# -- Phase 6: Astrology ---------------------------------------------------- + +def phase6_astrology(): + print(f"\n{'=' * 65}") + print("PHASE 6: Curated astrology (15 features)") + print("=" * 65) + + results = {} + for asset in ASSETS: + prices, dates = fetch_asset(asset) + # Use prices input (simpler, no label-bug risk) + data = make_windows(prices, dates, WINDOW_SIZE, SHIFT, STRIDE, use_returns=False) + n = len(data["labels"]) + print(f"\n {asset}: {n} windows") + + r = walk_forward(data, use_sde=True, use_astro=True) + if r is None: + print(f" [SKIP]") + continue + + sig = "** SIG **" if r["significant"] else "" + print(f" Result: {r['total_acc']:.1%} ({r['n_correct']}/{r['n_total']}) " + f"p={r['p_value']:.4f} {sig}") + results[asset] = r + + return results + + +# -- Main -------------------------------------------------------------------- + +def main(): + t_start = time.time() + + # Phase 1 + p1 = phase1_baseline() + + # Phase 2 + p2 = phase2_variants() + + # Phase 3 & 4 + p34 = phase3_4_walkforward() + + # Phase 5 + phase5_sigma(p34) + + # Phase 6 + p6 = phase6_astrology() + + # ================================================================ + # FINAL SUMMARY + # ================================================================ + elapsed = time.time() - t_start + print(f"\n\n{'=' * 70}") + print(f"FINAL SUMMARY — CORRECTED LABELS ({elapsed:.0f}s)") + print(f"{'=' * 70}") + + print(f"\n Phase 1 — Baseline MSE:") + print(f" MSE improvement: {(1 - p1['mse_model']/p1['mse_rw'])*100:+.1f}% vs random walk") + print(f" Direction accuracy: {p1['dir_acc']:.1%}") + + print(f"\n Phase 2 — Enhanced Variants (BTC prices, train/test):") + print(f" {'Name':<12s} {'Test':>6s} {'p-val':>8s} {'Ofit':>6s}") + for r in p2: + sig = "**" if r["p_value"] < 0.05 else "" + print(f" {r['name']:<12s} {r['test_acc']:>5.1%} {r['p_value']:>8.4f} " + f"{r['overfit']:>+5.1%} {sig}") + + print(f"\n Phase 3+4 — Walk-Forward (all assets, both inputs):") + print(f" {'Config':<28s} {'Acc':>6s} {'N':>5s} {'p-val':>8s} {'Sig':>5s}") + print(f" {'─' * 55}") + for key, r in sorted(p34.items()): + sig = "**" if r["significant"] else "" + print(f" {key:<28s} {r['total_acc']:>5.1%} {r['n_total']:>5d} " + f"{r['p_value']:>8.4f} {sig:>5s}") + + if p6: + print(f"\n Phase 6 — Astrology (prices input):") + for asset, r in p6.items(): + # Compare with prices walk-forward + key_base = f"{asset} (prices)" + base_acc = p34[key_base]["total_acc"] if key_base in p34 else 0 + delta = r["total_acc"] - base_acc + sig = "**" if r["significant"] else "" + print(f" {asset:<10s} {r['total_acc']:>5.1%} (vs base {base_acc:.1%}, " + f"delta={delta:+.1%}) p={r['p_value']:.4f} {sig}") + + # Self-verification + print(f"\n SELF-VERIFICATION:") + + # Check for degenerate predictions + degenerate = [] + for key, r in p34.items(): + if len(set(r["all_preds"])) == 1: + degenerate.append(key) + print(f" Degenerate predictions: {degenerate if degenerate else 'None'}") + + # Check significant results are above majority + sig_results = [(k, r) for k, r in p34.items() if r["significant"]] + print(f" Significant results: {len(sig_results)}/{len(p34)}") + for k, r in sig_results: + print(f" {k}: {r['total_acc']:.1%} > majority {r['majority']:.1%}") + + # Check overfit in phase 2 + overfit_warn = [r["name"] for r in p2 if r["overfit"] > 0.20] + print(f" Phase 2 overfit >20%: {overfit_warn if overfit_warn else 'None'}") + + print(f"\n{'=' * 70}") + print(f" Key question: does BTC 75.8% survive label correction?") + btc_prices = p34.get("BTC-USD (prices)", {}).get("total_acc", 0) + btc_returns = p34.get("BTC-USD (returns)", {}).get("total_acc", 0) + print(f" BTC (prices): {btc_prices:.1%}") + print(f" BTC (returns): {btc_returns:.1%}") + if btc_returns > 0.60: + print(f" -> Returns result SURVIVES with correct labels") + elif btc_returns > 0.55: + print(f" -> Returns result weakened but still above chance") + else: + print(f" -> Returns result was ARTIFACT of wrong labels") + print(f"{'=' * 70}") + + +if __name__ == "__main__": + main() diff --git a/retest_isolated.py b/retest_isolated.py new file mode 100644 index 0000000..646fc56 --- /dev/null +++ b/retest_isolated.py @@ -0,0 +1,324 @@ +""" +Isolated feature tests with time lags. + +Phase A: Astrology only (no model, no technical) +Phase B: Technical only (no model, no astrology) +Phase C: Astrology with time lags (1-28 days) +Phase D: Technical with time lags (1-28 days) +Phase E: Best combo (astro lag + tech lag) + +All with walk-forward validation, correct price-based labels. +""" + +from __future__ import annotations + +import time +import warnings +from datetime import date, timedelta + +import numpy as np +from scipy import stats +from sklearn.linear_model import LogisticRegression +from sklearn.preprocessing import StandardScaler + +from data_v2 import fetch_asset, make_windows +from retest_all import curated_astro_features, extract_technical + +warnings.filterwarnings("ignore") + +# -- Config ------------------------------------------------------------------ + +ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"] +WINDOW_SIZE = 64 +SHIFT = 7 +STRIDE = 7 +INITIAL_TRAIN = 80 +TEST_CHUNK = 20 +RANDOM_STATE = 42 +LAGS = [0, 3, 7, 14, 21, 28] # days of lag to test + + +# -- Astro with lag ---------------------------------------------------------- + +def extract_astro_lagged(dates: list[date], lag_days: int = 0) -> np.ndarray: + """Extract astro features for dates shifted back by lag_days. + + lag=0: astro features for the decision date itself + lag=7: astro features from 7 days BEFORE the decision date + (hypothesis: planetary positions influence markets with delay) + """ + feats = [] + for d in dates: + shifted = d - timedelta(days=lag_days) + feats.append(curated_astro_features(shifted)) + return np.array(feats) + + +# -- Technical with lag ------------------------------------------------------ + +def extract_technical_lagged( + prices: np.ndarray, + dates: list[date], + win_dates: list[date], + lag_days: int = 0, +) -> np.ndarray: + """Extract technical indicators from price data lagged by lag_days. + + lag=0: technical features at decision point + lag=7: technical features from 7 days earlier + (hypothesis: delayed reaction to technical signals) + """ + # Build date->index mapping + date_to_idx = {d: i for i, d in enumerate(dates)} + + n = len(win_dates) + feats = np.zeros((n, 7)) + + for i, wd in enumerate(win_dates): + # Find the price index for this date - lag + target_date = wd - timedelta(days=lag_days) + + # Find nearest available date + idx = date_to_idx.get(target_date) + if idx is None: + # Search nearby dates (markets closed on weekends) + for offset in range(1, 5): + for sign in [-1, 1]: + candidate = target_date + timedelta(days=sign * offset) + idx = date_to_idx.get(candidate) + if idx is not None: + break + if idx is not None: + break + + if idx is None or idx < WINDOW_SIZE: + # Fallback: use zeros + continue + + # Extract window ending at idx + w = prices[idx - WINDOW_SIZE: idx].copy() + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + w = (w - mu) / std + + # Same 7 technical features + d = w[-14:] + g = np.maximum(d, 0).mean() + lo = np.abs(np.minimum(d, 0)).mean() + rsi = 100 - 100 / (1 + g / (lo + 1e-10)) if lo > 1e-10 else 50.0 + ma_cross = w[-7:].mean() - w[-21:].mean() + s20, st20 = w[-20:].mean(), w[-20:].std() + bb = (w[-1] - s20) / (2 * st20 + 1e-10) + vr = w[-7:].std() / (w.std() + 1e-10) + rs = (w[-1] - w.mean()) / (w.std() + 1e-10) + macd = w[-12:].mean() - w[-26:].mean() + cum = w[-10:].sum() + feats[i] = [rsi, ma_cross, bb, vr, rs, macd, cum] + + return feats + + +# -- Walk-Forward (generic) ------------------------------------------------- + +def walk_forward_features( + features: np.ndarray, + labels: np.ndarray, +) -> dict | None: + """Walk-forward using pre-computed features.""" + n = len(labels) + n_folds = (n - INITIAL_TRAIN) // TEST_CHUNK + + if n_folds < 3: + return None + + all_preds, all_true = [], [] + + for fold in range(n_folds): + bnd = INITIAL_TRAIN + fold * TEST_CHUNK + te = min(bnd + TEST_CHUNK, n) + tl = labels[bnd:te] + if len(tl) == 0: + break + + X_tr = np.nan_to_num(features[:bnd]) + X_te = np.nan_to_num(features[bnd:te]) + + sc = StandardScaler() + Xtr = sc.fit_transform(X_tr) + Xte = sc.transform(X_te) + + clf = LogisticRegression( + penalty="l1", solver="saga", C=1.0, l1_ratio=1.0, + max_iter=2000, random_state=RANDOM_STATE, + ) + clf.fit(Xtr, labels[:bnd]) + preds = clf.predict(Xte) + + all_preds.extend(preds.tolist()) + all_true.extend(tl.tolist()) + + all_preds = np.array(all_preds) + all_true = np.array(all_true) + n_total = len(all_true) + n_correct = int(np.sum(all_preds == all_true)) + total_acc = n_correct / n_total + majority = max(all_true.mean(), 1 - all_true.mean()) + + binom = stats.binomtest(n_correct, n_total, majority, alternative="greater") + + return { + "total_acc": total_acc, + "n_total": n_total, + "n_correct": n_correct, + "majority": majority, + "p_value": binom.pvalue, + "significant": binom.pvalue < 0.05, + } + + +# -- Main -------------------------------------------------------------------- + +def main(): + t_start = time.time() + + # Collect all results for final table + all_results = [] + + for asset in ASSETS: + prices, dates = fetch_asset(asset) + data = make_windows(prices, dates, WINDOW_SIZE, SHIFT, STRIDE, use_returns=False) + labels = data["labels"] + n = len(labels) + n_up = labels.sum() + + print(f"\n{'=' * 70}") + print(f" {asset}: {n} windows (up={n_up}, down={n - n_up})") + print(f"{'=' * 70}") + + # ── Phase A: Astrology only, different lags ── + + print(f"\n Phase A: ASTROLOGY ONLY") + print(f" {'Lag':>5s} {'Acc':>6s} {'N':>5s} {'p-val':>8s} {'Sig':>5s}") + print(f" {'─' * 35}") + + for lag in LAGS: + astro_feats = extract_astro_lagged(data["dates"], lag_days=lag) + r = walk_forward_features(astro_feats, labels) + if r is None: + print(f" {lag:>5d} [SKIP]") + continue + sig = "**" if r["significant"] else "" + print(f" {lag:>5d} {r['total_acc']:>5.1%} {r['n_total']:>5d} " + f"{r['p_value']:>8.4f} {sig:>5s}") + all_results.append({ + "asset": asset, "type": "astro", "lag": lag, **r, + }) + + # ── Phase B: Technical only, different lags ── + + print(f"\n Phase B: TECHNICAL ONLY") + print(f" {'Lag':>5s} {'Acc':>6s} {'N':>5s} {'p-val':>8s} {'Sig':>5s}") + print(f" {'─' * 35}") + + for lag in LAGS: + if lag == 0: + tech_feats = extract_technical(data["windows"]) + else: + tech_feats = extract_technical_lagged( + prices, dates, data["dates"], lag_days=lag, + ) + r = walk_forward_features(tech_feats, labels) + if r is None: + print(f" {lag:>5d} [SKIP]") + continue + sig = "**" if r["significant"] else "" + print(f" {lag:>5d} {r['total_acc']:>5.1%} {r['n_total']:>5d} " + f"{r['p_value']:>8.4f} {sig:>5s}") + all_results.append({ + "asset": asset, "type": "tech", "lag": lag, **r, + }) + + # ── Phase C: Astro + Tech at different lags ── + + print(f"\n Phase C: ASTRO + TECH (independent lags)") + print(f" {'A.lag':>5s} {'T.lag':>5s} {'Acc':>6s} {'N':>5s} " + f"{'p-val':>8s} {'Sig':>5s}") + print(f" {'─' * 42}") + + # Test key lag combinations + combos = [ + (0, 0), (7, 0), (14, 0), (0, 7), (0, 14), + (7, 7), (14, 7), (7, 14), (14, 14), (21, 7), + ] + + for a_lag, t_lag in combos: + astro_f = extract_astro_lagged(data["dates"], lag_days=a_lag) + if t_lag == 0: + tech_f = extract_technical(data["windows"]) + else: + tech_f = extract_technical_lagged( + prices, dates, data["dates"], lag_days=t_lag, + ) + combined = np.hstack([astro_f, tech_f]) + r = walk_forward_features(combined, labels) + if r is None: + print(f" {a_lag:>5d} {t_lag:>5d} [SKIP]") + continue + sig = "**" if r["significant"] else "" + print(f" {a_lag:>5d} {t_lag:>5d} {r['total_acc']:>5.1%} {r['n_total']:>5d} " + f"{r['p_value']:>8.4f} {sig:>5s}") + all_results.append({ + "asset": asset, "type": "combo", + "lag": f"a{a_lag}+t{t_lag}", **r, + }) + + # ================================================================ + # FINAL SUMMARY + # ================================================================ + elapsed = time.time() - t_start + print(f"\n\n{'=' * 70}") + print(f"FINAL SUMMARY — ISOLATED FEATURES + LAGS ({elapsed:.0f}s)") + print(f"{'=' * 70}") + + # Best per asset per type + for asset in ASSETS: + asset_results = [r for r in all_results if r["asset"] == asset] + if not asset_results: + continue + + print(f"\n {asset}:") + + for ftype in ["astro", "tech", "combo"]: + type_results = [r for r in asset_results if r["type"] == ftype] + if not type_results: + continue + best = max(type_results, key=lambda r: r["total_acc"]) + sig = "**" if best["significant"] else "" + print(f" Best {ftype:<6s}: {best['total_acc']:.1%} " + f"(lag={best['lag']}) p={best['p_value']:.4f} {sig}") + + # Significant results + sig_results = [r for r in all_results if r["significant"]] + print(f"\n Significant results (p<0.05): {len(sig_results)}/{len(all_results)}") + for r in sig_results: + print(f" {r['asset']} {r['type']} lag={r['lag']}: " + f"{r['total_acc']:.1%} p={r['p_value']:.4f}") + + if not sig_results: + print(" None — neither astrology nor technical indicators alone") + print(" predict price direction at any tested lag.") + + # Multiple testing correction + n_tests = len(all_results) + bonferroni = 0.05 / n_tests + print(f"\n Multiple testing: {n_tests} tests performed") + print(f" Bonferroni threshold: p < {bonferroni:.4f}") + bonf_sig = [r for r in all_results if r["p_value"] < bonferroni] + print(f" Survives Bonferroni: {len(bonf_sig)}") + + print(f"\n{'=' * 70}") + + +if __name__ == "__main__": + main() diff --git a/shape_confirm_backtest.py b/shape_confirm_backtest.py new file mode 100644 index 0000000..9d3936d --- /dev/null +++ b/shape_confirm_backtest.py @@ -0,0 +1,457 @@ +""" +Shape confirmation strategy with money management. + +Idea: + 1. Model predicts shape for next 7 days + 2. Wait K days, check if actual price follows predicted shape + 3. If correlation > threshold → open position in predicted direction + 4. Hold until end of prediction window (7-K days remaining) + +Money management: + - Fixed risk per trade (2% of equity) + - Stop-loss at max predicted deviation + - Position sizing based on stop distance + - Commission: 0.1% per trade (entry + exit) +""" + +from __future__ import annotations + +import warnings + +import numpy as np +import torch +import torch.nn as nn + +from data_v2 import fetch_asset + +warnings.filterwarnings("ignore") + +# -- Config ------------------------------------------------------------------ + +ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"] +WINDOW_SIZE = 64 +N_STEPS = 20 +TOTAL_TIME = 0.5 +EPOCHS = 200 +FINETUNE_EPOCHS = 50 +LR = 3e-3 + +# Strategy params +CONFIRM_DAYS = [1, 2, 3] # K: days to wait for confirmation +CORR_THRESHOLDS = [0.5, 0.7, 0.9] # minimum correlation to enter +SHIFT = 7 # prediction horizon + +# Money management +INITIAL_EQUITY = 10000.0 +RISK_PER_TRADE = 0.02 # 2% of equity risked per trade +COMMISSION = 0.001 # 0.1% per side (entry + exit = 0.2% total) +STOP_MULT = 1.5 # stop-loss at 1.5x predicted range + + +# -- Model ------------------------------------------------------------------- + +from models import EnhancedRemizovNet + + +def create_model(): + return EnhancedRemizovNet( + grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME, + dx=1.0 / WINDOW_SIZE, use_sde=True, + ) + + +def train_model(model, windows, targets, epochs): + g = torch.tensor(windows, dtype=torch.float32) + y = torch.tensor(targets, dtype=torch.float32) + opt = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4) + crit = nn.MSELoss() + bs = min(64, len(windows)) + for _ in range(epochs): + model.train() + perm = torch.randperm(len(g)) + for i in range(0, len(g), bs): + idx = perm[i:i + bs] + opt.zero_grad() + loss = crit(model(g[idx], stochastic=True), y[idx]) + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + + +# -- Data Preparation ------------------------------------------------------- + +def prepare_sequential_data(prices: np.ndarray) -> list[dict]: + """Create sequential prediction windows (no normalization overlap issues). + + Each entry: + - input_window: 64 prices ending at decision point + - future_prices: next 7 actual prices (for confirmation + PnL) + - norm_input: z-scored input window (for model) + - norm_target: z-scored target window (for training) + """ + n = len(prices) + data = [] + + for t in range(WINDOW_SIZE, n - SHIFT, SHIFT): # non-overlapping decisions + w = prices[t - WINDOW_SIZE:t].copy() + future = prices[t:t + SHIFT].copy() + + if len(future) < SHIFT: + continue + + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + + # Also need the shifted window for training + s = prices[t - WINDOW_SIZE + SHIFT:t + SHIFT].copy() + + data.append({ + "price_at_entry": prices[t - 1], + "future_prices": future, + "norm_input": (w - mu) / std, + "norm_target": (s - mu) / std, + "mu": mu, + "std": std, + }) + + return data + + +# -- Shape Confirmation Logic ----------------------------------------------- + +def check_shape_confirmation( + predicted_shape: np.ndarray, + actual_prices: np.ndarray, + mu: float, + std: float, + confirm_days: int, + corr_threshold: float, +) -> dict | None: + """Check if actual prices follow predicted shape for first K days. + + Returns trade signal or None. + """ + if confirm_days >= SHIFT: + return None + + # Predicted shape is normalized — convert actual prices to same normalization + actual_norm = (actual_prices[:confirm_days] - mu) / std + + # The predicted shape's corresponding segment + # predicted_shape is the full 64-point shifted window + # The "new" points are the last SHIFT points + pred_new = predicted_shape[-SHIFT:] + pred_confirm = pred_new[:confirm_days] + pred_remaining = pred_new[confirm_days:] + + if len(pred_confirm) < 2: + # Need at least 2 points for correlation + # Use simple sign agreement for K=1 + pred_dir = pred_confirm[0] - predicted_shape[-SHIFT - 1] + actual_dir = actual_norm[0] - (actual_prices[0] - mu) / std + # Not enough for correlation, skip + return None + + # Correlation between predicted and actual shape + corr = np.corrcoef(pred_confirm, actual_norm)[0, 1] + + if np.isnan(corr) or corr < corr_threshold: + return None + + # Direction: where does the predicted shape end relative to confirmation point? + entry_price = actual_prices[confirm_days - 1] + pred_end_norm = pred_new[-1] + pred_at_confirm_norm = pred_new[confirm_days - 1] + pred_direction = pred_end_norm - pred_at_confirm_norm + + if abs(pred_direction) < 1e-10: + return None + + # Convert predicted range to price space for stop-loss + pred_range_norm = np.max(np.abs(pred_remaining - pred_at_confirm_norm)) + pred_range_price = pred_range_norm * std + + direction = 1 if pred_direction > 0 else -1 + expected_move = pred_direction * std # in price units + + return { + "correlation": corr, + "direction": direction, + "entry_price": entry_price, + "expected_move": expected_move, + "stop_distance": max(pred_range_price * STOP_MULT, entry_price * 0.005), + "hold_days": SHIFT - confirm_days, + "confirm_day": confirm_days, + } + + +# -- Backtest Engine --------------------------------------------------------- + +def backtest_strategy( + data: list[dict], + model, + confirm_days: int, + corr_threshold: float, + train_size: int = 80, +) -> dict: + """Run backtest with online learning.""" + + equity = INITIAL_EQUITY + equity_curve = [equity] + trades = [] + n = len(data) + + if n < train_size + 5: + return {"equity": equity, "trades": [], "equity_curve": equity_curve} + + # Initial training + windows = np.array([d["norm_input"] for d in data[:train_size]]) + targets = np.array([d["norm_target"] for d in data[:train_size]]) + train_model(model, windows, targets, EPOCHS) + + retrain_counter = 0 + + for i in range(train_size, n): + d = data[i] + + # Predict shape + model.eval() + with torch.no_grad(): + inp = torch.tensor(d["norm_input"], dtype=torch.float32).unsqueeze(0) + pred = model(inp, stochastic=False).squeeze(0).numpy() + + # Check confirmation after K days + signal = check_shape_confirmation( + pred, d["future_prices"], d["mu"], d["std"], + confirm_days, corr_threshold, + ) + + if signal is not None: + # Position sizing: risk 2% of equity + stop_dist = signal["stop_distance"] + risk_amount = equity * RISK_PER_TRADE + position_size = risk_amount / stop_dist # number of units + position_value = position_size * signal["entry_price"] + + # Cap at 100% of equity (no leverage) + if position_value > equity: + position_size = equity / signal["entry_price"] + position_value = equity + + # Actual exit price (hold_days later) + exit_idx = signal["confirm_day"] + signal["hold_days"] - 1 + if exit_idx < len(d["future_prices"]): + exit_price = d["future_prices"][exit_idx] + else: + exit_price = d["future_prices"][-1] + + # Check stop-loss hit during holding period + hold_prices = d["future_prices"][signal["confirm_day"]:exit_idx + 1] + stopped = False + stop_price = signal["entry_price"] - signal["direction"] * stop_dist + + for hp in hold_prices: + if signal["direction"] == 1 and hp <= stop_price: + exit_price = stop_price + stopped = True + break + elif signal["direction"] == -1 and hp >= stop_price: + exit_price = stop_price + stopped = True + break + + # PnL + price_change = (exit_price - signal["entry_price"]) * signal["direction"] + pnl_gross = position_size * price_change + commission_cost = position_value * COMMISSION * 2 # entry + exit + pnl_net = pnl_gross - commission_cost + + equity += pnl_net + + trades.append({ + "idx": i, + "direction": "LONG" if signal["direction"] == 1 else "SHORT", + "entry": signal["entry_price"], + "exit": exit_price, + "pnl_pct": pnl_net / (position_value) * 100 if position_value > 0 else 0, + "pnl_abs": pnl_net, + "equity": equity, + "correlation": signal["correlation"], + "stopped": stopped, + }) + + equity_curve.append(equity) + + # Online fine-tune every 10 windows + retrain_counter += 1 + if retrain_counter >= 10: + windows = np.array([d["norm_input"] for d in data[:i + 1]]) + targets = np.array([d["norm_target"] for d in data[:i + 1]]) + train_model(model, windows, targets, FINETUNE_EPOCHS) + retrain_counter = 0 + + return { + "equity": equity, + "trades": trades, + "equity_curve": equity_curve, + } + + +# -- Analysis ---------------------------------------------------------------- + +def analyze_trades(trades: list[dict]) -> dict: + if not trades: + return {"n_trades": 0} + + pnls = [t["pnl_pct"] for t in trades] + wins = [p for p in pnls if p > 0] + losses = [p for p in pnls if p <= 0] + stopped = sum(1 for t in trades if t["stopped"]) + + win_rate = len(wins) / len(pnls) if pnls else 0 + avg_win = np.mean(wins) if wins else 0 + avg_loss = np.mean(losses) if losses else 0 + profit_factor = abs(sum(wins) / sum(losses)) if losses and sum(losses) != 0 else float("inf") + + # Max drawdown from equity curve + equities = [t["equity"] for t in trades] + if equities: + peak = equities[0] + max_dd = 0 + for e in equities: + peak = max(peak, e) + dd = (e - peak) / peak + max_dd = min(max_dd, dd) + else: + max_dd = 0 + + return { + "n_trades": len(trades), + "win_rate": win_rate, + "avg_win": avg_win, + "avg_loss": avg_loss, + "profit_factor": profit_factor, + "total_pnl": sum(pnls), + "max_drawdown": max_dd, + "stopped_out": stopped, + "long_trades": sum(1 for t in trades if t["direction"] == "LONG"), + "short_trades": sum(1 for t in trades if t["direction"] == "SHORT"), + } + + +# -- Main -------------------------------------------------------------------- + +def main(): + print("=" * 75) + print("SHAPE CONFIRMATION BACKTEST (with money management)") + print("=" * 75) + print(f" Initial equity: ${INITIAL_EQUITY:,.0f}") + print(f" Risk per trade: {RISK_PER_TRADE:.0%}") + print(f" Commission: {COMMISSION:.1%} per side") + print(f" Stop-loss: {STOP_MULT}x predicted range") + + all_results = [] + + for asset in ASSETS: + import time as _time + _time.sleep(2) # avoid yfinance rate limit + try: + prices, dates = fetch_asset(asset) + except Exception as e: + print(f"\n {asset}: FETCH ERROR ({e}), skipping") + continue + data = prepare_sequential_data(prices) + print(f"\n{'=' * 75}") + print(f" {asset}: {len(data)} decision points " + f"({dates[WINDOW_SIZE]} to {dates[-1]})") + print(f"{'=' * 75}") + + for K in CONFIRM_DAYS: + for thresh in CORR_THRESHOLDS: + model = create_model() + result = backtest_strategy(data, model, K, thresh) + stats = analyze_trades(result["trades"]) + + final_eq = result["equity"] + total_ret = (final_eq / INITIAL_EQUITY - 1) * 100 + + config = f"K={K} corr>{thresh}" + + if stats["n_trades"] == 0: + print(f" {config:<16s}: NO TRADES") + all_results.append({ + "asset": asset, "K": K, "thresh": thresh, + "n_trades": 0, "total_return": 0, + }) + continue + + print(f" {config:<16s}: " + f"${final_eq:>9,.0f} ({total_ret:>+6.1f}%) " + f"{stats['n_trades']:>3d} trades " + f"WR={stats['win_rate']:.0%} " + f"PF={stats['profit_factor']:.2f} " + f"DD={stats['max_drawdown']:.1%} " + f"stops={stats['stopped_out']}") + + all_results.append({ + "asset": asset, "K": K, "thresh": thresh, + "total_return": total_ret, **stats, + }) + + # ── Final Summary ── + print(f"\n\n{'=' * 75}") + print("FINAL SUMMARY") + print(f"{'=' * 75}") + + # Best per asset + for asset in ASSETS: + ar = [r for r in all_results if r["asset"] == asset and r["n_trades"] > 5] + if not ar: + print(f"\n {asset}: insufficient trades across all configs") + continue + + best = max(ar, key=lambda r: r["total_return"]) + worst = min(ar, key=lambda r: r["total_return"]) + + print(f"\n {asset}:") + print(f" Best: K={best['K']} corr>{best['thresh']}: " + f"{best['total_return']:+.1f}% " + f"({best['n_trades']} trades, WR={best['win_rate']:.0%})") + print(f" Worst: K={worst['K']} corr>{worst['thresh']}: " + f"{worst['total_return']:+.1f}% " + f"({worst['n_trades']} trades, WR={worst['win_rate']:.0%})") + + # Buy-and-hold comparison + print(f"\n BUY-AND-HOLD comparison:") + for asset in ASSETS: + try: + prices, _ = fetch_asset(asset) + except Exception: + continue + n_data = len(prepare_sequential_data(prices)) + train_start = min(80, n_data) + if train_start < len(prices) - SHIFT: + bh_start = prices[WINDOW_SIZE + train_start * SHIFT] + bh_end = prices[-1] + bh_ret = (bh_end / bh_start - 1) * 100 + print(f" {asset}: {bh_ret:+.1f}%") + + # Overall verdict + profitable = [r for r in all_results if r["n_trades"] > 5 and r["total_return"] > 0] + total_configs = [r for r in all_results if r["n_trades"] > 5] + + print(f"\n Profitable configs: {len(profitable)}/{len(total_configs)}") + + if not profitable: + print(" VERDICT: Shape confirmation does NOT produce profitable trades.") + print(" The predicted shape is too smooth/lagged to capture real moves.") + else: + avg_ret = np.mean([r["total_return"] for r in profitable]) + print(f" Avg profitable return: {avg_ret:+.1f}%") + + print(f"\n{'=' * 75}") + + +if __name__ == "__main__": + main()