""" Improved experiment: log-returns + multi-timeframe + online learning. 3 improvements over final_experiment.py: 1. Log-returns instead of prices (stationarity) 2. Multi-scale ensemble: 32d + 64d + 128d windows 3. Online learning: fine-tune from previous fold Per-asset walk-forward validation with self-verification. """ from __future__ import annotations 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_SIZES = [32, 64, 128] # multi-timeframe SHIFT = 7 STRIDE = 7 INITIAL_TRAIN = 80 TEST_CHUNK = 20 FIRST_FOLD_EPOCHS = 200 FINETUNE_EPOCHS = 50 N_STEPS = 20 TOTAL_TIME = 0.5 MC_SAMPLES = 30 LR = 3e-3 RANDOM_STATE = 42 # -- Data Pipeline ----------------------------------------------------------- def fetch_returns(ticker: str) -> np.ndarray: """Fetch daily prices → compute log-returns.""" t = yf.Ticker(ticker) hist = t.history(period="5y") prices = hist["Close"].dropna().values.astype(np.float64) # Log-returns: r[t] = log(p[t+1] / p[t]) returns = np.diff(np.log(prices)) print(f" {len(returns)} daily log-returns " f"(mean={returns.mean():.5f}, std={returns.std():.4f})") return returns def make_multiscale_data(returns: np.ndarray) -> dict: """Create aligned multi-scale windows with direction labels. All window sizes end at the same decision point t. Direction is based on raw (unnormalized) cumulative return over next SHIFT days. Returns dict with: windows: {32: array, 64: array, 128: array} targets: {32: array, 64: array, 128: array} labels: array of 0/1 """ W_max = max(WINDOW_SIZES) n = len(returns) windows = {ws: [] for ws in WINDOW_SIZES} targets = {ws: [] for ws in WINDOW_SIZES} labels = [] for t in range(W_max, n - SHIFT, STRIDE): # Direction: cumulative return over next SHIFT days (from RAW returns) future_ret = returns[t : t + SHIFT].sum() if abs(future_ret) < 1e-10: continue label = 1 if future_ret > 0 else 0 for ws in WINDOW_SIZES: w = returns[t - ws : t].copy() s = returns[t - ws + SHIFT : t + SHIFT].copy() # Z-score normalize (preserves shape, stabilizes training) mu, std = w.mean(), w.std() if std < 1e-10: std = 1e-10 w_norm = (w - mu) / std s_norm = (s - mu) / std # same reference frame windows[ws].append(w_norm) targets[ws].append(s_norm) labels.append(label) for ws in WINDOW_SIZES: windows[ws] = np.array(windows[ws], dtype=np.float64) targets[ws] = np.array(targets[ws], dtype=np.float64) labels = np.array(labels, dtype=np.int64) n_up = labels.sum() print(f" {len(labels)} windows (up={n_up}, down={len(labels)-n_up})") return {"windows": windows, "targets": targets, "labels": labels} # -- Feature Extraction ------------------------------------------------------ def extract_technical(windows_64: np.ndarray) -> np.ndarray: """7 technical features from medium-scale (64d) windows.""" n = len(windows_64) feats = np.zeros((n, 7)) for i, w in enumerate(windows_64): L = len(w) # RSI (14-period) on returns deltas = w[-14:] # returns are already deltas 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 # Short vs long mean 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) # Vol ratio vol_ratio = w[-7:].std() / (w.std() + 1e-10) # Relative position rel_sma = (w[-1] - w.mean()) / (w.std() + 1e-10) # MACD-like macd = w[-12:].mean() - w[: min(26, L)].mean() # Cumulative return (sum of normalized returns in last 10 days) cum_ret = w[-10:].sum() feats[i] = [rsi, ma_cross, bb_pos, vol_ratio, rel_sma, macd, cum_ret] 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_t = torch.stack(preds) mean_p = preds_t.mean(0).numpy() std_p = preds_t.std(0).numpy() g_np = windows n = len(windows) W = windows.shape[1] feats = np.zeros((n, 6)) for i in range(n): diff = mean_p[i] - g_np[i] feats[i, 0] = diff.mean() feats[i, 1] = diff[-1] feats[i, 2] = std_p[i].mean() feats[i, 3] = std_p[i, -1] feats[i, 4] = np.polyfit(np.arange(W), mean_p[i], 1)[0] feats[i, 5] = mean_p[i, -1] - mean_p[i].mean() return feats # -- Model Management ------------------------------------------------------- def create_sde_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_ssm=False, use_fno=False, use_sde=True, ) def train_sde( model: EnhancedRemizovNet, g_train: np.ndarray, y_train: np.ndarray, epochs: int, ) -> None: """Train (or fine-tune) SDE model in-place.""" 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=20, factor=0.5, min_lr=1e-5, ) criterion = nn.MSELoss() bs = min(64, len(g_train)) for _ in range(epochs): model.train() perm = torch.randperm(len(g_t)) total, nb = 0.0, 0 for i in range(0, len(g_t), bs): idx = perm[i : i + bs] 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.item() nb += 1 scheduler.step(total / nb) # -- Walk-Forward Validation ------------------------------------------------- def walk_forward( asset: str, data: dict, ) -> dict | None: """Walk-forward with online learning and multi-scale ensemble.""" labels = data["labels"] n = len(labels) n_folds = (n - INITIAL_TRAIN) // TEST_CHUNK if n_folds < 2: print(f" [SKIP] Only {n} windows, need more data") return None print(f" Walk-forward: {n_folds} folds " f"(init={INITIAL_TRAIN}, chunk={TEST_CHUNK})") # Online learning: persistent models across folds models: dict[int, EnhancedRemizovNet | None] = {ws: None for ws in WINDOW_SIZES} all_preds = [] all_true = [] fold_details = [] for fold in range(n_folds): boundary = INITIAL_TRAIN + fold * TEST_CHUNK test_end = min(boundary + TEST_CHUNK, n) test_labels = labels[boundary:test_end] if len(test_labels) == 0: break # -- Train/fine-tune 3 SDE models -- for ws in WINDOW_SIZES: w_tr = data["windows"][ws][:boundary] t_tr = data["targets"][ws][:boundary] if models[ws] is None: models[ws] = create_sde_model(ws) epochs = FIRST_FOLD_EPOCHS else: epochs = FINETUNE_EPOCHS train_sde(models[ws], w_tr, t_tr, epochs) # -- Extract features -- sde_feats_train = [] sde_feats_test = [] for ws in WINDOW_SIZES: sde_feats_train.append( extract_sde_features(models[ws], data["windows"][ws][:boundary]) ) sde_feats_test.append( extract_sde_features(models[ws], data["windows"][ws][boundary:test_end]) ) tech_train = extract_technical(data["windows"][64][:boundary]) tech_test = extract_technical(data["windows"][64][boundary:test_end]) X_train = np.hstack(sde_feats_train + [tech_train]) # 3*6 + 7 = 25 X_test = np.hstack(sde_feats_test + [tech_test]) 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) # -- Classify -- 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, labels[:boundary]) preds = clf.predict(Xte) fold_acc = np.mean(preds == test_labels) all_preds.extend(preds.tolist()) all_true.extend(test_labels.tolist()) # Get equation from medium-scale model eq = models[64].equation_string(precision=3) fold_details.append({ "fold": fold + 1, "train": boundary, "test": len(test_labels), "acc": fold_acc, }) print(f" Fold {fold+1}/{n_folds}: train={boundary} test={len(test_labels)} " f"acc={fold_acc:.0%} {eq}") if not all_preds: return None all_preds = np.array(all_preds) all_true = np.array(all_true) total_acc = np.mean(all_preds == all_true) n_total = len(all_true) n_correct = int(np.sum(all_preds == all_true)) 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, "beats_majority": total_acc > majority, "p_value": binom.pvalue, "significant": binom.pvalue < 0.05, "ci_low": ci.low, "ci_high": ci.high, "folds": fold_details, "up_ratio": all_true.mean(), } # -- Self-Verification ------------------------------------------------------- def verify(r: dict) -> None: """Self-verification protocol.""" print(f"\n {'─' * 50}") print(f" VERIFY: {r['asset']}") print(f" {'─' * 50}") # 1. Recompute accuracy from folds recomp = sum(f["acc"] * f["test"] for f in r["folds"]) recomp /= sum(f["test"] for f in r["folds"]) ok = abs(recomp - r["total_acc"]) < 0.02 print(f" Accuracy check: {recomp:.3f} vs {r['total_acc']:.3f} {'OK' if ok else 'MISMATCH!'}") # 2. Class balance print(f" Balance: {r['up_ratio']:.1%} up / {1-r['up_ratio']:.1%} down") # 3. Fold stability accs = [f["acc"] for f in r["folds"]] print(f" Folds: {' '.join(f'{a:.0%}' for a in accs)} " f"std={np.std(accs):.1%}") # 4. Does accuracy improve over folds? (online learning signal) if len(accs) >= 4: first_half = np.mean(accs[: len(accs) // 2]) second_half = np.mean(accs[len(accs) // 2 :]) improving = second_half > first_half print(f" Online learning: first_half={first_half:.1%} → " f"second_half={second_half:.1%} " f"{'IMPROVING' if improving else 'no improvement'}") # 5. Significance print(f" p-value: {r['p_value']:.4f} " f"{'** SIGNIFICANT **' if r['significant'] else ''}") print(f" 95% CI: [{r['ci_low']:.1%}, {r['ci_high']:.1%}]") ci_robust = r["ci_low"] > r["majority"] print(f" CI > majority ({r['majority']:.1%})? " f"{'YES' if ci_robust else 'NO'}") # -- Main -------------------------------------------------------------------- def main() -> None: print("=" * 60) print("IMPROVED EXPERIMENT") print("Log-returns + Multi-timeframe (32/64/128d) + Online Learning") print("=" * 60) results = [] t_total = time.time() for asset in ASSETS: print(f"\n{'=' * 60}") print(f" {asset}") print(f"{'=' * 60}") t0 = time.time() returns = fetch_returns(asset) if len(returns) < max(WINDOW_SIZES) + SHIFT + INITIAL_TRAIN * STRIDE: print(f" [SKIP] Not enough data") continue data = make_multiscale_data(returns) result = walk_forward(asset, data) if result is None: continue result["time"] = time.time() - t0 print(f"\n Time: {result['time']:.1f}s") verify(result) results.append(result) # -- Summary --- print(f"\n\n{'=' * 60}") print(f"SUMMARY ({time.time() - t_total:.0f}s total)") print(f"{'=' * 60}") print(f"{'Asset':<10s} {'Acc':>6s} {'N':>5s} {'Maj':>6s} " f"{'p-val':>8s} {'Sig':>5s} {'CI':>16s} {'Online':>8s}") print("─" * 70) for r in results: sig = "**" if r["significant"] else "" ci = f"[{r['ci_low']:.1%},{r['ci_high']:.1%}]" accs = [f["acc"] for f in r["folds"]] first = np.mean(accs[: len(accs) // 2]) second = np.mean(accs[len(accs) // 2 :]) trend = "UP" if second > first + 0.02 else ("DOWN" if second < first - 0.02 else "flat") print(f"{r['asset']:<10s} {r['total_acc']:>5.1%} {r['n_total']:>5d} " f"{r['majority']:>5.1%} {r['p_value']:>8.4f} {sig:>5s} " f"{ci:>16s} {trend:>8s}") # -- Comparison with previous experiment --- print(f"\n{'=' * 60}") print("COMPARISON: improved vs previous") print("=" * 60) prev = {"BTC-USD": 0.533, "ETH-USD": 0.593, "SOL-USD": 0.453, "BNB-USD": 0.487} for r in results: p = prev.get(r["asset"], 0) delta = r["total_acc"] - p print(f" {r['asset']}: {p:.1%} → {r['total_acc']:.1%} ({delta:+.1%})") # -- Verdict --- print(f"\n{'=' * 60}") print("VERDICT") print("=" * 60) sig = [r for r in results if r["significant"]] if sig: for r in sig: print(f" {r['asset']}: {r['total_acc']:.1%} (p={r['p_value']:.4f}) " f"— STATISTICALLY SIGNIFICANT") else: best = max(results, key=lambda r: r["total_acc"]) if results else None if best: print(f" Best: {best['asset']} at {best['total_acc']:.1%} (p={best['p_value']:.4f})") beating = [r for r in results if r["beats_majority"]] if beating: print(f" Beating majority: {', '.join(r['asset'] for r in beating)}") # Online learning effectiveness improving = [] for r in results: accs = [f["acc"] for f in r["folds"]] if len(accs) >= 4: if np.mean(accs[len(accs)//2:]) > np.mean(accs[:len(accs)//2]) + 0.02: improving.append(r["asset"]) if improving: print(f" Online learning helps: {', '.join(improving)}") print("=" * 60) if __name__ == "__main__": main()