File size: 4,981 Bytes
9b7f9ef | 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | """Prediction API — loads trained models and generates signals."""
import os, sys, json, argparse
import numpy as np, pandas as pd, joblib
from config import cfg
from data_loader import download, get_asset_name
from features import build_all_features, get_feature_columns
from labels import add_all_labels
from models import EnsemblePredictor
import warnings; warnings.filterwarnings('ignore')
class AssetPredictor:
def __init__(self, ticker):
self.ticker = ticker
self.model_dir = os.path.join(cfg.model_dir, ticker)
if not os.path.exists(self.model_dir):
raise FileNotFoundError(f"No trained models for {ticker} at {self.model_dir}")
meta_path = os.path.join(self.model_dir, 'meta.json')
self.meta = {}
if os.path.exists(meta_path):
with open(meta_path) as f: self.meta = json.load(f)
self.feature_cols = joblib.load(os.path.join(self.model_dir, 'feature_cols.joblib'))
self.models = {}
for h in cfg.horizons:
md = os.path.join(self.model_dir)
lgbm_path = os.path.join(md, f'lgbm_h{h}.joblib')
if not os.path.exists(lgbm_path): continue
model = EnsemblePredictor(horizon=h)
try:
model.load(md)
self.models[h] = model
except Exception as e:
print(f"Warning: Could not load model h={h}: {e}")
if not self.models:
raise RuntimeError(f"No valid models loaded for {ticker}")
print(f"Loaded {len(self.models)} horizon models for {ticker} ({get_asset_name(ticker)})")
def _prepare_features(self, df=None):
if df is None:
df = download(self.ticker)
all_data = {self.ticker: df}
for b in ['QQQ', 'VIXY', 'GLD']:
if b == self.ticker: continue
try: all_data[b] = download(b)
except: pass
df = build_all_features(df, ticker=self.ticker, all_data=all_data)
df = add_all_labels(df)
for c in self.feature_cols:
if c not in df.columns:
df[c] = 0.0
return df
def get_multi_horizon(self, df=None, use_lstm=True):
df = self._prepare_features(df)
results = {}
for h, model in self.models.items():
try: results[h] = model.predict_latest(df, use_lstm=use_lstm)
except Exception as e: results[h] = {'error': str(e)}
signals = [r.get('signal', 'HOLD') for r in results.values() if 'signal' in r]
if not signals: consensus = 'NO_DATA'
else:
buys = sum(1 for s in signals if s == 'BUY')
sells = sum(1 for s in signals if s == 'SELL')
if buys > sells: consensus = f'BUY ({buys}/{len(signals)})'
elif sells > buys: consensus = f'SELL ({sells}/{len(signals)})'
else: consensus = f'HOLD ({len(signals) - buys - sells}/{len(signals)})'
results['consensus'] = consensus
results['ticker'] = self.ticker
results['name'] = get_asset_name(self.ticker)
return results
def get_signal(self, df=None, use_lstm=True):
r = self.get_multi_horizon(df, use_lstm)
return r['consensus']
def get_prediction_summary(self, df=None):
r = self.get_multi_horizon(df)
name = r.get('name', self.ticker)
print(f"\n{'='*60}")
print(f" {self.ticker} — {name}")
print(f"{'='*60}")
print(f" Consensus: {r.get('consensus', '?')}")
for h in sorted([k for k in r if isinstance(k, int)]):
res = r[h]
if 'signal' in res:
print(f" h={h:>2}d: {res['signal']:>4} conf={res['confidence']:.0%} pred={res['ensemble_prediction']:+.4f}")
return r
def predict_all_assets():
results = {}
for ticker in cfg.tickers:
model_dir = os.path.join(cfg.model_dir, ticker)
if not os.path.exists(model_dir):
continue
try:
predictor = AssetPredictor(ticker)
results[ticker] = predictor.get_multi_horizon(use_lstm=False)
except Exception as e:
print(f"Error predicting {ticker}: {e}")
return results
def main():
parser = argparse.ArgumentParser(description='High-Volatility Asset Prediction')
parser.add_argument('--ticker', type=str, default=None)
parser.add_argument('--all', action='store_true')
parser.add_argument('--no-lstm', action='store_true')
args = parser.parse_args()
use_lstm = not args.no_lstm
if args.all:
results = predict_all_assets()
print(f"\n{'='*60}\nHigh-Volatility Asset Predictions Summary\n{'='*60}")
for t, r in results.items():
print(f" {t:>6}: {r.get('consensus', 'N/A')}")
elif args.ticker:
predictor = AssetPredictor(args.ticker)
predictor.get_prediction_summary()
else:
print("Specify --ticker <TICKER> or --all")
if __name__ == '__main__':
main()
|