feat: кэш обученных моделей в бэктесте (40с → 6с)

common/dataset.py: save_cached_model/load_cached_model по ключу
(dataset + ticker + ws + shift + train_ratio).
exp19: автоматически кэширует при первом запуске, потом загружает.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-10 20:45:54 +10:00
co-authored by Claude Opus 4.6
parent eceb766893
commit 74bbef3356
2 changed files with 55 additions and 7 deletions
+41
View File
@@ -103,3 +103,44 @@ def load_or_fetch(name: str = "default") -> dict:
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