""" RemizovNet crypto experiment: can Chernoff-based ODE discovery predict BTC price patterns? Experiment: 1. Fetch BTC daily prices 2. Create sliding windows (input g -> target y shifted by N days) 3. Train RemizovNet to learn g -> y mapping 4. Compare to random walk baseline 5. Interpret discovered ODE coefficients """ from __future__ import annotations import time import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn from data import fetch_btc_daily, prepare_dataset from remizov_net import RemizovNet # -- Config ------------------------------------------------------------------ WINDOW_SIZE = 64 # ~2 months of daily data SHIFT = 7 # predict 7 days ahead TRAIN_RATIO = 0.8 N_STEPS = 20 # Chernoff depth TOTAL_TIME = 0.5 # semigroup evolution time EPOCHS = 500 LR = 3e-3 DX = 1.0 / WINDOW_SIZE # normalized grid spacing # -- Training ---------------------------------------------------------------- def train_model( model: RemizovNet, g_train: torch.Tensor, y_train: torch.Tensor, epochs: int = EPOCHS, lr: float = LR, ) -> list[float]: """Train RemizovNet on window pairs.""" optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=1e-4) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, patience=50, factor=0.5, min_lr=1e-5, ) criterion = nn.MSELoss() loss_history = [] # Mini-batch training for better convergence batch_size = min(128, len(g_train)) print(f"\nTraining RemizovNet (depth={model.n_steps}, epochs={epochs})...") t0 = time.time() for epoch in range(epochs): # Shuffle perm = torch.randperm(len(g_train)) epoch_loss = 0.0 n_batches = 0 for i in range(0, len(g_train), batch_size): idx = perm[i : i + batch_size] g_batch = g_train[idx] y_batch = y_train[idx] optimizer.zero_grad() y_pred = model(g_batch) loss = criterion(y_pred, y_batch) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() epoch_loss += loss.item() n_batches += 1 avg_loss = epoch_loss / n_batches loss_history.append(avg_loss) scheduler.step(avg_loss) if (epoch + 1) % 100 == 0: eq = model.equation_string() elapsed = time.time() - t0 print(f" Epoch {epoch+1}/{epochs} loss={avg_loss:.6f} " f"time={elapsed:.1f}s {eq}") print(f"Training done in {time.time() - t0:.1f}s, final loss={loss_history[-1]:.6f}") return loss_history # -- Evaluation -------------------------------------------------------------- def evaluate( model: RemizovNet, g_test: torch.Tensor, y_test: torch.Tensor, ) -> dict[str, float]: """Evaluate model vs multiple baselines.""" model.eval() with torch.no_grad(): y_pred = model(g_test) y_pred_np = y_pred.numpy() y_test_np = y_test.numpy() g_test_np = g_test.numpy() # Baseline 1: Random walk (y = g, pattern unchanged) rw_pred = g_test_np # Baseline 2: Linear extrapolation (extend the local trend) # For each window, extrapolate using the slope of the last 7 points lin_pred = np.zeros_like(g_test_np) for i in range(len(g_test_np)): g = g_test_np[i] slope = (g[-1] - g[-SHIFT]) / SHIFT if SHIFT > 0 else 0.0 lin_pred[i] = g + slope * SHIFT # shift entire window by the trend # MSE for all mse_model = np.mean((y_pred_np - y_test_np) ** 2) mse_rw = np.mean((rw_pred - y_test_np) ** 2) mse_lin = np.mean((lin_pred - y_test_np) ** 2) # MAE mae_model = np.mean(np.abs(y_pred_np - y_test_np)) mae_rw = np.mean(np.abs(rw_pred - y_test_np)) # Directional accuracy: compare the LAST point of predicted vs input window # This measures "does the model predict price going up or down?" true_direction = np.sign(y_test_np[:, -1] - g_test_np[:, -1]) pred_direction = np.sign(y_pred_np[:, -1] - g_test_np[:, -1]) # Filter out zero-direction samples (no change) for fair comparison nonzero_mask = true_direction != 0 if nonzero_mask.sum() > 0: directional_acc = np.mean( pred_direction[nonzero_mask] == true_direction[nonzero_mask] ) else: directional_acc = 0.5 # "Always up" baseline — exposes bull-market bias always_up_acc = np.mean(true_direction[nonzero_mask] == 1) if nonzero_mask.sum() > 0 else 0.5 results = { "mse_model": mse_model, "mse_rw": mse_rw, "mse_lin": mse_lin, "mse_vs_rw": mse_model / mse_rw if mse_rw > 0 else float("inf"), "mse_vs_lin": mse_model / mse_lin if mse_lin > 0 else float("inf"), "mae_model": mae_model, "mae_rw": mae_rw, "directional_acc": directional_acc, "always_up_acc": always_up_acc, "n_test": len(g_test_np), "n_nonzero": int(nonzero_mask.sum()), } print("\n" + "=" * 60) print("RESULTS") print("=" * 60) print(f"MSE Model: {mse_model:.6f}") print(f"MSE Random Walk: {mse_rw:.6f}") print(f"MSE Linear Extrap: {mse_lin:.6f}") print(f"MSE vs RW: {results['mse_vs_rw']:.4f} {'BETTER' if results['mse_vs_rw'] < 1 else 'WORSE'}") print(f"MSE vs LinExtrap: {results['mse_vs_lin']:.4f} {'BETTER' if results['mse_vs_lin'] < 1 else 'WORSE'}") print(f"MAE Model: {mae_model:.6f}") print(f"MAE Random Walk: {mae_rw:.6f}") print() print(f"Dir. Accuracy Model: {directional_acc:.1%} ({results['n_nonzero']} samples with clear direction)") print(f"Dir. Accuracy 'Always Up': {always_up_acc:.1%} (bull-market bias check)") if directional_acc > always_up_acc + 0.05: print(" -> Model beats naive 'always up' — learns real structure") elif directional_acc > always_up_acc - 0.05: print(" -> Model ~ 'always up' — may just be learning the trend bias") else: print(" -> Model worse than 'always up' — not learning direction") print("=" * 60) return results # -- Interpretation ---------------------------------------------------------- def interpret_coefficients(model: RemizovNet) -> None: """Print and analyze discovered ODE coefficients.""" coeffs = model.get_coefficients() a = coeffs["a"].numpy() b = coeffs["b"].numpy() c = coeffs["c"].numpy() print("\nDiscovered ODE: a(x)y'' + b(x)y' + c(x)y = g(x)") print(f" {model.equation_string(precision=4)}") print(f"\n a(x) [volatility/diffusion]: mean={a.mean():.4f}, std={a.std():.4f}") print(f" b(x) [drift/trend]: mean={b.mean():.4f}, std={b.std():.4f}") print(f" c(x) [mean-reversion]: mean={c.mean():.4f}, std={c.std():.4f}") # Physical interpretation print("\nInterpretation:") if a.mean() > 0.5: print(" - High diffusion (a >> 0): price patterns spread/smooth over time") else: print(" - Low diffusion (a ~ 0): patterns persist with minimal smoothing") if abs(b.mean()) > 0.1: direction = "upward" if b.mean() > 0 else "downward" print(f" - Non-zero drift (b != 0): systematic {direction} trend detected") else: print(" - Near-zero drift (b ~ 0): no systematic trend (efficient market)") if c.mean() < -0.1: print(" - Negative potential (c < 0): mean-reverting behavior") elif c.mean() > 0.1: print(" - Positive potential (c > 0): momentum/amplification behavior") else: print(" - Near-zero potential (c ~ 0): neither mean-reversion nor momentum") return a, b, c # -- Visualization ----------------------------------------------------------- def plot_results( loss_history: list[float], model: RemizovNet, g_test: torch.Tensor, y_test: torch.Tensor, a: np.ndarray, b: np.ndarray, c: np.ndarray, ) -> None: """Generate plots for the experiment.""" fig, axes = plt.subplots(2, 2, figsize=(14, 10)) fig.suptitle("RemizovNet Crypto Experiment: BTC-USD Daily", fontsize=14) # 1. Loss curve ax = axes[0, 0] ax.semilogy(loss_history) ax.set_xlabel("Epoch") ax.set_ylabel("MSE Loss") ax.set_title("Training Loss") ax.grid(True, alpha=0.3) # 2. Sample predictions ax = axes[0, 1] model.eval() with torch.no_grad(): y_pred = model(g_test[:5]) for i in range(3): x = np.arange(WINDOW_SIZE) ax.plot(x, g_test[i].numpy(), "b--", alpha=0.4, label="input g" if i == 0 else "") ax.plot(x, y_test[i].numpy(), "g-", alpha=0.6, label="true y" if i == 0 else "") ax.plot(x, y_pred[i].numpy(), "r-", alpha=0.6, label="predicted" if i == 0 else "") ax.set_xlabel("Position in window") ax.set_ylabel("Normalized price") ax.set_title(f"Sample Predictions (shift={SHIFT}d)") ax.legend(fontsize=8) ax.grid(True, alpha=0.3) # 3. Discovered coefficients ax = axes[1, 0] x = np.arange(WINDOW_SIZE) ax.plot(x, a, label="a(x) — diffusion", linewidth=2) ax.plot(x, b, label="b(x) — drift", linewidth=2) ax.plot(x, c, label="c(x) — potential", linewidth=2) ax.axhline(y=0, color="k", linestyle=":", alpha=0.3) ax.set_xlabel("Position in window") ax.set_ylabel("Coefficient value") ax.set_title("Discovered ODE Coefficients") ax.legend(fontsize=8) ax.grid(True, alpha=0.3) # 4. Prediction error distribution ax = axes[1, 1] with torch.no_grad(): y_pred_all = model(g_test).numpy() errors = (y_pred_all - y_test.numpy()).flatten() ax.hist(errors, bins=50, density=True, alpha=0.7, color="steelblue") ax.axvline(x=0, color="r", linestyle="--", alpha=0.5) ax.set_xlabel("Prediction error") ax.set_ylabel("Density") ax.set_title(f"Error Distribution (mean={errors.mean():.4f}, std={errors.std():.4f})") ax.grid(True, alpha=0.3) plt.tight_layout() plt.savefig("/Users/alchemist/Python_projects/remizov-crypto/results.png", dpi=150) print("\nPlot saved to results.png") plt.close() # -- Main -------------------------------------------------------------------- def main() -> None: print("=" * 60) print("RemizovNet Crypto Experiment") print("Can Chernoff ODE discovery predict BTC price patterns?") print("=" * 60) # 1. Fetch data prices = fetch_btc_daily(period="5y") # 2. Prepare dataset dataset = prepare_dataset( prices, window_size=WINDOW_SIZE, shift=SHIFT, train_ratio=TRAIN_RATIO, ) # 3. Create model model = RemizovNet( grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME, shared_coeffs=True, dx=DX, ) print(f"\nModel: {sum(p.numel() for p in model.parameters())} parameters") # 4. Train loss_history = train_model( model, dataset["g_train"], dataset["y_train"], epochs=EPOCHS, lr=LR, ) # 5. Evaluate results = evaluate(model, dataset["g_test"], dataset["y_test"]) # 6. Interpret a, b, c = interpret_coefficients(model) # 7. Visualize plot_results( loss_history, model, dataset["g_test"], dataset["y_test"], a, b, c, ) # 8. Verdict print("\n" + "=" * 60) print("VERDICT") print("=" * 60) # MSE vs both baselines beats_rw = results["mse_vs_rw"] < 0.95 beats_lin = results["mse_vs_lin"] < 0.95 if beats_rw and beats_lin: print("RemizovNet BEATS both baselines!") print(f" vs Random Walk: -{(1 - results['mse_vs_rw']) * 100:.1f}% MSE") print(f" vs Linear Extrap: -{(1 - results['mse_vs_lin']) * 100:.1f}% MSE") elif beats_rw: print("RemizovNet beats random walk but NOT linear extrapolation.") print("The model may just be learning a simple trend shift.") else: print("RemizovNet does NOT beat baselines on MSE.") # Directional accuracy — honest assessment da = results["directional_acc"] au = results["always_up_acc"] if da > au + 0.05: print(f"\nDirectional accuracy {da:.1%} > 'always up' {au:.1%}") print("Model learns structure beyond simple trend bias.") else: print(f"\nDirectional accuracy {da:.1%} ~ 'always up' {au:.1%}") print("CAUTION: model may just be exploiting bull-market bias.") print("\nCAVEATS:") print(" - Linear ODE is a strong simplification of market dynamics") print(" - No transaction costs, slippage, or execution modeled") print(" - Past performance does not predict future results") print("=" * 60) if __name__ == "__main__": main()