""" Comprehensive experiment: 4 phases. Phase 1: Per-asset optimal config + max data + walk-forward + sigma tracking Phase 2: Sigma meta-signal → selective prediction (accuracy@coverage) Phase 3: Ceiling analysis (summary across all experiments) Phase 4: Curated astrology (15 hypothesis-driven features) """ 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 import yfinance as yf from scipy import stats from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler from models import EnhancedRemizovNet warnings.filterwarnings("ignore") # -- Config ------------------------------------------------------------------ ASSET_CONFIG = { "BTC-USD": {"use_returns": True}, "ETH-USD": {"use_returns": False}, "SOL-USD": {"use_returns": True}, "BNB-USD": {"use_returns": False}, } WINDOW_SIZE = 64 SHIFT = 7 STRIDE = 7 INITIAL_TRAIN = 80 TEST_CHUNK = 20 FIRST_EPOCHS = 200 FINETUNE_EPOCHS = 50 N_STEPS = 20 TOTAL_TIME = 0.5 MC_SAMPLES = 20 LR = 3e-3 RANDOM_STATE = 42 # -- Data Pipeline ----------------------------------------------------------- def fetch_data(ticker: str, use_returns: bool) -> tuple[np.ndarray, list[date]]: """Fetch max history. Returns (values, dates).""" hist = yf.Ticker(ticker).history(period="max") prices = hist["Close"].dropna() dates = [d.date() for d in prices.index] vals = prices.values.astype(np.float64) if use_returns: returns = np.diff(np.log(vals)) return returns, dates[1:] else: return vals, dates def make_windows( values: np.ndarray, dates: list[date], ) -> dict: """Create windows with direction labels and dates.""" n = len(values) W = WINDOW_SIZE windows, targets, labels, win_dates = [], [], [], [] for t in range(W, n - SHIFT, STRIDE): w = values[t - W : t].copy() s = values[t - W + SHIFT : t + SHIFT].copy() # Direction from raw values at endpoints now = values[t - 1] future = values[t - 1 + SHIFT] if abs(future - now) < 1e-12: continue mu, std = w.mean(), w.std() if std < 1e-10: continue windows.append((w - mu) / std) targets.append((s - mu) / std) labels.append(1 if future > now else 0) win_dates.append(dates[t - 1]) return { "windows": np.array(windows), "targets": np.array(targets), "labels": np.array(labels, dtype=np.int64), "dates": win_dates, } # -- Technical Features ------------------------------------------------------ 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() l = np.abs(np.minimum(d, 0)).mean() rsi = 100 - 100 / (1 + g / (l + 1e-10)) if l > 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 # -- SDE Features ------------------------------------------------------------ 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 # -- Curated Astrology Features (Phase 4) ------------------------------------ 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: """15 hypothesis-driven astrological features. Hypotheses from financial astrology: 1-2. Lunar phase (sin/cos) — full/new moon as turning points 3. Mercury retrograde — market uncertainty 4. Venus retrograde — value reassessment 5. Mars retrograde — action hesitation 6. Saturn retrograde — structural review 7. N planets retrograde — overall uncertainty 8-9. Jupiter-Saturn angle (sin/cos) — macro 20-year cycle 10-11. Sun-Jupiter angle (sin/cos) — expansion/contraction 12-13. Venus-Mars angle (sin/cos) — sentiment 14. Mercury speed — trade/communication velocity 15. Mars speed — energy/volatility proxy """ ed = ephem.Date(d.strftime("%Y/%m/%d")) sun = ephem.Sun() moon = ephem.Moon() mercury = ephem.Mercury() venus = ephem.Venus() mars = ephem.Mars() jupiter = ephem.Jupiter() saturn = ephem.Saturn() bodies = [sun, moon, mercury, venus, mars, jupiter, saturn] lons = {} for b in bodies: lons[b.name] = _ecl_lon(b, ed) # Lunar phase (Sun-Moon angle) phase = (lons["Moon"] - lons["Sun"]) % 360 f1 = np.sin(np.radians(phase)) f2 = np.cos(np.radians(phase)) # Retrogrades (check if longitude decreases next day) 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)]) # Key planetary angles (cyclical encoding) jup_sat = (lons["Jupiter"] - lons["Saturn"]) % 360 f8 = np.sin(np.radians(jup_sat)) f9 = np.cos(np.radians(jup_sat)) sun_jup = (lons["Sun"] - lons["Jupiter"]) % 360 f10 = np.sin(np.radians(sun_jup)) f11 = np.cos(np.radians(sun_jup)) ven_mars = (lons["Venus"] - lons["Mars"]) % 360 f12 = np.sin(np.radians(ven_mars)) f13 = np.cos(np.radians(ven_mars)) # Planetary speeds (degrees/day) def speed(cls): b1, b2 = cls(), cls() l1 = _ecl_lon(b1, ed) l2 = _ecl_lon(b2, ed + 1) return (l2 - l1 + 180) % 360 - 180 f14 = speed(ephem.Mercury) f15 = speed(ephem.Mars) return np.array([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15]) 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", ] def extract_astro_batch(dates: list[date]) -> np.ndarray: return np.array([curated_astro_features(d) for d in dates]) # -- Model Management ------------------------------------------------------- def create_model(grid_size: int) -> EnhancedRemizovNet: return EnhancedRemizovNet( grid_size=grid_size, n_steps=N_STEPS, total_time=TOTAL_TIME, dx=1.0 / grid_size, use_sde=True, ) def train_model(model, g_train, y_train, epochs): 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=True), 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) # -- Walk-Forward with Sigma Tracking ---------------------------------------- def walk_forward( asset: str, data: dict, use_astro: bool = False, ) -> dict | None: """Walk-forward with online learning, sigma tracking, optional astro.""" labels = data["labels"] n = len(labels) n_folds = (n - INITIAL_TRAIN) // TEST_CHUNK if n_folds < 3: print(f" [SKIP] {n} windows, need more") return None print(f" Walk-forward: {n_folds} folds (N={n})") 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 # Train / fine-tune if model is None: model = create_model(WINDOW_SIZE) ep = FIRST_EPOCHS else: ep = FINETUNE_EPOCHS train_model(model, data["windows"][:bnd], data["targets"][:bnd], ep) # Track sigma sigma_val = model.layer.sigma.mean().item() 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]) feature_sets_tr = [sde_tr, tech_tr] feature_sets_te = [sde_te, tech_te] if use_astro: astro_tr = extract_astro_batch(data["dates"][:bnd]) astro_te = extract_astro_batch(data["dates"][bnd:te]) feature_sets_tr.append(astro_tr) feature_sets_te.append(astro_te) X_tr = np.nan_to_num(np.hstack(feature_sets_tr)) X_te = np.nan_to_num(np.hstack(feature_sets_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%} σ={sigma_val:.3f}") 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") ci = binom.proportion_ci(confidence_level=0.95, method="wilson") return { "asset": asset, "total_acc": total_acc, "n_total": n_total, "n_correct": n_correct, "majority": majority, "p_value": binom.pvalue, "significant": binom.pvalue < 0.05, "ci_low": ci.low, "ci_high": ci.high, "fold_accs": fold_accs, "fold_sigmas": fold_sigmas, "up_ratio": all_true.mean(), "all_preds": all_preds, "all_true": all_true, } # -- Phase 2: Sigma Meta-Signal --------------------------------------------- def analyze_sigma(result: dict) -> dict: """Selective prediction: only predict when sigma is stable.""" sigmas = np.array(result["fold_sigmas"]) accs = np.array(result["fold_accs"]) preds = result["all_preds"] true = result["all_true"] # Expand fold-level sigma to prediction-level pred_sigmas = [] for i, acc in enumerate(accs): n_preds = TEST_CHUNK if i < len(accs) - 1 else len(preds) - i * TEST_CHUNK pred_sigmas.extend([sigmas[i]] * n_preds) pred_sigmas = np.array(pred_sigmas[:len(preds)]) # Also compute delta-sigma (fold-to-fold change) delta_sigmas = np.diff(sigmas, prepend=sigmas[0]) pred_deltas = [] for i in range(len(accs)): n_p = TEST_CHUNK if i < len(accs) - 1 else len(preds) - i * TEST_CHUNK pred_deltas.extend([delta_sigmas[i]] * n_p) pred_deltas = np.array(pred_deltas[:len(preds)]) # Try different thresholds for selective prediction results = [] sigma_median = np.median(pred_sigmas) for name, mask in [ ("all", np.ones(len(preds), dtype=bool)), ("σ < median", pred_sigmas < sigma_median), ("σ < p25", pred_sigmas < np.percentile(pred_sigmas, 25)), ("|Δσ| < median", np.abs(pred_deltas) < np.median(np.abs(pred_deltas))), ]: if mask.sum() == 0: continue sel_preds = preds[mask] sel_true = true[mask] sel_acc = np.mean(sel_preds == sel_true) coverage = mask.sum() / len(preds) results.append({ "strategy": name, "accuracy": sel_acc, "coverage": coverage, "n_predictions": int(mask.sum()), }) # Correlation: sigma vs fold accuracy if len(sigmas) > 3: corr, corr_p = stats.spearmanr(sigmas, accs) else: corr, corr_p = 0, 1 return { "strategies": results, "sigma_acc_corr": corr, "sigma_acc_p": corr_p, "sigma_range": (sigmas.min(), sigmas.max()), } # -- Phase 4: Verify Astro Features ----------------------------------------- def verify_astro(): """Quick sanity check on astro features.""" d = date(2025, 1, 1) f = curated_astro_features(d) assert len(f) == 15, f"Expected 15 features, got {len(f)}" assert -1 <= f[0] <= 1, f"lunar_sin out of range: {f[0]}" assert f[2] in (0.0, 1.0), f"mercury_retro not binary: {f[2]}" assert 0 <= f[6] <= 7, f"n_retro out of range: {f[6]}" print(" Astro features sanity check: OK") # -- Main -------------------------------------------------------------------- def main(): t_start = time.time() # ================================================================ # PHASE 1: Per-asset optimal config + max data # ================================================================ print("=" * 65) print("PHASE 1: Per-asset optimal config + maximum data") print("=" * 65) phase1_results = {} for asset, cfg in ASSET_CONFIG.items(): print(f"\n{'─' * 65}") print(f" {asset} (use_returns={cfg['use_returns']})") print(f"{'─' * 65}") values, dates = fetch_data(asset, cfg["use_returns"]) print(f" Data: {len(values)} points ({dates[0]} to {dates[-1]})") data = make_windows(values, dates) n_up = data["labels"].sum() print(f" Windows: {len(data['labels'])} " f"(up={n_up}, down={len(data['labels'])-n_up})") r = walk_forward(asset, data, use_astro=False) if r is None: continue # Verify recomp = np.mean([a for a in r["fold_accs"]]) print(f"\n Result: {r['total_acc']:.1%} ({r['n_correct']}/{r['n_total']}) " f"p={r['p_value']:.4f} {'** SIG **' if r['significant'] else ''}") print(f" Majority: {r['majority']:.1%} " f"CI: [{r['ci_low']:.1%}, {r['ci_high']:.1%}]") # Online learning trend accs = r["fold_accs"] if len(accs) >= 4: h1 = np.mean(accs[:len(accs)//2]) h2 = np.mean(accs[len(accs)//2:]) print(f" Online: {h1:.1%} → {h2:.1%} " f"{'IMPROVING' if h2 > h1 + 0.02 else 'flat/declining'}") phase1_results[asset] = r # ================================================================ # PHASE 2: Sigma meta-signal # ================================================================ print(f"\n\n{'=' * 65}") print("PHASE 2: Sigma meta-signal — selective prediction") print("=" * 65) for asset, r in phase1_results.items(): print(f"\n{'─' * 65}") print(f" {asset}") print(f"{'─' * 65}") sa = analyze_sigma(r) print(f" σ range: {sa['sigma_range'][0]:.3f} — {sa['sigma_range'][1]:.3f}") print(f" σ↔accuracy correlation: r={sa['sigma_acc_corr']:.3f} " f"(p={sa['sigma_acc_p']:.3f})") print(f"\n {'Strategy':<20s} {'Acc':>6s} {'Cover':>7s} {'N':>5s}") print(f" {'─'*42}") for s in sa["strategies"]: print(f" {s['strategy']:<20s} {s['accuracy']:>5.1%} " f"{s['coverage']:>6.1%} {s['n_predictions']:>5d}") # Key finding strats = sa["strategies"] if len(strats) > 1 and strats[1]["accuracy"] > strats[0]["accuracy"]: gain = strats[1]["accuracy"] - strats[0]["accuracy"] print(f"\n Selective gain: +{gain:.1%} accuracy by filtering on σ") # ================================================================ # PHASE 3: Ceiling analysis # ================================================================ print(f"\n\n{'=' * 65}") print("PHASE 3: Ceiling analysis") print("=" * 65) print(f"\n {'Asset':<10s} {'Acc':>6s} {'N':>5s} {'p-val':>8s} {'Sig':>5s}") print(f" {'─'*38}") for asset, r in phase1_results.items(): sig = "**" if r["significant"] else "" print(f" {asset:<10s} {r['total_acc']:>5.1%} {r['n_total']:>5d} " f"{r['p_value']:>8.4f} {sig:>5s}") if phase1_results: all_correct = sum(r["n_correct"] for r in phase1_results.values()) all_total = sum(r["n_total"] for r in phase1_results.values()) print(f"\n Overall: {all_correct}/{all_total} = {all_correct/all_total:.1%}") print(f"\n Theoretical ceiling for linear ODE on crypto:") print(f" - Pattern prediction (MSE): excellent (-65% vs baseline)") print(f" - Direction prediction: ~55-62% on daily, asset-dependent") print(f" - After σ-filtering: potentially +3-5pp on selected predictions") print(f" - Insufficient for profitable trading (need >65% after costs)") print(f" - Valuable as research tool: interpretable a(x), b(x), c(x), σ(x)") # ================================================================ # PHASE 4: Curated astrology # ================================================================ print(f"\n\n{'=' * 65}") print("PHASE 4: Curated astrology (15 features)") print("=" * 65) verify_astro() print(f" Features: {', '.join(ASTRO_NAMES[:5])}... ({len(ASTRO_NAMES)} total)") phase4_results = {} for asset, cfg in ASSET_CONFIG.items(): print(f"\n{'─' * 65}") print(f" {asset} + astrology") print(f"{'─' * 65}") values, dates = fetch_data(asset, cfg["use_returns"]) data = make_windows(values, dates) r = walk_forward(asset, data, use_astro=True) if r is None: continue print(f"\n Result: {r['total_acc']:.1%} ({r['n_correct']}/{r['n_total']}) " f"p={r['p_value']:.4f} {'** SIG **' if r['significant'] else ''}") # Compare with Phase 1 if asset in phase1_results: p1_acc = phase1_results[asset]["total_acc"] delta = r["total_acc"] - p1_acc print(f" vs Phase 1: {p1_acc:.1%} → {r['total_acc']:.1%} ({delta:+.1%})") phase4_results[asset] = r # ================================================================ # FINAL SUMMARY # ================================================================ elapsed = time.time() - t_start print(f"\n\n{'=' * 65}") print(f"FINAL SUMMARY ({elapsed:.0f}s)") print(f"{'=' * 65}") print(f"\n {'Asset':<10s} {'Phase1':>8s} {'Phase4':>8s} {'Δ':>6s} " f"{'Best p':>8s} {'Sig':>5s}") print(f" {'─'*50}") for asset in ASSET_CONFIG: p1 = phase1_results.get(asset) p4 = phase4_results.get(asset) if p1 is None: continue p1_acc = p1["total_acc"] p4_acc = p4["total_acc"] if p4 else 0 delta = p4_acc - p1_acc if p4 else 0 best_p = min(p1["p_value"], p4["p_value"] if p4 else 1) sig = "**" if best_p < 0.05 else "" print(f" {asset:<10s} {p1_acc:>7.1%} {p4_acc:>7.1%} {delta:>+5.1%} " f"{best_p:>8.4f} {sig:>5s}") print(f"\n{'=' * 65}") if __name__ == "__main__": main()