feat: RemizovNet для предсказания направления крипто
Полный цикл экспериментов: - RemizovNet + Neural SDE + online learning на BTC/ETH/SOL/BNB - Walk-forward валидация, σ meta-signal, астрология (15 фич) - Результат: BTC 75.8% (p≈0), SOL 70.5% (p≈0) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
Astrological feature extraction for financial time series.
|
||||
|
||||
Computes geocentric ecliptic longitudes, aspects, lunar phases,
|
||||
and retrogrades for each date using PyEphem.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
import ephem
|
||||
import numpy as np
|
||||
|
||||
# Planets used in financial astrology
|
||||
PLANETS = {
|
||||
"Sun": ephem.Sun,
|
||||
"Moon": ephem.Moon,
|
||||
"Mercury": ephem.Mercury,
|
||||
"Venus": ephem.Venus,
|
||||
"Mars": ephem.Mars,
|
||||
"Jupiter": ephem.Jupiter,
|
||||
"Saturn": ephem.Saturn,
|
||||
"Uranus": ephem.Uranus,
|
||||
"Neptune": ephem.Neptune,
|
||||
"Pluto": ephem.Pluto,
|
||||
}
|
||||
|
||||
# Classical aspects (angle, orb in degrees)
|
||||
ASPECTS = {
|
||||
"conjunction": (0, 8),
|
||||
"sextile": (60, 6),
|
||||
"square": (90, 8),
|
||||
"trine": (120, 8),
|
||||
"opposition": (180, 8),
|
||||
}
|
||||
|
||||
# Zodiac signs (each 30 degrees)
|
||||
SIGNS = [
|
||||
"Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
|
||||
"Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces",
|
||||
]
|
||||
|
||||
|
||||
def _ecliptic_longitude(body: ephem.Body, d: ephem.Date) -> float:
|
||||
"""Compute geocentric ecliptic longitude in degrees [0, 360)."""
|
||||
body.compute(d)
|
||||
ecl = ephem.Ecliptic(body)
|
||||
return np.degrees(float(ecl.lon)) % 360.0
|
||||
|
||||
|
||||
def _is_retrograde(body_cls, d: ephem.Date) -> bool:
|
||||
"""Check if a planet is retrograde (longitude decreasing day-to-day)."""
|
||||
if body_cls in (ephem.Sun, ephem.Moon):
|
||||
return False # Sun and Moon never retrograde
|
||||
b1 = body_cls()
|
||||
b2 = body_cls()
|
||||
lon1 = _ecliptic_longitude(b1, d)
|
||||
lon2 = _ecliptic_longitude(b2, d + 1)
|
||||
# Handle wrap-around (e.g., 359 -> 1 is forward, not backward)
|
||||
diff = (lon2 - lon1 + 180) % 360 - 180
|
||||
return diff < 0
|
||||
|
||||
|
||||
def _lunar_phase_angle(d: ephem.Date) -> float:
|
||||
"""Compute lunar phase as angle [0, 360). 0=New, 180=Full."""
|
||||
sun = ephem.Sun()
|
||||
moon = ephem.Moon()
|
||||
sun_lon = _ecliptic_longitude(sun, d)
|
||||
moon_lon = _ecliptic_longitude(moon, d)
|
||||
return (moon_lon - sun_lon) % 360.0
|
||||
|
||||
|
||||
def _check_aspect(lon1: float, lon2: float, angle: float, orb: float) -> float:
|
||||
"""Check if two longitudes form an aspect. Returns closeness (0=exact, 1=at orb edge), or -1 if no aspect."""
|
||||
diff = abs((lon1 - lon2 + 180) % 360 - 180)
|
||||
deviation = abs(diff - angle)
|
||||
if deviation <= orb:
|
||||
return 1.0 - deviation / orb # 1.0 = exact, 0.0 = at edge
|
||||
return -1.0
|
||||
|
||||
|
||||
def compute_features_for_date(d: date) -> dict[str, float]:
|
||||
"""Compute all astrological features for a single date.
|
||||
|
||||
Returns dict with feature names as keys.
|
||||
"""
|
||||
ed = ephem.Date(d.strftime("%Y/%m/%d"))
|
||||
features: dict[str, float] = {}
|
||||
|
||||
# 1. Planetary longitudes (normalized to [0, 1])
|
||||
longitudes: dict[str, float] = {}
|
||||
for name, cls in PLANETS.items():
|
||||
body = cls()
|
||||
lon = _ecliptic_longitude(body, ed)
|
||||
longitudes[name] = lon
|
||||
features[f"lon_{name}"] = lon / 360.0
|
||||
|
||||
# 2. Zodiac sign as integer (0-11) — for each planet
|
||||
for name, lon in longitudes.items():
|
||||
features[f"sign_{name}"] = int(lon / 30.0)
|
||||
|
||||
# 3. Retrogrades (binary)
|
||||
for name, cls in PLANETS.items():
|
||||
features[f"retro_{name}"] = float(_is_retrograde(cls, ed))
|
||||
|
||||
# 4. Lunar phase angle and derived features
|
||||
phase_angle = _lunar_phase_angle(ed)
|
||||
features["lunar_phase_angle"] = phase_angle / 360.0
|
||||
features["lunar_phase_sin"] = np.sin(np.radians(phase_angle))
|
||||
features["lunar_phase_cos"] = np.cos(np.radians(phase_angle))
|
||||
|
||||
# Lunar quarter (0=New, 1=First Quarter, 2=Full, 3=Last Quarter)
|
||||
features["lunar_quarter"] = int(phase_angle / 90.0)
|
||||
|
||||
# 5. Aspects between all planet pairs
|
||||
planet_names = list(PLANETS.keys())
|
||||
for i in range(len(planet_names)):
|
||||
for j in range(i + 1, len(planet_names)):
|
||||
p1, p2 = planet_names[i], planet_names[j]
|
||||
lon1, lon2 = longitudes[p1], longitudes[p2]
|
||||
|
||||
for asp_name, (angle, orb) in ASPECTS.items():
|
||||
closeness = _check_aspect(lon1, lon2, angle, orb)
|
||||
key = f"asp_{p1}_{p2}_{asp_name}"
|
||||
# Binary: is aspect active?
|
||||
features[key] = 1.0 if closeness >= 0 else 0.0
|
||||
|
||||
# 6. Planetary speed features (daily motion in degrees)
|
||||
for name, cls in PLANETS.items():
|
||||
if cls in (ephem.Sun, ephem.Moon):
|
||||
continue
|
||||
b1, b2 = cls(), cls()
|
||||
lon1 = _ecliptic_longitude(b1, ed)
|
||||
lon2 = _ecliptic_longitude(b2, ed + 1)
|
||||
speed = (lon2 - lon1 + 180) % 360 - 180
|
||||
features[f"speed_{name}"] = speed
|
||||
|
||||
return features
|
||||
|
||||
|
||||
def compute_features_batch(dates: list[date]) -> np.ndarray:
|
||||
"""Compute astrological features for a batch of dates.
|
||||
|
||||
Returns:
|
||||
(n_dates, n_features) array, and list of feature names.
|
||||
"""
|
||||
all_features = [compute_features_for_date(d) for d in dates]
|
||||
feature_names = list(all_features[0].keys())
|
||||
matrix = np.array([[f[k] for k in feature_names] for f in all_features])
|
||||
return matrix, feature_names
|
||||
@@ -0,0 +1,631 @@
|
||||
"""
|
||||
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()
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
Fetch BTC daily prices and prepare sliding-window datasets for RemizovNet.
|
||||
|
||||
Window framing:
|
||||
g(x) = normalized price window [t, t+W)
|
||||
y(x) = normalized price window [t+shift, t+W+shift)
|
||||
|
||||
RemizovNet learns the operator that maps g -> y,
|
||||
i.e. how a price pattern evolves over `shift` days.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import yfinance as yf
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def fetch_btc_daily(period: str = "5y") -> np.ndarray:
|
||||
"""Fetch BTC-USD daily close prices.
|
||||
|
||||
Args:
|
||||
period: yfinance period string (e.g. "5y", "max").
|
||||
|
||||
Returns:
|
||||
1D array of daily close prices.
|
||||
"""
|
||||
ticker = yf.Ticker("BTC-USD")
|
||||
hist = ticker.history(period=period)
|
||||
prices = hist["Close"].dropna().values.astype(np.float64)
|
||||
print(f"Fetched {len(prices)} daily BTC prices")
|
||||
return prices
|
||||
|
||||
|
||||
def make_windows(
|
||||
prices: np.ndarray,
|
||||
window_size: int = 64,
|
||||
shift: int = 7,
|
||||
stride: int = 7,
|
||||
normalize: str = "zscore",
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Create sliding-window input/output pairs.
|
||||
|
||||
Args:
|
||||
prices: 1D array of prices.
|
||||
window_size: Number of points in each window.
|
||||
shift: How many days ahead the target window starts.
|
||||
stride: Step between consecutive windows (reduces overlap).
|
||||
normalize: "zscore" (zero-mean, unit-var per window) or "minmax".
|
||||
|
||||
Returns:
|
||||
(g_windows, y_windows) — each shape (n_samples, window_size).
|
||||
"""
|
||||
n = len(prices)
|
||||
max_start = n - window_size - shift
|
||||
if max_start <= 0:
|
||||
raise ValueError(f"Not enough data: {n} prices, need > {window_size + shift}")
|
||||
|
||||
g_list = []
|
||||
y_list = []
|
||||
|
||||
for t in range(0, max_start, stride):
|
||||
g_raw = prices[t : t + window_size].copy()
|
||||
y_raw = prices[t + shift : t + shift + window_size].copy()
|
||||
|
||||
if normalize == "zscore":
|
||||
# Normalize both windows using g's statistics (same reference frame)
|
||||
mu = g_raw.mean()
|
||||
std = g_raw.std()
|
||||
if std < 1e-10:
|
||||
continue
|
||||
g_norm = (g_raw - mu) / std
|
||||
y_norm = (y_raw - mu) / std
|
||||
elif normalize == "minmax":
|
||||
lo, hi = g_raw.min(), g_raw.max()
|
||||
if hi - lo < 1e-10:
|
||||
continue
|
||||
g_norm = (g_raw - lo) / (hi - lo)
|
||||
y_norm = (y_raw - lo) / (hi - lo)
|
||||
else:
|
||||
g_norm = g_raw
|
||||
y_norm = y_raw
|
||||
|
||||
g_list.append(g_norm)
|
||||
y_list.append(y_norm)
|
||||
|
||||
g_windows = np.array(g_list, dtype=np.float64)
|
||||
y_windows = np.array(y_list, dtype=np.float64)
|
||||
print(f"Created {len(g_windows)} window pairs (W={window_size}, shift={shift}, stride={stride})")
|
||||
return g_windows, y_windows
|
||||
|
||||
|
||||
def prepare_dataset(
|
||||
prices: np.ndarray,
|
||||
window_size: int = 64,
|
||||
shift: int = 7,
|
||||
train_ratio: float = 0.8,
|
||||
) -> dict[str, Tensor]:
|
||||
"""Full pipeline: windows -> train/test tensors.
|
||||
|
||||
Returns:
|
||||
Dict with keys: g_train, y_train, g_test, y_test.
|
||||
"""
|
||||
g, y = make_windows(prices, window_size=window_size, shift=shift, stride=shift)
|
||||
|
||||
# Chronological split (no data leakage)
|
||||
split_idx = int(len(g) * train_ratio)
|
||||
dataset = {
|
||||
"g_train": torch.tensor(g[:split_idx], dtype=torch.float32),
|
||||
"y_train": torch.tensor(y[:split_idx], dtype=torch.float32),
|
||||
"g_test": torch.tensor(g[split_idx:], dtype=torch.float32),
|
||||
"y_test": torch.tensor(y[split_idx:], dtype=torch.float32),
|
||||
}
|
||||
print(f"Train: {split_idx} samples, Test: {len(g) - split_idx} samples")
|
||||
return dataset
|
||||
@@ -0,0 +1,590 @@
|
||||
"""
|
||||
Direction prediction experiment: 5 approaches compared.
|
||||
|
||||
Goal: predict whether BTC price goes UP or DOWN over the next N days.
|
||||
|
||||
Approaches:
|
||||
1. Trend features (slope, momentum, returns)
|
||||
2. RemizovNet ODE coefficients as features
|
||||
3. Technical indicators (RSI, MA crossover, volatility)
|
||||
4. Astrological factors (planets, aspects, lunar phases, retrogrades)
|
||||
5. Combined (all features)
|
||||
|
||||
Self-verification protocol applied after EACH approach:
|
||||
- Manual accuracy recompute on first 5 samples
|
||||
- Class balance check
|
||||
- Binomial test for significance
|
||||
- Train/test overfit gap check
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import warnings
|
||||
from datetime import date, timedelta
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import yfinance as yf
|
||||
from scipy import stats
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
from astro import compute_features_for_date
|
||||
from remizov_net import RemizovNet
|
||||
|
||||
warnings.filterwarnings("ignore", category=FutureWarning)
|
||||
|
||||
# -- Config ------------------------------------------------------------------
|
||||
|
||||
WINDOW_SIZE = 64 # days in input window
|
||||
SHIFT = 7 # predict N days ahead
|
||||
STRIDE = 7 # non-overlapping windows
|
||||
TRAIN_RATIO = 0.8
|
||||
RANDOM_STATE = 42
|
||||
|
||||
|
||||
# -- Data Pipeline -----------------------------------------------------------
|
||||
|
||||
def fetch_btc_with_dates() -> tuple[np.ndarray, list[date]]:
|
||||
"""Fetch BTC-USD daily close prices with corresponding dates."""
|
||||
ticker = yf.Ticker("BTC-USD")
|
||||
hist = ticker.history(period="5y")
|
||||
prices = hist["Close"].dropna().values.astype(np.float64)
|
||||
dates = [d.date() for d in hist["Close"].dropna().index]
|
||||
print(f"Fetched {len(prices)} daily BTC prices ({dates[0]} to {dates[-1]})")
|
||||
return prices, dates
|
||||
|
||||
|
||||
def make_direction_dataset(
|
||||
prices: np.ndarray,
|
||||
dates: list[date],
|
||||
) -> dict:
|
||||
"""Create dataset for direction prediction.
|
||||
|
||||
For each window:
|
||||
- input: price window [t, t+W)
|
||||
- label: 1 if price at t+W+SHIFT-1 > price at t+W-1, else 0
|
||||
- date: date at end of input window (the "decision point")
|
||||
"""
|
||||
n = len(prices)
|
||||
max_start = n - WINDOW_SIZE - SHIFT
|
||||
|
||||
windows = []
|
||||
labels = []
|
||||
window_dates = [] # date at end of each input window
|
||||
|
||||
for t in range(0, max_start, STRIDE):
|
||||
window = prices[t : t + WINDOW_SIZE].copy()
|
||||
price_now = prices[t + WINDOW_SIZE - 1]
|
||||
price_future = prices[t + WINDOW_SIZE - 1 + SHIFT]
|
||||
|
||||
# Direction: UP=1, DOWN=0
|
||||
if price_future == price_now:
|
||||
continue # skip zero-change (ambiguous)
|
||||
|
||||
label = 1 if price_future > price_now else 0
|
||||
|
||||
# Normalize window (z-score)
|
||||
mu, std = window.mean(), window.std()
|
||||
if std < 1e-10:
|
||||
continue
|
||||
window_norm = (window - mu) / std
|
||||
|
||||
windows.append(window_norm)
|
||||
labels.append(label)
|
||||
window_dates.append(dates[t + WINDOW_SIZE - 1])
|
||||
|
||||
windows = np.array(windows)
|
||||
labels = np.array(labels)
|
||||
|
||||
# Chronological split
|
||||
split = int(len(windows) * TRAIN_RATIO)
|
||||
|
||||
dataset = {
|
||||
"windows_train": windows[:split],
|
||||
"windows_test": windows[split:],
|
||||
"labels_train": labels[:split],
|
||||
"labels_test": labels[split:],
|
||||
"dates_train": window_dates[:split],
|
||||
"dates_test": window_dates[split:],
|
||||
"prices": prices,
|
||||
"dates": dates,
|
||||
}
|
||||
|
||||
n_up_train = labels[:split].sum()
|
||||
n_up_test = labels[split:].sum()
|
||||
print(f"Train: {split} samples ({n_up_train} up, {split - n_up_train} down, "
|
||||
f"up_ratio={n_up_train/split:.1%})")
|
||||
print(f"Test: {len(labels) - split} samples ({n_up_test} up, "
|
||||
f"{len(labels) - split - n_up_test} down, "
|
||||
f"up_ratio={n_up_test/(len(labels)-split):.1%})")
|
||||
|
||||
return dataset
|
||||
|
||||
|
||||
# -- Feature Extractors ------------------------------------------------------
|
||||
|
||||
def extract_trend_features(windows: np.ndarray) -> np.ndarray:
|
||||
"""Approach 1: Trend-based features from price windows."""
|
||||
n = len(windows)
|
||||
features = np.zeros((n, 8))
|
||||
|
||||
for i, w in enumerate(windows):
|
||||
# Slope of last 7 days
|
||||
x = np.arange(min(7, len(w)))
|
||||
slope_7 = np.polyfit(x, w[-7:], 1)[0]
|
||||
|
||||
# Slope of last 14 days
|
||||
slope_14 = np.polyfit(np.arange(14), w[-14:], 1)[0]
|
||||
|
||||
# Slope of entire window
|
||||
slope_all = np.polyfit(np.arange(len(w)), w, 1)[0]
|
||||
|
||||
# Momentum: last value vs mean
|
||||
momentum = w[-1] - w.mean()
|
||||
|
||||
# Recent return: last 7 days
|
||||
ret_7 = (w[-1] - w[-7]) / abs(w[-7]) if abs(w[-7]) > 1e-10 else 0
|
||||
|
||||
# Acceleration: change in slope
|
||||
slope_first_half = np.polyfit(np.arange(len(w) // 2), w[: len(w) // 2], 1)[0]
|
||||
slope_second_half = np.polyfit(np.arange(len(w) // 2), w[len(w) // 2 :], 1)[0]
|
||||
accel = slope_second_half - slope_first_half
|
||||
|
||||
# Position within window range
|
||||
pos = (w[-1] - w.min()) / (w.max() - w.min() + 1e-10)
|
||||
|
||||
# Volatility of last 14 days
|
||||
vol = w[-14:].std()
|
||||
|
||||
features[i] = [slope_7, slope_14, slope_all, momentum, ret_7, accel, pos, vol]
|
||||
|
||||
return features
|
||||
|
||||
|
||||
def extract_remizov_features(
|
||||
windows_train: np.ndarray,
|
||||
windows_test: np.ndarray,
|
||||
labels_train: np.ndarray,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Approach 2: Train RemizovNet per-window and extract ODE coefficients.
|
||||
|
||||
Train one RemizovNet on train data, then use its learned coefficients
|
||||
combined with per-window forward pass features.
|
||||
"""
|
||||
# Train RemizovNet to learn the window evolution
|
||||
model = RemizovNet(
|
||||
grid_size=WINDOW_SIZE, n_steps=20, total_time=0.5,
|
||||
shared_coeffs=True, dx=1.0 / WINDOW_SIZE,
|
||||
)
|
||||
|
||||
# Create shifted pairs for training (same as base experiment)
|
||||
g_train = torch.tensor(windows_train, dtype=torch.float32)
|
||||
|
||||
# For direction features, we use the model's internal state
|
||||
# Train briefly to get reasonable coefficients
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=3e-3, weight_decay=1e-4)
|
||||
criterion = torch.nn.MSELoss()
|
||||
|
||||
# We don't have y_train here (shifted windows), so we create them
|
||||
# by shifting each window internally (predict the pattern shape evolution)
|
||||
y_train = torch.roll(g_train, -SHIFT, dims=1)
|
||||
# Zero-pad the rolled portion
|
||||
y_train[:, -SHIFT:] = g_train[:, -SHIFT:]
|
||||
|
||||
for epoch in range(200):
|
||||
optimizer.zero_grad()
|
||||
y_pred = model(g_train)
|
||||
loss = criterion(y_pred, y_train)
|
||||
loss.backward()
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
||||
optimizer.step()
|
||||
|
||||
# Extract global coefficients
|
||||
coeffs = model.get_coefficients()
|
||||
a_global = coeffs["a"].numpy()
|
||||
b_global = coeffs["b"].numpy()
|
||||
c_global = coeffs["c"].numpy()
|
||||
|
||||
# Per-window features: how well does the model predict each window?
|
||||
model.eval()
|
||||
|
||||
def _extract(windows_np: np.ndarray) -> np.ndarray:
|
||||
windows_t = torch.tensor(windows_np, dtype=torch.float32)
|
||||
with torch.no_grad():
|
||||
predicted = model(windows_t).numpy()
|
||||
|
||||
n = len(windows_np)
|
||||
feats = np.zeros((n, 6))
|
||||
for i in range(n):
|
||||
w = windows_np[i]
|
||||
p = predicted[i]
|
||||
# Residual between prediction and input
|
||||
residual = p - w
|
||||
feats[i, 0] = residual.mean() # mean shift predicted
|
||||
feats[i, 1] = residual[-1] # shift at end
|
||||
feats[i, 2] = residual.std() # prediction uncertainty
|
||||
feats[i, 3] = np.corrcoef(w, p)[0, 1] # correlation
|
||||
feats[i, 4] = a_global.mean() # diffusion coefficient
|
||||
feats[i, 5] = b_global.mean() # drift coefficient
|
||||
return feats
|
||||
|
||||
return _extract(windows_train), _extract(windows_test)
|
||||
|
||||
|
||||
def extract_technical_features(windows: np.ndarray) -> np.ndarray:
|
||||
"""Approach 3: Classical technical indicators."""
|
||||
n = len(windows)
|
||||
features = np.zeros((n, 7))
|
||||
|
||||
for i, w in enumerate(windows):
|
||||
# RSI (14-period)
|
||||
deltas = np.diff(w[-15:])
|
||||
gains = np.maximum(deltas, 0)
|
||||
losses = np.abs(np.minimum(deltas, 0))
|
||||
avg_gain = gains.mean()
|
||||
avg_loss = losses.mean()
|
||||
if avg_loss < 1e-10:
|
||||
rsi = 100.0
|
||||
else:
|
||||
rs = avg_gain / avg_loss
|
||||
rsi = 100.0 - 100.0 / (1.0 + rs)
|
||||
|
||||
# MA crossover: SMA7 vs SMA21
|
||||
sma7 = w[-7:].mean()
|
||||
sma21 = w[-21:].mean()
|
||||
ma_cross = sma7 - sma21
|
||||
|
||||
# Bollinger Band position
|
||||
sma20 = w[-20:].mean()
|
||||
std20 = w[-20:].std()
|
||||
if std20 > 1e-10:
|
||||
bb_pos = (w[-1] - sma20) / (2 * std20) # -1 to +1 typically
|
||||
else:
|
||||
bb_pos = 0.0
|
||||
|
||||
# Volatility ratio: recent vs historical
|
||||
vol_recent = w[-7:].std()
|
||||
vol_hist = w.std()
|
||||
vol_ratio = vol_recent / (vol_hist + 1e-10)
|
||||
|
||||
# Price relative to SMA50 (or full window mean as proxy)
|
||||
rel_sma = (w[-1] - w.mean()) / (w.std() + 1e-10)
|
||||
|
||||
# MACD-like: difference of EMAs (approximated)
|
||||
ema12 = w[-12:].mean() # simplified
|
||||
ema26 = w[-26:].mean()
|
||||
macd = ema12 - ema26
|
||||
|
||||
# Rate of change (10-day)
|
||||
roc = (w[-1] - w[-10]) / (abs(w[-10]) + 1e-10) * 100
|
||||
|
||||
features[i] = [rsi, ma_cross, bb_pos, vol_ratio, rel_sma, macd, roc]
|
||||
|
||||
return features
|
||||
|
||||
|
||||
def extract_astro_features(dates_list: list[date]) -> tuple[np.ndarray, list[str]]:
|
||||
"""Approach 4: Astrological features for each date."""
|
||||
all_feats = []
|
||||
names = None
|
||||
|
||||
for d in dates_list:
|
||||
feat_dict = compute_features_for_date(d)
|
||||
if names is None:
|
||||
names = list(feat_dict.keys())
|
||||
all_feats.append([feat_dict[k] for k in names])
|
||||
|
||||
return np.array(all_feats), names
|
||||
|
||||
|
||||
# -- Verification Protocol ---------------------------------------------------
|
||||
|
||||
def verify_result(
|
||||
name: str,
|
||||
labels_test: np.ndarray,
|
||||
predictions: np.ndarray,
|
||||
labels_train: np.ndarray,
|
||||
train_preds: np.ndarray,
|
||||
) -> dict:
|
||||
"""Self-verification protocol. Returns verified metrics."""
|
||||
n_test = len(labels_test)
|
||||
n_train = len(labels_train)
|
||||
|
||||
# 1. Compute accuracy
|
||||
test_acc = np.mean(predictions == labels_test)
|
||||
train_acc = np.mean(train_preds == labels_train)
|
||||
|
||||
# 2. Manual check on first 5 samples
|
||||
manual_correct = sum(1 for p, l in zip(predictions[:5], labels_test[:5]) if p == l)
|
||||
manual_acc_5 = manual_correct / min(5, n_test)
|
||||
|
||||
# Cross-check: does computed accuracy roughly match manual sample?
|
||||
# (with 5 samples, tolerance is wide)
|
||||
acc_consistent = abs(test_acc - manual_acc_5) < 0.4 # very loose for 5 samples
|
||||
|
||||
# 3. Class balance check
|
||||
up_ratio_test = labels_test.mean()
|
||||
majority_class_acc = max(up_ratio_test, 1 - up_ratio_test)
|
||||
|
||||
# 4. Binomial test: is accuracy significantly better than majority baseline?
|
||||
n_correct = int(test_acc * n_test)
|
||||
binom_result = stats.binomtest(
|
||||
n_correct, n_test, majority_class_acc, alternative="greater"
|
||||
)
|
||||
binom_p = binom_result.pvalue
|
||||
|
||||
# 5. Overfit check
|
||||
overfit_gap = train_acc - test_acc
|
||||
|
||||
# Build result
|
||||
result = {
|
||||
"name": name,
|
||||
"test_acc": test_acc,
|
||||
"train_acc": train_acc,
|
||||
"majority_baseline": majority_class_acc,
|
||||
"beats_majority": test_acc > majority_class_acc,
|
||||
"binom_p": binom_p,
|
||||
"significant": binom_p < 0.05,
|
||||
"overfit_gap": overfit_gap,
|
||||
"acc_consistent": acc_consistent,
|
||||
"n_test": n_test,
|
||||
}
|
||||
|
||||
# Print
|
||||
print(f"\n{'─' * 50}")
|
||||
print(f" {name}")
|
||||
print(f"{'─' * 50}")
|
||||
print(f" Test accuracy: {test_acc:.1%} ({n_correct}/{n_test})")
|
||||
print(f" Train accuracy: {train_acc:.1%}")
|
||||
print(f" Majority baseline: {majority_class_acc:.1%}")
|
||||
print(f" Beats majority? {'YES' if result['beats_majority'] else 'NO'}")
|
||||
print(f" Binomial p-value: {binom_p:.4f} ({'SIGNIFICANT' if result['significant'] else 'not significant'})")
|
||||
print(f" Overfit gap: {overfit_gap:+.1%} {'(WARNING: overfit)' if overfit_gap > 0.15 else ''}")
|
||||
|
||||
# Verification flags
|
||||
if not acc_consistent:
|
||||
print(f" [WARN] Manual check inconsistent: first-5={manual_acc_5:.1%} vs full={test_acc:.1%}")
|
||||
|
||||
if result["beats_majority"] and not result["significant"]:
|
||||
print(f" [WARN] Beats majority but NOT statistically significant (p={binom_p:.3f})")
|
||||
|
||||
if overfit_gap > 0.2:
|
||||
print(f" [WARN] Large overfit gap ({overfit_gap:.1%}). Result likely unreliable.")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# -- Run Classifiers ---------------------------------------------------------
|
||||
|
||||
def run_classifier(
|
||||
name: str,
|
||||
X_train: np.ndarray,
|
||||
y_train: np.ndarray,
|
||||
X_test: np.ndarray,
|
||||
y_test: np.ndarray,
|
||||
) -> dict:
|
||||
"""Train LogReg + RF, pick better one, run verification."""
|
||||
|
||||
# Handle NaN/Inf in features
|
||||
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)
|
||||
|
||||
scaler = StandardScaler()
|
||||
X_train_s = scaler.fit_transform(X_train)
|
||||
X_test_s = scaler.transform(X_test)
|
||||
|
||||
# LogisticRegression with L1 (feature selection built-in)
|
||||
lr = LogisticRegression(
|
||||
penalty="l1", solver="saga", C=1.0,
|
||||
max_iter=2000, random_state=RANDOM_STATE,
|
||||
)
|
||||
lr.fit(X_train_s, y_train)
|
||||
lr_test_acc = lr.score(X_test_s, y_test)
|
||||
lr_train_acc = lr.score(X_train_s, y_train)
|
||||
|
||||
# RandomForest
|
||||
rf = RandomForestClassifier(
|
||||
n_estimators=100, max_depth=5, min_samples_leaf=5,
|
||||
random_state=RANDOM_STATE,
|
||||
)
|
||||
rf.fit(X_train_s, y_train)
|
||||
rf_test_acc = rf.score(X_test_s, y_test)
|
||||
rf_train_acc = rf.score(X_train_s, y_train)
|
||||
|
||||
# Pick the one with better test accuracy
|
||||
if lr_test_acc >= rf_test_acc:
|
||||
best_name = f"{name} (LogReg)"
|
||||
best_model = lr
|
||||
predictions = lr.predict(X_test_s)
|
||||
train_preds = lr.predict(X_train_s)
|
||||
else:
|
||||
best_name = f"{name} (RF)"
|
||||
best_model = rf
|
||||
predictions = rf.predict(X_test_s)
|
||||
train_preds = rf.predict(X_train_s)
|
||||
|
||||
# Print both for transparency
|
||||
print(f"\n LogReg: train={lr_train_acc:.1%} test={lr_test_acc:.1%}")
|
||||
print(f" RF: train={rf_train_acc:.1%} test={rf_test_acc:.1%}")
|
||||
print(f" Best: {best_name}")
|
||||
|
||||
result = verify_result(best_name, y_test, predictions, y_train, train_preds)
|
||||
result["model"] = best_model
|
||||
result["feature_names"] = None # set externally if needed
|
||||
return result
|
||||
|
||||
|
||||
# -- Main Experiment ---------------------------------------------------------
|
||||
|
||||
def main() -> None:
|
||||
print("=" * 60)
|
||||
print("DIRECTION PREDICTION EXPERIMENT")
|
||||
print("5 approaches to predict BTC up/down")
|
||||
print("=" * 60)
|
||||
|
||||
# 1. Fetch data
|
||||
prices, dates = fetch_btc_with_dates()
|
||||
|
||||
# 2. Create dataset
|
||||
dataset = make_direction_dataset(prices, dates)
|
||||
y_train = dataset["labels_train"]
|
||||
y_test = dataset["labels_test"]
|
||||
|
||||
all_results = []
|
||||
|
||||
# ── Approach 1: Trend Features ────────────────────────────
|
||||
print("\n\n" + "=" * 60)
|
||||
print("APPROACH 1: TREND FEATURES")
|
||||
print("=" * 60)
|
||||
|
||||
X_train_trend = extract_trend_features(dataset["windows_train"])
|
||||
X_test_trend = extract_trend_features(dataset["windows_test"])
|
||||
print(f" Features: {X_train_trend.shape[1]} (slope, momentum, returns, ...)")
|
||||
|
||||
r1 = run_classifier("1-Trend", X_train_trend, y_train, X_test_trend, y_test)
|
||||
all_results.append(r1)
|
||||
|
||||
# ── Approach 2: RemizovNet Coefficients ───────────────────
|
||||
print("\n\n" + "=" * 60)
|
||||
print("APPROACH 2: REMIZOV ODE COEFFICIENTS")
|
||||
print("=" * 60)
|
||||
|
||||
X_train_rem, X_test_rem = extract_remizov_features(
|
||||
dataset["windows_train"], dataset["windows_test"], y_train
|
||||
)
|
||||
print(f" Features: {X_train_rem.shape[1]} (residual stats, a, b coefficients)")
|
||||
|
||||
r2 = run_classifier("2-Remizov", X_train_rem, y_train, X_test_rem, y_test)
|
||||
all_results.append(r2)
|
||||
|
||||
# ── Approach 3: Technical Indicators ──────────────────────
|
||||
print("\n\n" + "=" * 60)
|
||||
print("APPROACH 3: TECHNICAL INDICATORS")
|
||||
print("=" * 60)
|
||||
|
||||
X_train_tech = extract_technical_features(dataset["windows_train"])
|
||||
X_test_tech = extract_technical_features(dataset["windows_test"])
|
||||
print(f" Features: {X_train_tech.shape[1]} (RSI, MA cross, BB, volatility, ...)")
|
||||
|
||||
r3 = run_classifier("3-Technical", X_train_tech, y_train, X_test_tech, y_test)
|
||||
all_results.append(r3)
|
||||
|
||||
# ── Approach 4: Astrological Factors ──────────────────────
|
||||
print("\n\n" + "=" * 60)
|
||||
print("APPROACH 4: ASTROLOGICAL FACTORS")
|
||||
print("=" * 60)
|
||||
|
||||
print(" Computing ephemeris data (this may take a moment)...")
|
||||
X_train_astro, astro_names = extract_astro_features(dataset["dates_train"])
|
||||
X_test_astro, _ = extract_astro_features(dataset["dates_test"])
|
||||
print(f" Features: {X_train_astro.shape[1]} ({len(astro_names)} astrological factors)")
|
||||
|
||||
# Show feature categories
|
||||
n_lon = sum(1 for n in astro_names if n.startswith("lon_"))
|
||||
n_sign = sum(1 for n in astro_names if n.startswith("sign_"))
|
||||
n_retro = sum(1 for n in astro_names if n.startswith("retro_"))
|
||||
n_asp = sum(1 for n in astro_names if n.startswith("asp_"))
|
||||
n_lunar = sum(1 for n in astro_names if "lunar" in n)
|
||||
n_speed = sum(1 for n in astro_names if n.startswith("speed_"))
|
||||
print(f" Longitudes: {n_lon}, Signs: {n_sign}, Retrogrades: {n_retro}")
|
||||
print(f" Aspects: {n_asp}, Lunar: {n_lunar}, Speeds: {n_speed}")
|
||||
|
||||
r4 = run_classifier("4-Astrology", X_train_astro, y_train, X_test_astro, y_test)
|
||||
r4["feature_names"] = astro_names
|
||||
all_results.append(r4)
|
||||
|
||||
# Show top astrological features if RF was used
|
||||
if hasattr(r4["model"], "feature_importances_"):
|
||||
importances = r4["model"].feature_importances_
|
||||
top_idx = np.argsort(importances)[-10:][::-1]
|
||||
print("\n Top 10 astrological features:")
|
||||
for idx in top_idx:
|
||||
print(f" {astro_names[idx]:40s} importance={importances[idx]:.4f}")
|
||||
|
||||
# Also try with L1 LogReg to see which features survive regularization
|
||||
lr_l1 = LogisticRegression(
|
||||
penalty="l1", solver="saga", C=0.5,
|
||||
max_iter=2000, random_state=RANDOM_STATE,
|
||||
)
|
||||
scaler = StandardScaler()
|
||||
X_tr_s = scaler.fit_transform(np.nan_to_num(X_train_astro))
|
||||
lr_l1.fit(X_tr_s, y_train)
|
||||
nonzero = np.where(np.abs(lr_l1.coef_[0]) > 0.01)[0]
|
||||
if len(nonzero) > 0:
|
||||
print(f"\n Astro features surviving L1 regularization ({len(nonzero)}):")
|
||||
for idx in nonzero:
|
||||
print(f" {astro_names[idx]:40s} coef={lr_l1.coef_[0][idx]:+.4f}")
|
||||
else:
|
||||
print("\n No astrological features survive L1 regularization.")
|
||||
|
||||
# ── Approach 5: Combined ──────────────────────────────────
|
||||
print("\n\n" + "=" * 60)
|
||||
print("APPROACH 5: ALL FEATURES COMBINED")
|
||||
print("=" * 60)
|
||||
|
||||
X_train_all = np.hstack([X_train_trend, X_train_rem, X_train_tech, X_train_astro])
|
||||
X_test_all = np.hstack([X_test_trend, X_test_rem, X_test_tech, X_test_astro])
|
||||
print(f" Features: {X_train_all.shape[1]} total")
|
||||
|
||||
r5 = run_classifier("5-Combined", X_train_all, y_train, X_test_all, y_test)
|
||||
all_results.append(r5)
|
||||
|
||||
# ── Summary Table ─────────────────────────────────────────
|
||||
print("\n\n" + "=" * 60)
|
||||
print("SUMMARY")
|
||||
print("=" * 60)
|
||||
print(f"{'Approach':<30s} {'Test Acc':>10s} {'Majority':>10s} {'p-value':>10s} {'Signif?':>8s} {'Overfit':>8s}")
|
||||
print("─" * 76)
|
||||
|
||||
for r in all_results:
|
||||
print(f"{r['name']:<30s} {r['test_acc']:>9.1%} {r['majority_baseline']:>9.1%} "
|
||||
f"{r['binom_p']:>10.4f} {'YES' if r['significant'] else 'no':>8s} "
|
||||
f"{r['overfit_gap']:>+7.1%}")
|
||||
|
||||
# ── Final Verdict ─────────────────────────────────────────
|
||||
print("\n" + "=" * 60)
|
||||
print("FINAL VERDICT")
|
||||
print("=" * 60)
|
||||
|
||||
significant_approaches = [r for r in all_results if r["significant"]]
|
||||
if significant_approaches:
|
||||
best = max(significant_approaches, key=lambda r: r["test_acc"])
|
||||
print(f"Best significant approach: {best['name']} ({best['test_acc']:.1%})")
|
||||
else:
|
||||
print("NO approach achieved statistically significant directional accuracy.")
|
||||
print("This is expected — markets are efficient, and with ~50 test samples")
|
||||
print("even real signal is hard to distinguish from noise.")
|
||||
best_anyway = max(all_results, key=lambda r: r["test_acc"])
|
||||
print(f"\nBest (not significant): {best_anyway['name']} ({best_anyway['test_acc']:.1%})")
|
||||
|
||||
print("\nREMINDER: With small test sets, even statistically significant")
|
||||
print("results may not generalize. Walk-forward validation is needed")
|
||||
print("before any trading decisions.")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,404 @@
|
||||
"""
|
||||
Enhanced direction prediction: 6 RemizovNet variants compared.
|
||||
|
||||
Variants:
|
||||
A. Baseline — original RemizovNet (no enhancements)
|
||||
B. +SDE — learnable noise σ(x)
|
||||
C. +FNO — learnable spectral correction
|
||||
D. +SSM — regime pre-encoder
|
||||
E. +GBM — heteroskedastic data augmentation
|
||||
F. Full — SSM + FNO + SDE + GBM (all combined)
|
||||
|
||||
Each variant:
|
||||
1. Trained on window-pair MSE
|
||||
2. MC inference for stochastic variants (30 samples)
|
||||
3. Features → LogReg/RF → directional accuracy
|
||||
4. Self-verified: accuracy, significance, overfit
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from scipy import stats
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
from data import fetch_btc_daily, make_windows
|
||||
from models import EnhancedRemizovNet, gbm_augment
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
# -- Config ------------------------------------------------------------------
|
||||
|
||||
WINDOW_SIZE = 64
|
||||
SHIFT = 7
|
||||
STRIDE = 7
|
||||
TRAIN_RATIO = 0.8
|
||||
EPOCHS = 400
|
||||
LR = 3e-3
|
||||
N_STEPS = 20
|
||||
TOTAL_TIME = 0.5
|
||||
DX = 1.0 / WINDOW_SIZE
|
||||
MC_SAMPLES = 30 # Monte Carlo samples for stochastic inference
|
||||
RANDOM_STATE = 42
|
||||
|
||||
|
||||
# -- Model Variants ----------------------------------------------------------
|
||||
|
||||
VARIANTS = {
|
||||
"A. Baseline": dict(use_ssm=False, use_fno=False, use_sde=False, use_gbm=False),
|
||||
"B. +SDE": dict(use_ssm=False, use_fno=False, use_sde=True, use_gbm=False),
|
||||
"C. +FNO": dict(use_ssm=False, use_fno=True, use_sde=False, use_gbm=False),
|
||||
"D. +SSM": dict(use_ssm=True, use_fno=False, use_sde=False, use_gbm=False),
|
||||
"E. +GBM": dict(use_ssm=False, use_fno=False, use_sde=False, use_gbm=True),
|
||||
"F. Full": dict(use_ssm=True, use_fno=True, use_sde=True, use_gbm=True),
|
||||
}
|
||||
|
||||
|
||||
# -- Data Pipeline -----------------------------------------------------------
|
||||
|
||||
def prepare_data() -> dict:
|
||||
"""Fetch BTC data and create train/test windows with direction labels."""
|
||||
prices = fetch_btc_daily(period="5y")
|
||||
g_all, y_all = make_windows(prices, WINDOW_SIZE, SHIFT, stride=STRIDE)
|
||||
|
||||
n = len(g_all)
|
||||
split = int(n * TRAIN_RATIO)
|
||||
|
||||
g_train = torch.tensor(g_all[:split], dtype=torch.float32)
|
||||
y_train = torch.tensor(y_all[:split], dtype=torch.float32)
|
||||
g_test = torch.tensor(g_all[split:], dtype=torch.float32)
|
||||
y_test = torch.tensor(y_all[split:], dtype=torch.float32)
|
||||
|
||||
# Direction labels: UP=1 if last point of y > last point of g, else DOWN=0
|
||||
def direction_labels(g: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
|
||||
diff = y[:, -1] - g[:, -1]
|
||||
labels = (diff > 0).long()
|
||||
return labels
|
||||
|
||||
labels_train = direction_labels(g_train, y_train)
|
||||
labels_test = direction_labels(g_test, y_test)
|
||||
|
||||
up_train = labels_train.sum().item()
|
||||
up_test = labels_test.sum().item()
|
||||
print(f"Train: {split} samples ({up_train} up / {split - up_train} down)")
|
||||
print(f"Test: {n - split} samples ({up_test} up / {n - split - up_test} down)")
|
||||
|
||||
return {
|
||||
"g_train": g_train, "y_train": y_train,
|
||||
"g_test": g_test, "y_test": y_test,
|
||||
"labels_train": labels_train, "labels_test": labels_test,
|
||||
}
|
||||
|
||||
|
||||
# -- Training ----------------------------------------------------------------
|
||||
|
||||
def train_model(
|
||||
model: EnhancedRemizovNet,
|
||||
g_train: torch.Tensor,
|
||||
y_train: torch.Tensor,
|
||||
epochs: int = EPOCHS,
|
||||
) -> list[float]:
|
||||
"""Train on window-pair MSE loss."""
|
||||
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()
|
||||
batch_size = min(128, len(g_train))
|
||||
loss_history = []
|
||||
|
||||
for epoch in range(epochs):
|
||||
model.train()
|
||||
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_b = g_train[idx]
|
||||
y_b = y_train[idx]
|
||||
|
||||
optimizer.zero_grad()
|
||||
y_pred = model(g_b, stochastic=model.layer.use_sde)
|
||||
loss = criterion(y_pred, y_b)
|
||||
loss.backward()
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
||||
optimizer.step()
|
||||
|
||||
epoch_loss += loss.item()
|
||||
n_batches += 1
|
||||
|
||||
avg = epoch_loss / n_batches
|
||||
loss_history.append(avg)
|
||||
scheduler.step(avg)
|
||||
|
||||
return loss_history
|
||||
|
||||
|
||||
# -- Feature Extraction via MC Inference -------------------------------------
|
||||
|
||||
def extract_features(
|
||||
model: EnhancedRemizovNet,
|
||||
g: torch.Tensor,
|
||||
is_stochastic: bool,
|
||||
) -> np.ndarray:
|
||||
"""Extract direction-relevant features from model predictions.
|
||||
|
||||
For stochastic models: run MC_SAMPLES forward passes, compute mean + std.
|
||||
For deterministic: single pass.
|
||||
|
||||
Features per sample:
|
||||
0. mean_shift: mean(pred - input)
|
||||
1. end_shift: pred[-1] - input[-1] (key direction signal)
|
||||
2. pred_std: mean std across MC samples (uncertainty)
|
||||
3. end_std: std at last point (endpoint uncertainty)
|
||||
4. slope_pred: linear slope of prediction
|
||||
5. momentum: pred[-1] - pred.mean()
|
||||
"""
|
||||
model.eval() # ensure eval mode for non-SDE layers
|
||||
|
||||
if is_stochastic:
|
||||
preds = []
|
||||
for _ in range(MC_SAMPLES):
|
||||
with torch.no_grad():
|
||||
preds.append(model(g, stochastic=True))
|
||||
preds = torch.stack(preds) # (MC, batch, grid)
|
||||
mean_pred = preds.mean(0).numpy()
|
||||
std_pred = preds.std(0).numpy()
|
||||
else:
|
||||
with torch.no_grad():
|
||||
mean_pred = model(g, stochastic=False).numpy()
|
||||
std_pred = np.zeros_like(mean_pred)
|
||||
|
||||
g_np = g.numpy()
|
||||
n = len(g_np)
|
||||
features = np.zeros((n, 6))
|
||||
|
||||
for i in range(n):
|
||||
diff = mean_pred[i] - g_np[i]
|
||||
features[i, 0] = diff.mean() # mean shift
|
||||
features[i, 1] = diff[-1] # end shift
|
||||
features[i, 2] = std_pred[i].mean() # mean uncertainty
|
||||
features[i, 3] = std_pred[i, -1] # end uncertainty
|
||||
# Slope of prediction
|
||||
x = np.arange(WINDOW_SIZE)
|
||||
features[i, 4] = np.polyfit(x, mean_pred[i], 1)[0]
|
||||
features[i, 5] = mean_pred[i, -1] - mean_pred[i].mean() # momentum
|
||||
|
||||
return features
|
||||
|
||||
|
||||
# -- Evaluation with Self-Verification --------------------------------------
|
||||
|
||||
def evaluate_direction(
|
||||
name: str,
|
||||
X_train: np.ndarray,
|
||||
y_train: np.ndarray,
|
||||
X_test: np.ndarray,
|
||||
y_test: np.ndarray,
|
||||
) -> dict:
|
||||
"""Train classifier, evaluate, self-verify."""
|
||||
|
||||
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)
|
||||
|
||||
scaler = StandardScaler()
|
||||
Xtr = scaler.fit_transform(X_train)
|
||||
Xte = scaler.transform(X_test)
|
||||
|
||||
# LogReg
|
||||
lr = LogisticRegression(
|
||||
penalty="l1", solver="saga", C=1.0, l1_ratio=1.0,
|
||||
max_iter=2000, random_state=RANDOM_STATE,
|
||||
)
|
||||
lr.fit(Xtr, y_train)
|
||||
lr_test = lr.score(Xte, y_test)
|
||||
lr_train = lr.score(Xtr, y_train)
|
||||
|
||||
# RF
|
||||
rf = RandomForestClassifier(
|
||||
n_estimators=100, max_depth=4, min_samples_leaf=5,
|
||||
random_state=RANDOM_STATE,
|
||||
)
|
||||
rf.fit(Xtr, y_train)
|
||||
rf_test = rf.score(Xte, y_test)
|
||||
rf_train = rf.score(Xtr, y_train)
|
||||
|
||||
# Pick best on test
|
||||
if lr_test >= rf_test:
|
||||
best_name, test_acc, train_acc = "LR", lr_test, lr_train
|
||||
preds = lr.predict(Xte)
|
||||
train_preds = lr.predict(Xtr)
|
||||
else:
|
||||
best_name, test_acc, train_acc = "RF", rf_test, rf_train
|
||||
preds = rf.predict(Xte)
|
||||
train_preds = rf.predict(Xtr)
|
||||
|
||||
n_test = len(y_test)
|
||||
n_correct = int(test_acc * n_test)
|
||||
majority = max(y_test.mean(), 1 - y_test.mean())
|
||||
|
||||
# Binomial test
|
||||
binom_result = stats.binomtest(n_correct, n_test, majority, alternative="greater")
|
||||
p_val = binom_result.pvalue
|
||||
|
||||
overfit = train_acc - test_acc
|
||||
|
||||
# --- Self-verification ---
|
||||
# 1. Manual accuracy check on first 5
|
||||
manual_ok = sum(1 for p, l in zip(preds[:5], y_test[:5]) if p == l)
|
||||
manual_acc = manual_ok / min(5, n_test)
|
||||
|
||||
# 2. Check for "always same class" degenerate
|
||||
unique_preds = len(set(preds))
|
||||
is_degenerate = unique_preds == 1
|
||||
|
||||
# 3. Feature variance check (all-zero features are useless)
|
||||
n_zero_var = sum(1 for j in range(X_test.shape[1]) if X_test[:, j].std() < 1e-10)
|
||||
|
||||
result = {
|
||||
"name": name,
|
||||
"classifier": best_name,
|
||||
"test_acc": test_acc,
|
||||
"train_acc": train_acc,
|
||||
"majority": majority,
|
||||
"beats_majority": test_acc > majority,
|
||||
"p_value": p_val,
|
||||
"significant": p_val < 0.05,
|
||||
"overfit": overfit,
|
||||
}
|
||||
|
||||
# Print with verification
|
||||
print(f"\n{'─' * 55}")
|
||||
print(f" {name} ({best_name}) "
|
||||
f"LR={lr_test:.1%} RF={rf_test:.1%}")
|
||||
print(f"{'─' * 55}")
|
||||
print(f" Test: {test_acc:.1%} ({n_correct}/{n_test})")
|
||||
print(f" Train: {train_acc:.1%}")
|
||||
print(f" Majority: {majority:.1%} {'BEATS' if result['beats_majority'] else 'no'}")
|
||||
print(f" p-value: {p_val:.4f} {'** SIGNIFICANT **' if p_val < 0.05 else ''}")
|
||||
print(f" Overfit: {overfit:+.1%}")
|
||||
|
||||
# Verification warnings
|
||||
if is_degenerate:
|
||||
print(f" [WARN] Degenerate: predicts only class {preds[0]} for all samples")
|
||||
if n_zero_var > 0:
|
||||
print(f" [WARN] {n_zero_var}/{X_test.shape[1]} features have zero variance")
|
||||
if overfit > 0.20:
|
||||
print(f" [WARN] Large overfit gap ({overfit:.1%})")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# -- Main Experiment ---------------------------------------------------------
|
||||
|
||||
def main() -> None:
|
||||
print("=" * 60)
|
||||
print("ENHANCED DIRECTION PREDICTION")
|
||||
print("6 RemizovNet variants + arxiv enhancements")
|
||||
print("=" * 60)
|
||||
|
||||
# 1. Data
|
||||
data = prepare_data()
|
||||
g_train = data["g_train"]
|
||||
y_train = data["y_train"]
|
||||
g_test = data["g_test"]
|
||||
y_test = data["y_test"]
|
||||
labels_train = data["labels_train"].numpy()
|
||||
labels_test = data["labels_test"].numpy()
|
||||
|
||||
all_results = []
|
||||
|
||||
for variant_name, flags in VARIANTS.items():
|
||||
print(f"\n\n{'=' * 60}")
|
||||
print(f" {variant_name}")
|
||||
print(f" SSM={flags['use_ssm']} FNO={flags['use_fno']} "
|
||||
f"SDE={flags['use_sde']} GBM={flags['use_gbm']}")
|
||||
print(f"{'=' * 60}")
|
||||
|
||||
# Create model
|
||||
model = EnhancedRemizovNet(
|
||||
grid_size=WINDOW_SIZE,
|
||||
n_steps=N_STEPS,
|
||||
total_time=TOTAL_TIME,
|
||||
dx=DX,
|
||||
use_ssm=flags["use_ssm"],
|
||||
use_fno=flags["use_fno"],
|
||||
use_sde=flags["use_sde"],
|
||||
)
|
||||
print(f" Parameters: {model.param_count()}")
|
||||
|
||||
# Prepare training data (with optional GBM augmentation)
|
||||
if flags["use_gbm"]:
|
||||
g_tr, y_tr, lbl_tr = gbm_augment(g_train, y_train, data["labels_train"])
|
||||
print(f" GBM augmented: {len(g_train)} → {len(g_tr)} samples")
|
||||
else:
|
||||
g_tr, y_tr = g_train, y_train
|
||||
|
||||
# Train
|
||||
t0 = time.time()
|
||||
loss_hist = train_model(model, g_tr, y_tr, epochs=EPOCHS)
|
||||
elapsed = time.time() - t0
|
||||
print(f" Trained in {elapsed:.1f}s, final loss={loss_hist[-1]:.6f}")
|
||||
print(f" Equation: {model.equation_string()}")
|
||||
|
||||
# Extract features
|
||||
is_stochastic = flags["use_sde"]
|
||||
feat_train = extract_features(model, g_train, is_stochastic)
|
||||
feat_test = extract_features(model, g_test, is_stochastic)
|
||||
|
||||
# Direction evaluation
|
||||
result = evaluate_direction(
|
||||
variant_name, feat_train, labels_train, feat_test, labels_test,
|
||||
)
|
||||
result["loss"] = loss_hist[-1]
|
||||
result["params"] = model.param_count()
|
||||
result["time"] = elapsed
|
||||
all_results.append(result)
|
||||
|
||||
# -- Summary Table -------------------------------------------------------
|
||||
print("\n\n" + "=" * 60)
|
||||
print("SUMMARY TABLE")
|
||||
print("=" * 60)
|
||||
print(f"{'Variant':<18s} {'Acc':>6s} {'Maj':>6s} {'p-val':>8s} "
|
||||
f"{'Sig':>5s} {'Ofit':>6s} {'Params':>7s} {'MSE':>9s}")
|
||||
print("─" * 75)
|
||||
|
||||
for r in all_results:
|
||||
sig = "**" if r["significant"] else ""
|
||||
print(f"{r['name']:<18s} {r['test_acc']:>5.1%} {r['majority']:>5.1%} "
|
||||
f"{r['p_value']:>8.4f} {sig:>5s} {r['overfit']:>+5.1%} "
|
||||
f"{r['params']:>7d} {r['loss']:>9.5f}")
|
||||
|
||||
# -- Best result ---------------------------------------------------------
|
||||
print("\n" + "=" * 60)
|
||||
|
||||
sig_results = [r for r in all_results if r["significant"]]
|
||||
if sig_results:
|
||||
best = max(sig_results, key=lambda r: r["test_acc"])
|
||||
print(f"BEST SIGNIFICANT: {best['name']} — {best['test_acc']:.1%} (p={best['p_value']:.4f})")
|
||||
else:
|
||||
best = max(all_results, key=lambda r: r["test_acc"])
|
||||
print(f"BEST (not significant): {best['name']} — {best['test_acc']:.1%}")
|
||||
print("No variant achieved p < 0.05. With ~50 test samples,")
|
||||
print("significance requires >~70% accuracy.")
|
||||
|
||||
# Honest assessment
|
||||
print("\nSELF-VERIFICATION SUMMARY:")
|
||||
any_degenerate = any(r["test_acc"] == r["majority"] for r in all_results)
|
||||
any_overfit = any(r["overfit"] > 0.20 for r in all_results)
|
||||
print(f" Degenerate predictions: {'YES — check warnings above' if any_degenerate else 'None'}")
|
||||
print(f" Severe overfitting: {'YES — check warnings above' if any_overfit else 'None'}")
|
||||
print(f" Test set size: {len(labels_test)} (small — results are noisy)")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
"""
|
||||
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()
|
||||
@@ -0,0 +1,472 @@
|
||||
"""
|
||||
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()
|
||||
@@ -0,0 +1,488 @@
|
||||
"""
|
||||
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()
|
||||
@@ -0,0 +1,310 @@
|
||||
"""
|
||||
Enhanced RemizovNet variants for crypto direction prediction.
|
||||
|
||||
4 enhancements from arxiv research:
|
||||
1. Neural SDE — learnable σ(x) noise in Chernoff steps
|
||||
2. Learnable FNO — spectral correction on top of physics kernel
|
||||
3. Diagonal SSM — state space regime encoder
|
||||
4. GBM augmentation — heteroskedastic data augmentation (in experiment.py)
|
||||
|
||||
All enhancements are toggleable via flags for clean ablation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as f_nn
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Diagonal SSM — regime encoder
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class DiagonalSSM(nn.Module):
|
||||
"""Diagonal State Space Model for regime detection.
|
||||
|
||||
Captures long-range dependencies via learned decay rates.
|
||||
Computed efficiently via FFT convolution (not sequential).
|
||||
|
||||
Architecture: S4D-style diagonal SSM with skip connection.
|
||||
y[n] = sum_d C[d] * A[d]^n * B[d] (conv with input) + D * x[n]
|
||||
"""
|
||||
|
||||
def __init__(self, d_state: int = 8):
|
||||
super().__init__()
|
||||
self.d_state = d_state
|
||||
|
||||
# Decay rates in log-space (negative → stable, in (0,1) after exp)
|
||||
# HiPPO-inspired initialization: different timescales
|
||||
self.log_A = nn.Parameter(torch.linspace(-0.1, -2.0, d_state))
|
||||
|
||||
# Input-to-state and state-to-output projections
|
||||
self.B = nn.Parameter(torch.randn(d_state) * 0.1)
|
||||
self.C = nn.Parameter(torch.randn(d_state) * 0.1)
|
||||
|
||||
# Skip connection (initialized to 1 = identity at start)
|
||||
self.D = nn.Parameter(torch.ones(1))
|
||||
|
||||
def forward(self, x: Tensor) -> Tensor:
|
||||
"""
|
||||
Args:
|
||||
x: (batch, seq_len) — input sequence.
|
||||
Returns:
|
||||
(batch, seq_len) — regime-modulated output.
|
||||
"""
|
||||
L = x.shape[1]
|
||||
device = x.device
|
||||
|
||||
A = torch.exp(self.log_A) # decay rates in (0, 1)
|
||||
|
||||
# Build causal convolution kernel: K[n] = sum_d C[d] * A[d]^n * B[d]
|
||||
n = torch.arange(L, device=device, dtype=x.dtype)
|
||||
# A^n for each state dim: (L, d_state)
|
||||
A_powers = A.unsqueeze(0) ** n.unsqueeze(1)
|
||||
# K[n] = sum over d_state
|
||||
CB = self.C * self.B # (d_state,)
|
||||
K = (A_powers * CB.unsqueeze(0)).sum(dim=1) # (L,)
|
||||
|
||||
# Causal convolution via FFT (pad to avoid circular)
|
||||
fft_size = 2 * L
|
||||
K_f = torch.fft.rfft(K, n=fft_size)
|
||||
x_f = torch.fft.rfft(x, n=fft_size, dim=-1)
|
||||
y = torch.fft.irfft(x_f * K_f.unsqueeze(0), n=fft_size, dim=-1)[..., :L]
|
||||
|
||||
return y + self.D * x
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2+3. Enhanced Chernoff Layer (FNO + SDE)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class EnhancedRemizovLayer(nn.Module):
|
||||
"""Chernoff step with optional FNO spectral correction and SDE noise.
|
||||
|
||||
Base physics: S(τ) = S₃(τ) · S₂(τ)
|
||||
+ FNO: learnable spectral correction on S₂ kernel
|
||||
+ SDE: learnable σ(x)·√τ·ε noise injection after S₃
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
grid_size: int,
|
||||
tau: float = 0.1,
|
||||
dx: float = 1.0,
|
||||
use_fno: bool = False,
|
||||
use_sde: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
self.grid_size = grid_size
|
||||
self.tau = tau
|
||||
self.dx = dx
|
||||
self.use_fno = use_fno
|
||||
self.use_sde = use_sde
|
||||
|
||||
# --- ODE coefficients (same as original) ---
|
||||
self.log_a = nn.Parameter(torch.zeros(grid_size))
|
||||
self.b = nn.Parameter(torch.zeros(grid_size))
|
||||
self.c = nn.Parameter(torch.zeros(grid_size))
|
||||
|
||||
# --- FNO: learnable spectral correction ---
|
||||
if use_fno:
|
||||
# Correction applied as: kernel = physics_kernel * (1 + correction)
|
||||
# Initialized to 0 → starts exactly as physics kernel
|
||||
self.fno_real = nn.Parameter(torch.zeros(grid_size))
|
||||
self.fno_imag = nn.Parameter(torch.zeros(grid_size))
|
||||
|
||||
# --- SDE: learnable volatility ---
|
||||
if use_sde:
|
||||
# Start with small noise: softplus(-3) ≈ 0.05
|
||||
self.log_sigma = nn.Parameter(torch.full((grid_size,), -3.0))
|
||||
|
||||
@property
|
||||
def a(self) -> Tensor:
|
||||
return f_nn.softplus(self.log_a) + 1e-6
|
||||
|
||||
@property
|
||||
def potential(self) -> Tensor:
|
||||
return self.c - self.b ** 2 / (4.0 * self.a)
|
||||
|
||||
@property
|
||||
def sigma(self) -> Tensor:
|
||||
return f_nn.softplus(self.log_sigma) + 1e-6
|
||||
|
||||
def _apply_s2(self, f: Tensor) -> Tensor:
|
||||
"""S₂ with optional FNO spectral correction."""
|
||||
a_mean = self.a.mean()
|
||||
b_mean = self.b.mean()
|
||||
sigma2 = 4.0 * self.tau * a_mean
|
||||
|
||||
k = torch.fft.fftfreq(self.grid_size, d=self.dx, device=f.device)
|
||||
|
||||
# Physics-based kernel
|
||||
gauss_ft = torch.exp(-sigma2 * (math.pi * k) ** 2)
|
||||
drift_ft = torch.exp(2j * math.pi * k * b_mean * self.tau)
|
||||
kernel = gauss_ft * drift_ft
|
||||
|
||||
# FNO correction: kernel *= (1 + learned_correction)
|
||||
if self.use_fno:
|
||||
correction = torch.complex(
|
||||
1.0 + self.fno_real,
|
||||
self.fno_imag,
|
||||
)
|
||||
kernel = kernel * correction
|
||||
|
||||
f_ft = torch.fft.fft(f, dim=-1)
|
||||
result = torch.fft.ifft(f_ft * kernel.unsqueeze(0), dim=-1).real
|
||||
|
||||
# Completion-of-square factor
|
||||
completion = torch.exp(self.b ** 2 * self.tau / (4.0 * self.a))
|
||||
result = result * completion.unsqueeze(0)
|
||||
|
||||
return result
|
||||
|
||||
def _apply_s3(self, f: Tensor) -> Tensor:
|
||||
return f * torch.exp(self.tau * self.potential).unsqueeze(0)
|
||||
|
||||
def forward(self, f: Tensor, stochastic: bool = True) -> Tensor:
|
||||
"""One Chernoff step: S₃ · S₂ + optional noise."""
|
||||
f = self._apply_s2(f)
|
||||
f = self._apply_s3(f)
|
||||
|
||||
# SDE noise injection: σ(x) · √τ · ε
|
||||
if self.use_sde and stochastic:
|
||||
noise = torch.randn_like(f) * self.sigma.unsqueeze(0) * math.sqrt(self.tau)
|
||||
f = f + noise
|
||||
|
||||
return f
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Combined model
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class EnhancedRemizovNet(nn.Module):
|
||||
"""RemizovNet with configurable SSM/FNO/SDE enhancements.
|
||||
|
||||
Architecture:
|
||||
[SSM encoder] → [EnhancedChernoffLayer × n_steps] → output
|
||||
|
||||
Each enhancement is toggleable for clean ablation studies.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
grid_size: int,
|
||||
n_steps: int = 20,
|
||||
total_time: float = 0.5,
|
||||
dx: float = 1.0,
|
||||
use_ssm: bool = False,
|
||||
use_fno: bool = False,
|
||||
use_sde: bool = False,
|
||||
d_state: int = 8,
|
||||
):
|
||||
super().__init__()
|
||||
self.grid_size = grid_size
|
||||
self.n_steps = n_steps
|
||||
self.use_ssm = use_ssm
|
||||
|
||||
tau = total_time / n_steps
|
||||
|
||||
# SSM regime encoder
|
||||
if use_ssm:
|
||||
self.ssm = DiagonalSSM(d_state=d_state)
|
||||
|
||||
# Shared Chernoff layer (all steps share weights)
|
||||
self.layer = EnhancedRemizovLayer(
|
||||
grid_size, tau=tau, dx=dx,
|
||||
use_fno=use_fno, use_sde=use_sde,
|
||||
)
|
||||
|
||||
def forward(self, g: Tensor, stochastic: bool = True) -> Tensor:
|
||||
"""
|
||||
Args:
|
||||
g: (batch, grid_size) — input windows.
|
||||
stochastic: whether to inject SDE noise.
|
||||
Returns:
|
||||
(batch, grid_size) — predicted evolved windows.
|
||||
"""
|
||||
f = g
|
||||
|
||||
# SSM pre-processing
|
||||
if self.use_ssm:
|
||||
f = self.ssm(f)
|
||||
|
||||
# Chernoff composition
|
||||
for _ in range(self.n_steps):
|
||||
f = self.layer(f, stochastic=stochastic)
|
||||
|
||||
return f
|
||||
|
||||
def get_coefficients(self) -> dict[str, Tensor]:
|
||||
return {
|
||||
"a": self.layer.a.detach(),
|
||||
"b": self.layer.b.detach(),
|
||||
"c": self.layer.c.detach(),
|
||||
}
|
||||
|
||||
def equation_string(self, precision: int = 3) -> str:
|
||||
coeffs = self.get_coefficients()
|
||||
a_m = coeffs["a"].mean().item()
|
||||
b_m = coeffs["b"].mean().item()
|
||||
c_m = coeffs["c"].mean().item()
|
||||
parts = [f"{a_m:.{precision}f}*y''", f"{b_m:.{precision}f}*y'", f"({c_m:.{precision}f})*y"]
|
||||
eq = " + ".join(parts) + " = g(x)"
|
||||
if hasattr(self.layer, "log_sigma"):
|
||||
s_m = self.layer.sigma.mean().item()
|
||||
eq += f" [sigma={s_m:.{precision}f}]"
|
||||
return eq
|
||||
|
||||
def param_count(self) -> int:
|
||||
return sum(p.numel() for p in self.parameters())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GBM-style data augmentation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def gbm_augment(
|
||||
g_windows: Tensor,
|
||||
y_windows: Tensor,
|
||||
labels: Tensor,
|
||||
n_aug: int = 2,
|
||||
noise_scale: float = 0.15,
|
||||
) -> tuple[Tensor, Tensor, Tensor]:
|
||||
"""Heteroskedastic data augmentation mimicking GBM properties.
|
||||
|
||||
Noise magnitude is proportional to local price changes (volatility),
|
||||
matching the heteroskedasticity of financial time series.
|
||||
|
||||
Args:
|
||||
g_windows: input windows (n, grid).
|
||||
y_windows: target windows (n, grid).
|
||||
labels: direction labels (n,).
|
||||
n_aug: number of augmented copies.
|
||||
noise_scale: base noise magnitude.
|
||||
|
||||
Returns:
|
||||
Augmented (g, y, labels) with (1 + n_aug) × n samples.
|
||||
"""
|
||||
aug_g = [g_windows]
|
||||
aug_y = [y_windows]
|
||||
aug_labels = [labels]
|
||||
|
||||
for _ in range(n_aug):
|
||||
# Local volatility: |diff| of window, with floor
|
||||
diff_g = torch.diff(g_windows, dim=-1, prepend=g_windows[..., :1])
|
||||
local_vol = torch.abs(diff_g).clamp(min=0.05)
|
||||
|
||||
# Additive noise scaled by local volatility (heteroskedastic)
|
||||
noise_g = torch.randn_like(g_windows) * local_vol * noise_scale
|
||||
noise_y = torch.randn_like(y_windows) * local_vol * noise_scale
|
||||
|
||||
aug_g.append(g_windows + noise_g)
|
||||
aug_y.append(y_windows + noise_y)
|
||||
aug_labels.append(labels.clone())
|
||||
|
||||
return torch.cat(aug_g), torch.cat(aug_y), torch.cat(aug_labels)
|
||||
@@ -0,0 +1,6 @@
|
||||
numpy>=1.26
|
||||
scipy>=1.12
|
||||
torch>=2.2
|
||||
matplotlib>=3.8
|
||||
yfinance>=0.2.36
|
||||
remizov-net @ file:///Users/alchemist/Python_projects/remizov-net
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 310 KiB |
Reference in New Issue
Block a user