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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user