""" Final experiment: SDE+Technical features with walk-forward validation. Each crypto asset (BTC, ETH, SOL, BNB) is treated as a separate entity with its own model, own walk-forward, own evaluation. Pipeline per asset: 1. Fetch daily prices 2. Create non-overlapping windows 3. Walk-forward validation: a. Train SDE-RemizovNet on train windows (MSE loss) b. MC inference → uncertainty features c. Extract technical features from raw windows d. Combined 13 features → LogReg → direction prediction 4. Aggregate all folds, binomial test, report """ from __future__ import annotations import math import time import warnings 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 ------------------------------------------------------------------ ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"] WINDOW_SIZE = 64 SHIFT = 7 STRIDE = 7 INITIAL_TRAIN = 100 # min samples before first test TEST_CHUNK = 25 # samples per walk-forward fold SDE_EPOCHS = 200 # epochs per fold (speed vs quality trade-off) N_STEPS = 20 TOTAL_TIME = 0.5 DX = 1.0 / WINDOW_SIZE MC_SAMPLES = 30 LR = 3e-3 RANDOM_STATE = 42 # -- Data Pipeline ----------------------------------------------------------- def fetch_prices(ticker: str, period: str = "5y") -> np.ndarray: """Fetch daily close prices for a ticker.""" t = yf.Ticker(ticker) hist = t.history(period=period) prices = hist["Close"].dropna().values.astype(np.float64) return prices def make_windows(prices: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Create non-overlapping windows with direction labels. Returns: (windows, shifted_windows, labels) — labels: 1=up, 0=down """ n = len(prices) max_start = n - WINDOW_SIZE - SHIFT windows, shifted, labels = [], [], [] for t in range(0, max_start, STRIDE): w = prices[t : t + WINDOW_SIZE].copy() s = prices[t + SHIFT : t + SHIFT + WINDOW_SIZE].copy() price_now = prices[t + WINDOW_SIZE - 1] price_future = prices[t + WINDOW_SIZE - 1 + SHIFT] if price_future == price_now: continue # Z-score normalize (using input window stats) mu, std = w.mean(), w.std() if std < 1e-10: continue windows.append((w - mu) / std) shifted.append((s - mu) / std) labels.append(1 if price_future > price_now else 0) return ( np.array(windows, dtype=np.float64), np.array(shifted, dtype=np.float64), np.array(labels, dtype=np.int64), ) # -- Feature Extraction ------------------------------------------------------ def extract_technical(windows: np.ndarray) -> np.ndarray: """7 technical features per window.""" n = len(windows) feats = np.zeros((n, 7)) for i, w in enumerate(windows): # RSI (14-period) deltas = np.diff(w[-15:]) gains = np.maximum(deltas, 0).mean() losses = np.abs(np.minimum(deltas, 0)).mean() rsi = 100 - 100 / (1 + gains / (losses + 1e-10)) if losses > 1e-10 else 50.0 # MA crossover: SMA7 - SMA21 ma_cross = w[-7:].mean() - w[-21:].mean() # Bollinger position sma20 = w[-20:].mean() std20 = w[-20:].std() bb_pos = (w[-1] - sma20) / (2 * std20 + 1e-10) # Volatility ratio: recent / historical vol_ratio = w[-7:].std() / (w.std() + 1e-10) # Price vs SMA rel_sma = (w[-1] - w.mean()) / (w.std() + 1e-10) # MACD-like macd = w[-12:].mean() - w[-26:].mean() # Rate of change roc = (w[-1] - w[-10]) / (abs(w[-10]) + 1e-10) feats[i] = [rsi, ma_cross, bb_pos, vol_ratio, rel_sma, macd, roc] return feats def extract_sde_features( model: EnhancedRemizovNet, windows: np.ndarray, ) -> np.ndarray: """6 SDE features via MC inference.""" 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) mean_p = preds.mean(0).numpy() std_p = preds.std(0).numpy() g_np = windows n = len(windows) feats = np.zeros((n, 6)) for i in range(n): diff = mean_p[i] - g_np[i] feats[i, 0] = diff.mean() # mean shift feats[i, 1] = diff[-1] # end shift feats[i, 2] = std_p[i].mean() # mean uncertainty feats[i, 3] = std_p[i, -1] # end uncertainty feats[i, 4] = np.polyfit(np.arange(WINDOW_SIZE), mean_p[i], 1)[0] # slope feats[i, 5] = mean_p[i, -1] - mean_p[i].mean() # momentum return feats # -- Train SDE Model --------------------------------------------------------- def train_sde_model( g_train: np.ndarray, y_train: np.ndarray, ) -> EnhancedRemizovNet: """Train SDE-enhanced RemizovNet on window pairs.""" model = EnhancedRemizovNet( grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME, dx=DX, use_ssm=False, use_fno=False, use_sde=True, ) g_t = torch.tensor(g_train, dtype=torch.float32) y_t = torch.tensor(y_train, dtype=torch.float32) optimizer = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, patience=30, factor=0.5, min_lr=1e-5, ) criterion = nn.MSELoss() batch_size = min(64, len(g_train)) for epoch in range(SDE_EPOCHS): model.train() perm = torch.randperm(len(g_t)) total_loss = 0.0 nb = 0 for i in range(0, len(g_t), batch_size): idx = perm[i : i + batch_size] optimizer.zero_grad() loss = criterion(model(g_t[idx], stochastic=True), y_t[idx]) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() total_loss += loss.item() nb += 1 scheduler.step(total_loss / nb) return model # -- Walk-Forward Validation ------------------------------------------------- def walk_forward_single_asset( asset: str, windows: np.ndarray, shifted: np.ndarray, labels: np.ndarray, ) -> dict: """Walk-forward validation for a single asset.""" n = len(windows) n_folds = (n - INITIAL_TRAIN) // TEST_CHUNK if n_folds < 2: print(f" [SKIP] Not enough data: {n} windows, need >{INITIAL_TRAIN + 2*TEST_CHUNK}") return None all_preds = [] all_true = [] fold_results = [] print(f" Walk-forward: {n_folds} folds, " f"initial_train={INITIAL_TRAIN}, test_chunk={TEST_CHUNK}") for fold in range(n_folds): train_end = INITIAL_TRAIN + fold * TEST_CHUNK test_end = min(train_end + TEST_CHUNK, n) w_train = windows[:train_end] s_train = shifted[:train_end] l_train = labels[:train_end] w_test = windows[train_end:test_end] l_test = labels[train_end:test_end] if len(w_test) == 0: break # 1. Train SDE model on this fold's training data model = train_sde_model(w_train, s_train) # 2. Extract features sde_train = extract_sde_features(model, w_train) sde_test = extract_sde_features(model, w_test) tech_train = extract_technical(w_train) tech_test = extract_technical(w_test) X_train = np.hstack([sde_train, tech_train]) X_test = np.hstack([sde_test, tech_test]) # Handle NaN/Inf X_train = np.nan_to_num(X_train, nan=0.0, posinf=0.0, neginf=0.0) X_test = np.nan_to_num(X_test, nan=0.0, posinf=0.0, neginf=0.0) # 3. Train classifier scaler = StandardScaler() Xtr = scaler.fit_transform(X_train) Xte = scaler.transform(X_test) clf = LogisticRegression( penalty="l1", solver="saga", C=1.0, l1_ratio=1.0, max_iter=2000, random_state=RANDOM_STATE, ) clf.fit(Xtr, l_train) # 4. Predict preds = clf.predict(Xte) fold_acc = np.mean(preds == l_test) all_preds.extend(preds.tolist()) all_true.extend(l_test.tolist()) fold_results.append({ "fold": fold + 1, "train_size": train_end, "test_size": len(w_test), "accuracy": fold_acc, "up_ratio": l_test.mean(), }) eq = model.equation_string(precision=3) print(f" Fold {fold+1}/{n_folds}: train={train_end} test={len(w_test)} " f"acc={fold_acc:.1%} {eq}") if not all_preds: return None all_preds = np.array(all_preds) all_true = np.array(all_true) # Aggregate metrics total_acc = np.mean(all_preds == all_true) n_total = len(all_true) n_correct = int(total_acc * n_total) majority = max(all_true.mean(), 1 - all_true.mean()) # Binomial test binom = stats.binomtest(n_correct, n_total, majority, alternative="greater") p_val = binom.pvalue # Confidence interval (Wilson score) ci = binom.proportion_ci(confidence_level=0.95, method="wilson") result = { "asset": asset, "total_acc": total_acc, "n_total": n_total, "n_correct": n_correct, "majority": majority, "beats_majority": total_acc > majority, "p_value": p_val, "significant": p_val < 0.05, "ci_low": ci.low, "ci_high": ci.high, "n_folds": len(fold_results), "folds": fold_results, "up_ratio": all_true.mean(), } return result # -- Self-Verification ------------------------------------------------------- def verify_result(r: dict) -> None: """Self-verification protocol for walk-forward results.""" print(f"\n {'─' * 50}") print(f" VERIFICATION: {r['asset']}") print(f" {'─' * 50}") # 1. Accuracy computation check expected_correct = sum( f["accuracy"] * f["test_size"] for f in r["folds"] ) expected_total = sum(f["test_size"] for f in r["folds"]) recomputed_acc = expected_correct / expected_total acc_match = abs(recomputed_acc - r["total_acc"]) < 0.02 print(f" Accuracy recompute: {recomputed_acc:.3f} vs {r['total_acc']:.3f} " f"{'OK' if acc_match else 'MISMATCH'}") # 2. Class balance check print(f" Class balance: {r['up_ratio']:.1%} up / {1-r['up_ratio']:.1%} down") if abs(r["up_ratio"] - 0.5) > 0.3: print(f" [WARN] Severe class imbalance — majority baseline is strong") # 3. Fold consistency fold_accs = [f["accuracy"] for f in r["folds"]] fold_std = np.std(fold_accs) if len(fold_accs) > 1 else 0 print(f" Fold accuracy range: {min(fold_accs):.1%} — {max(fold_accs):.1%} " f"(std={fold_std:.1%})") if fold_std > 0.25: print(f" [WARN] High variance across folds — result is unstable") # 4. Significance print(f" Binomial test: p={r['p_value']:.4f} " f"{'** SIGNIFICANT **' if r['significant'] else '(not significant)'}") print(f" 95% CI: [{r['ci_low']:.1%}, {r['ci_high']:.1%}]") # 5. Does CI exclude majority baseline? ci_excludes_majority = r["ci_low"] > r["majority"] print(f" CI excludes majority ({r['majority']:.1%})? " f"{'YES — robust' if ci_excludes_majority else 'NO — fragile'}") # -- Main -------------------------------------------------------------------- def main() -> None: print("=" * 60) print("FINAL EXPERIMENT: SDE + Technical, Walk-Forward") print("Per-asset analysis: BTC, ETH, SOL, BNB") print("=" * 60) all_results = [] t0_total = time.time() for asset in ASSETS: print(f"\n\n{'=' * 60}") print(f" {asset}") print(f"{'=' * 60}") # Fetch t0 = time.time() prices = fetch_prices(asset) print(f" Prices: {len(prices)} days") if len(prices) < WINDOW_SIZE + SHIFT + INITIAL_TRAIN * STRIDE: print(f" [SKIP] Not enough data") continue # Prepare windows, shifted, labels = make_windows(prices) n_up = labels.sum() print(f" Windows: {len(windows)} (up={n_up}, down={len(windows)-n_up})") # Walk-forward result = walk_forward_single_asset(asset, windows, shifted, labels) if result is None: continue elapsed = time.time() - t0 result["time"] = elapsed print(f"\n Total time: {elapsed:.1f}s") # Self-verify verify_result(result) all_results.append(result) # -- Summary Table ------------------------------------------------------- total_time = time.time() - t0_total print(f"\n\n{'=' * 60}") print(f"SUMMARY (total time: {total_time:.0f}s)") print(f"{'=' * 60}") print(f"{'Asset':<10s} {'Acc':>7s} {'N':>5s} {'Majority':>9s} " f"{'p-value':>9s} {'Sig':>5s} {'95% CI':>16s}") print("─" * 65) for r in all_results: sig = "**" if r["significant"] else "" ci = f"[{r['ci_low']:.1%}, {r['ci_high']:.1%}]" print(f"{r['asset']:<10s} {r['total_acc']:>6.1%} {r['n_total']:>5d} " f"{r['majority']:>8.1%} {r['p_value']:>9.4f} {sig:>5s} {ci:>16s}") # -- Aggregate across assets (for information, not pooled) --------------- if len(all_results) > 1: total_correct = sum(r["n_correct"] for r in all_results) total_n = sum(r["n_total"] for r in all_results) avg_acc = total_correct / total_n n_sig = sum(1 for r in all_results if r["significant"]) print(f"\n{'Combined':<10s} {avg_acc:>6.1%} {total_n:>5d}") print(f" Assets with p<0.05: {n_sig}/{len(all_results)}") # -- Final Verdict ------------------------------------------------------- print(f"\n{'=' * 60}") print("VERDICT") print("=" * 60) sig_assets = [r for r in all_results if r["significant"]] if sig_assets: for r in sig_assets: print(f" {r['asset']}: {r['total_acc']:.1%} accuracy, p={r['p_value']:.4f} " f"— STATISTICALLY SIGNIFICANT") print("\n SDE uncertainty + technical indicators provide") print(" a real directional signal on these assets.") else: print(" No asset achieved p < 0.05 in walk-forward validation.") # Check if any beats majority at all beating = [r for r in all_results if r["beats_majority"]] if beating: print(f"\n Assets beating majority baseline: " f"{', '.join(r['asset'] for r in beating)}") best = max(beating, key=lambda r: r["total_acc"]) print(f" Best: {best['asset']} at {best['total_acc']:.1%} " f"(majority={best['majority']:.1%}, p={best['p_value']:.4f})") else: print(" No asset beats its majority baseline.") print(" The market is efficient on daily timeframe for these methods.") print("=" * 60) if __name__ == "__main__": main()