"""Fixed dataset management for reproducible experiments. Save once with save_dataset.py, then load in any experiment. """ import json from pathlib import Path import numpy as np DATA_DIR = Path(__file__).parent.parent / "data" ASSETS = [ {"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241}, {"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158}, {"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.183}, {"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.183}, {"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127}, {"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108}, ] def save_dataset(name: str = "default") -> Path: """Fetch all assets from exchange and save as fixed dataset.""" import sys sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) from remizov_trader.core.signals import fetch_ohlcv_ccxt DATA_DIR.mkdir(parents=True, exist_ok=True) dataset_dir = DATA_DIR / name dataset_dir.mkdir(parents=True, exist_ok=True) meta = {"assets": {}} for a in ASSETS: ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"] print(f" Fetching {ticker} ({tf})...", end=" ", flush=True) ohlcv, dates = fetch_ohlcv_ccxt(symbol, tf, "max") if ohlcv is None or len(ohlcv) < 100: print("SKIP (not enough data)") continue prices = ohlcv[:, 3] # close column # Save prices (backward compat) + full OHLCV np.save(dataset_dir / f"{ticker}_prices.npy", prices) np.save(dataset_dir / f"{ticker}_ohlcv.npy", ohlcv) dates_str = [str(d) for d in dates] (dataset_dir / f"{ticker}_dates.json").write_text(json.dumps(dates_str)) meta["assets"][ticker] = { "symbol": symbol, "tf": tf, "ws": a["ws"], "leverage": a["leverage"], "weight": a["weight"], "bars": len(prices), "date_range": f"{dates_str[0]} -> {dates_str[-1]}", } print(f"{len(prices)} bars ({dates_str[0][:10]} -> {dates_str[-1][:10]})") from datetime import datetime meta["created"] = datetime.now().isoformat() meta["name"] = name (dataset_dir / "meta.json").write_text(json.dumps(meta, indent=2)) print(f"\nDataset saved: {dataset_dir}") return dataset_dir def load_dataset(name: str = "default") -> dict: """Load fixed dataset. Returns dict[ticker] -> {prices, dates, tf, ws, ...}.""" dataset_dir = DATA_DIR / name if not dataset_dir.exists(): raise FileNotFoundError( f"Dataset '{name}' not found at {dataset_dir}. " f"Run: .venv/bin/python3 experiments/common/save_dataset.py" ) meta_path = dataset_dir / "meta.json" meta = json.loads(meta_path.read_text()) result = {} for ticker, info in meta["assets"].items(): prices = np.load(dataset_dir / f"{ticker}_prices.npy") dates_str = json.loads((dataset_dir / f"{ticker}_dates.json").read_text()) # Convert to numpy array of date strings for compatibility dates = np.array(dates_str) ohlcv_path = dataset_dir / f"{ticker}_ohlcv.npy" ohlcv = np.load(ohlcv_path) if ohlcv_path.exists() else None result[ticker] = { "prices": prices, "ohlcv": ohlcv, # (N,4) [O,H,L,C] or None for old datasets "dates": dates, "tf": info["tf"], "ws": info["ws"], "leverage": info["leverage"], "weight": info["weight"], } return result def load_or_fetch(name: str = "default") -> dict: """Load dataset if exists, otherwise fetch and save.""" try: return load_dataset(name) except FileNotFoundError: print(f"Dataset '{name}' not found, fetching from exchange...") save_dataset(name) return load_dataset(name) # ══════════════════════════════════════════════════ # MODEL CACHE — train once per dataset, reuse across runs # ══════════════════════════════════════════════════ MODELS_CACHE_DIR = DATA_DIR / "models_cache" def _model_cache_key(ticker: str, ws: int, shift: int, train_ratio: float, dataset_name: str) -> str: """Deterministic cache key for a trained model.""" return f"{dataset_name}_{ticker}_ws{ws}_sh{shift}_tr{train_ratio}" def save_cached_model(model, ticker: str, ws: int, shift: int, train_ratio: float, dataset_name: str = "default") -> Path: """Save trained model to cache.""" import torch MODELS_CACHE_DIR.mkdir(parents=True, exist_ok=True) key = _model_cache_key(ticker, ws, shift, train_ratio, dataset_name) fpath = MODELS_CACHE_DIR / f"{key}.pt" torch.save(model.state_dict(), fpath) return fpath def load_cached_model(model_cfg, ticker: str, ws: int, shift: int, train_ratio: float, dataset_name: str = "default"): """Load cached model if exists. Returns model or None.""" import sys sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) import torch from remizov_trader.core.model import create_model key = _model_cache_key(ticker, ws, shift, train_ratio, dataset_name) fpath = MODELS_CACHE_DIR / f"{key}.pt" if not fpath.exists(): return None model = create_model(model_cfg) model.load_state_dict(torch.load(fpath, weights_only=True)) return model