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