File size: 2,452 Bytes
f418c65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Batch train LSTM models for all high-volatility 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()]
        fc_path = os.path.join(cfg.model_dir, ticker, 'feature_cols.joblib')
        if os.path.exists(fc_path):
            saved_fc = joblib.load(fc_path)
            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)
            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()