multi-asset-predictive-model / batch_train_lstm.py
AcyLa's picture
Upload batch_train_lstm.py with huggingface_hub
50e751a verified
Raw History Blame Contribute Delete
2.6 kB
"""Batch train LSTM models for all assets."""
import os, sys, json, time, traceback
import numpy as np, pandas as pd, joblib, torch
from config import cfg
from data_loader import download, download_all, get_asset_name
from features import build_all_features, get_feature_columns
from labels import add_all_labels
from models import LSTMPredictor
from backtest import quick_split, evaluate_predictions
import warnings; warnings.filterwarnings('ignore')
def train_lstm_one(ticker, all_data):
try:
df = all_data.get(ticker)
if df is None or len(df) < 500:
return None
df = build_all_features(df, ticker=ticker, all_data=all_data)
df = add_all_labels(df)
feature_cols = get_feature_columns(df)
feature_cols = [c for c in feature_cols if not df[c].isna().all()]
# Load existing feature_cols to ensure consistency
fc_path = os.path.join(cfg.model_dir, ticker, 'feature_cols.joblib')
if os.path.exists(fc_path):
saved_fc = joblib.load(fc_path)
# Use saved feature cols, adding any missing as zeros
for c in saved_fc:
if c not in df.columns: df[c] = 0.0
feature_cols = saved_fc
clean = df.dropna(subset=feature_cols, how='any')
splits = quick_split(len(clean))
tr_s, tr_e, va_s, va_e, te_s, te_e = splits[0]
tr, va, te = clean.iloc[tr_s:tr_e], clean.iloc[va_s:va_e], clean.iloc[te_s:te_e]
results = []
for h in cfg.horizons:
model = LSTMPredictor(horizon=h)
model.train(tr, va, feature_cols)
preds = model.predict(te)
tgt = f'Target_Return_{h}'
y = te[tgt].values; m = ~np.isnan(y) & ~np.isnan(preds)
metrics = evaluate_predictions(y[m], preds[m])
metrics.update({'horizon': h, 'ticker': ticker})
results.append(metrics)
# Save LSTM model
md = os.path.join(cfg.model_dir, ticker)
model.save(os.path.join(md, f'lstm_h{h}.pt'))
print(f' {ticker} LSTM h={h}: Dir.Acc={metrics["dir_acc"]:.1%} Sharpe={metrics["sharpe"]:.2f}')
return results
except Exception as e:
traceback.print_exc()
return None
if __name__ == '__main__':
all_data = download_all()
for ticker in cfg.tickers:
if ticker not in all_data: continue
print(f'\n{"="*50}\n {ticker} LSTM Training\n{"="*50}')
t0 = time.time()
r = train_lstm_one(ticker, all_data)
print(f' Time: {time.time()-t0:.1f}s')
sys.stdout.flush()