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
|
||||
|
||||
@@ -27,7 +27,7 @@ import torch
|
||||
from remizov_trader.core import model as model_mod, signals, risk
|
||||
from remizov_trader.config import ModelConfig
|
||||
from common.metrics import compute_metrics, save_results
|
||||
from common.dataset import load_or_fetch
|
||||
from common.dataset import load_or_fetch, load_cached_model, save_cached_model
|
||||
|
||||
TOTAL_CAPITAL = 114.0
|
||||
K = 2
|
||||
@@ -207,12 +207,19 @@ def main():
|
||||
window_size=ws, n_steps=20, total_time=0.5,
|
||||
shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003,
|
||||
)
|
||||
torch.manual_seed(42)
|
||||
np.random.seed(42)
|
||||
mdl = model_mod.create_model(model_cfg)
|
||||
windows_arr = np.array([d["norm_input"] for d in train_data])
|
||||
targets_arr = np.array([d["norm_target"] for d in train_data])
|
||||
model_mod.train(mdl, windows_arr, targets_arr, 200, 0.003)
|
||||
|
||||
# Try loading cached model (same dataset + params = same result)
|
||||
mdl = load_cached_model(model_cfg, ticker, ws, SHIFT, TRAIN_RATIO)
|
||||
if mdl is not None:
|
||||
print(f"(cached) ", end="")
|
||||
else:
|
||||
torch.manual_seed(42)
|
||||
np.random.seed(42)
|
||||
mdl = model_mod.create_model(model_cfg)
|
||||
windows_arr = np.array([d["norm_input"] for d in train_data])
|
||||
targets_arr = np.array([d["norm_target"] for d in train_data])
|
||||
model_mod.train(mdl, windows_arr, targets_arr, 200, 0.003)
|
||||
save_cached_model(mdl, ticker, ws, SHIFT, TRAIN_RATIO)
|
||||
|
||||
asset_data[ticker] = {
|
||||
"prices": prices, "dates": dates, "tf": tf,
|
||||
|
||||
Reference in New Issue
Block a user