Download models.py from AcyLa/volatility-predictive-model: direct link, hf CLI and curl.
- Browser
- Download file 9.94 kB
-
https://huggingface.co/AcyLa/volatility-predictive-model/resolve/main/models.py
- Command line
-
hf download hf://AcyLa/volatility-predictive-model/models.py
-
curl -L -o models.py https://huggingface.co/AcyLa/volatility-predictive-model/resolve/main/models.py
9.94 kB
| """Ensemble Model — LightGBM + LSTM with attention.""" | |
| import numpy as np, pandas as pd, lightgbm as lgb, torch, torch.nn as nn, joblib, os, warnings | |
| from torch.utils.data import Dataset, DataLoader | |
| from sklearn.preprocessing import StandardScaler | |
| from sklearn.metrics import mean_squared_error | |
| from config import cfg | |
| warnings.filterwarnings('ignore') | |
| class LightGBMPredictor: | |
| def __init__(self, horizon=1): | |
| self.horizon = horizon; self.target_col = f'Target_Return_{horizon}' | |
| self.model = None; self.feature_cols = None; self.best_iteration = None | |
| def train(self, train_df, val_df, feature_cols): | |
| self.feature_cols = feature_cols | |
| X_tr = train_df[feature_cols].values; y_tr = train_df[self.target_col].values | |
| X_va = val_df[feature_cols].values; y_va = val_df[self.target_col].values | |
| m1 = ~np.isnan(y_tr); m2 = ~np.isnan(y_va) | |
| X_tr, y_tr = X_tr[m1], y_tr[m1]; X_va, y_va = X_va[m2], y_va[m2] | |
| ts = lgb.Dataset(X_tr, label=y_tr, feature_name=feature_cols, free_raw_data=False) | |
| vs = lgb.Dataset(X_va, label=y_va, reference=ts, feature_name=feature_cols, free_raw_data=False) | |
| p = {**cfg.lgbm_params}; n = p.pop('n_estimators'); es = p.pop('early_stopping_rounds') | |
| self.model = lgb.train(p, ts, num_boost_round=n, valid_sets=[ts, vs], | |
| valid_names=['train','val'], callbacks=[lgb.early_stopping(es, verbose=False), lgb.log_evaluation(0)]) | |
| self.best_iteration = self.model.best_iteration; return self | |
| def predict(self, df): | |
| X = np.nan_to_num(df[self.feature_cols].values, nan=0.0) | |
| return self.model.predict(X, num_iteration=self.best_iteration) | |
| def feature_importance(self, top_n=20): | |
| imp = self.model.feature_importance(importance_type='gain') | |
| return pd.DataFrame({'feature': self.feature_cols, 'importance': imp}).sort_values('importance', ascending=False).head(top_n) | |
| def save(self, path): | |
| joblib.dump({'model': self.model, 'feature_cols': self.feature_cols, | |
| 'horizon': self.horizon, 'best_iteration': self.best_iteration}, path) | |
| def load(self, path): | |
| d = joblib.load(path); self.model = d['model']; self.feature_cols = d['feature_cols'] | |
| self.horizon = d['horizon']; self.best_iteration = d['best_iteration']; return self | |
| class SequenceDataset(Dataset): | |
| def __init__(self, f, t, s): self.f, self.t, self.s = f, t, s | |
| def __len__(self): return max(0, len(self.f) - self.s) | |
| def __getitem__(self, i): return torch.FloatTensor(self.f[i:i+self.s]), torch.FloatTensor([self.t[i+self.s]]) | |
| class LSTMModel(nn.Module): | |
| def __init__(self, input_size, hidden_size=128, num_layers=2, dropout=0.2): | |
| super().__init__() | |
| self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, | |
| batch_first=True, dropout=dropout if num_layers > 1 else 0) | |
| self.attention = nn.Sequential(nn.Linear(hidden_size, hidden_size//2), nn.Tanh(), nn.Linear(hidden_size//2, 1)) | |
| self.head = nn.Sequential(nn.LayerNorm(hidden_size), nn.Dropout(dropout), | |
| nn.Linear(hidden_size, hidden_size//2), nn.GELU(), nn.Linear(hidden_size//2, 1)) | |
| def forward(self, x): | |
| out, _ = self.lstm(x); attn = torch.softmax(self.attention(out), dim=1) | |
| return self.head((out * attn).sum(dim=1)).squeeze(-1) | |
| class LSTMPredictor: | |
| def __init__(self, horizon=1, seq_len=None): | |
| self.horizon = horizon; self.target_col = f'Target_Return_{horizon}' | |
| self.seq_len = seq_len or cfg.lstm_seq_len; self.model = None | |
| self.scaler = StandardScaler(); self.feature_cols = None | |
| self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| def _prep(self, df, fc, fit=False): | |
| self.feature_cols = fc; X = np.nan_to_num(df[fc].values, nan=0.0) | |
| y = df[self.target_col].values if self.target_col in df.columns else np.zeros(len(X)) | |
| y = np.nan_to_num(y, nan=0.0) | |
| if fit: self.scaler.fit(X) | |
| return self.scaler.transform(X), y | |
| def train(self, tr, va, fc): | |
| X_tr, y_tr = self._prep(tr, fc, fit=True); X_va, y_va = self._prep(va, fc, fit=False) | |
| tr_ld = DataLoader(SequenceDataset(X_tr, y_tr, self.seq_len), batch_size=cfg.lstm_batch_size, shuffle=True, drop_last=True) | |
| va_ld = DataLoader(SequenceDataset(X_va, y_va, self.seq_len), batch_size=cfg.lstm_batch_size, shuffle=False) | |
| self.model = LSTMModel(len(fc), cfg.lstm_hidden_size, cfg.lstm_num_layers, cfg.lstm_dropout).to(self.device) | |
| opt = torch.optim.AdamW(self.model.parameters(), lr=cfg.lstm_learning_rate, weight_decay=1e-4) | |
| sch = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=cfg.lstm_epochs); crit = nn.HuberLoss() | |
| best, pat, state = float('inf'), 0, None | |
| for _ in range(cfg.lstm_epochs): | |
| self.model.train() | |
| for bx, by in tr_ld: | |
| bx, by = bx.to(self.device), by.to(self.device) | |
| opt.zero_grad(); crit(self.model(bx), by).backward() | |
| torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0); opt.step() | |
| self.model.eval(); vl = 0 | |
| with torch.no_grad(): | |
| for bx, by in va_ld: vl += crit(self.model(bx.to(self.device)), by.to(self.device)).item() | |
| sch.step(); vl /= max(len(va_ld), 1) | |
| if vl < best: best, pat, state = vl, 0, {k: v.clone() for k, v in self.model.state_dict().items()} | |
| else: pat += 1 | |
| if pat >= cfg.lstm_patience: break | |
| if state: self.model.load_state_dict(state) | |
| return self | |
| def predict(self, df): | |
| self.model.eval(); X, _ = self._prep(df, self.feature_cols) | |
| preds = np.full(len(X), np.nan) | |
| with torch.no_grad(): | |
| for i in range(self.seq_len, len(X)): | |
| preds[i] = self.model(torch.FloatTensor(X[i-self.seq_len:i]).unsqueeze(0).to(self.device)).item() | |
| return preds | |
| def predict_last(self, df): | |
| self.model.eval(); X, _ = self._prep(df, self.feature_cols) | |
| if len(X) < self.seq_len: raise ValueError(f"Need {self.seq_len} bars") | |
| with torch.no_grad(): | |
| return self.model(torch.FloatTensor(X[-self.seq_len:]).unsqueeze(0).to(self.device)).item() | |
| def save(self, path): | |
| torch.save({'model_state': self.model.state_dict(), 'scaler': self.scaler, | |
| 'feature_cols': self.feature_cols, 'horizon': self.horizon, 'seq_len': self.seq_len, | |
| 'config': {'hidden_size': cfg.lstm_hidden_size, 'num_layers': cfg.lstm_num_layers, 'dropout': cfg.lstm_dropout}}, path) | |
| def load(self, path): | |
| ck = torch.load(path, map_location=self.device, weights_only=False) | |
| self.scaler = ck['scaler']; self.feature_cols = ck['feature_cols'] | |
| self.horizon = ck['horizon']; self.seq_len = ck['seq_len']; c = ck['config'] | |
| self.model = LSTMModel(len(self.feature_cols), c['hidden_size'], c['num_layers'], c['dropout']).to(self.device) | |
| self.model.load_state_dict(ck['model_state']); self.model.eval(); return self | |
| class EnsemblePredictor: | |
| def __init__(self, horizon=1): | |
| self.horizon = horizon; self.lgbm = LightGBMPredictor(horizon=horizon) | |
| self.lstm = LSTMPredictor(horizon=horizon); self.weights = cfg.ensemble_weights; self.is_trained = False | |
| def train(self, tr, va, fc): | |
| print(f" Training LightGBM (h={self.horizon})..."); self.lgbm.train(tr, va, fc) | |
| print(f" Training LSTM (h={self.horizon})..."); self.lstm.train(tr, va, fc) | |
| self._tune(va); self.is_trained = True; return self | |
| def _tune(self, va): | |
| tgt = f'Target_Return_{self.horizon}'; lp = self.lgbm.predict(va); sp = self.lstm.predict(va) | |
| y = va[tgt].values; v = ~np.isnan(y) & ~np.isnan(lp) & ~np.isnan(sp) | |
| if v.sum() < 10: return | |
| yv, lv, sv = y[v], lp[v], sp[v]; best_rmse, best_w = float('inf'), self.weights | |
| for w in np.arange(0.0, 1.1, 0.1): | |
| r = np.sqrt(mean_squared_error(yv, w*lv + (1-w)*sv)) | |
| if r < best_rmse: best_rmse = r; best_w = [w, 1-w] | |
| self.weights = best_w; print(f" Weights: LGBM={best_w[0]:.1f}, LSTM={best_w[1]:.1f} (RMSE={best_rmse:.6f})") | |
| def predict(self, df, use_lstm=True): | |
| lp = self.lgbm.predict(df) | |
| if not use_lstm or self.lstm.model is None: return lp | |
| sp = self.lstm.predict(df) | |
| return np.where(np.isnan(sp), lp, self.weights[0]*lp + self.weights[1]*sp) | |
| def predict_latest(self, df, use_lstm=True): | |
| lp = self.lgbm.predict(df)[-1]; r = {'horizon': self.horizon, 'lgbm_prediction': float(lp), 'weights': self.weights} | |
| if use_lstm and self.lstm.model is not None: | |
| sp = self.lstm.predict_last(df); ens = self.weights[0]*lp + self.weights[1]*sp | |
| r['lstm_prediction'] = float(sp); r['ensemble_prediction'] = float(ens) | |
| else: r['ensemble_prediction'] = float(lp) | |
| thr = cfg.classification_threshold / 2 | |
| p = r['ensemble_prediction'] | |
| if p > thr: r['signal'] = 'BUY'; r['confidence'] = min(abs(p)/cfg.classification_threshold, 1.0) | |
| elif p < -thr: r['signal'] = 'SELL'; r['confidence'] = min(abs(p)/cfg.classification_threshold, 1.0) | |
| else: r['signal'] = 'HOLD'; r['confidence'] = 0.5 | |
| return r | |
| def save(self, md): | |
| os.makedirs(md, exist_ok=True) | |
| self.lgbm.save(os.path.join(md, f'lgbm_h{self.horizon}.joblib')) | |
| self.lstm.save(os.path.join(md, f'lstm_h{self.horizon}.pt')) | |
| joblib.dump(self.weights, os.path.join(md, f'weights_h{self.horizon}.joblib')) | |
| def load(self, md): | |
| self.lgbm.load(os.path.join(md, f'lgbm_h{self.horizon}.joblib')) | |
| self.lstm.load(os.path.join(md, f'lstm_h{self.horizon}.pt')) | |
| wp = os.path.join(md, f'weights_h{self.horizon}.joblib') | |
| if os.path.exists(wp): self.weights = joblib.load(wp) | |
| self.is_trained = True; return self | |