""" Live Prediction API — loads trained models and produces real-time predictions. Designed for integration into HFT/trading systems. Usage: from predict import CryptoPredictor predictor = CryptoPredictor(ticker="BTC-USD") signal = predictor.get_signal() # Latest prediction signals = predictor.get_multi_horizon() # All horizons fast = predictor.get_signal(use_lstm=False) # Sub-ms for HFT CLI: python predict.py --ticker BTC-USD [--no-lstm] """ import sys, os, json, argparse, warnings sys.path.insert(0, os.path.dirname(__file__)) warnings.filterwarnings('ignore') import pandas as pd, numpy as np from datetime import datetime from config import cfg from data_loader import download from features import build_all_features, get_feature_columns from labels import get_label_columns from models import EnsemblePredictor class CryptoPredictor: """Production prediction interface for the crypto ensemble model.""" def __init__(self, ticker=None, model_dir=None): self.ticker = ticker or cfg.primary_ticker self.model_dir = model_dir or os.path.join(cfg.model_dir, self.ticker) meta_path = os.path.join(self.model_dir, 'meta.json') if not os.path.exists(meta_path): raise FileNotFoundError(f"No trained model at {self.model_dir}. Run train.py first.") with open(meta_path) as f: self.meta = json.load(f) self.feature_cols = self.meta['feature_cols'] self.horizons = self.meta['horizons'] self.models = {} for h in self.horizons: model = EnsemblePredictor(horizon=h) model.load(self.model_dir) self.models[h] = model print(f"✓ Loaded models for {self.ticker} (horizons: {self.horizons})") def _get_latest_data(self, n_days=250): df = download(self.ticker, period="1y", interval="1d") df = build_all_features(df) return df.tail(n_days) def get_signal_from_df(self, df, horizon=1, use_lstm=True): """Get prediction from a pre-built DataFrame (for HFT/live data feeds). The DataFrame must already have features built (call build_all_features first). """ if horizon not in self.models: raise ValueError(f"Horizon {horizon} not trained. Available: {self.horizons}") current_price = float(df['Close'].iloc[-1]) model = self.models[horizon] result = model.predict_latest(df, use_lstm=use_lstm) return {'ticker': self.ticker, 'timestamp': datetime.now().isoformat(), 'latest_bar': str(df.index[-1]), 'horizon_days': horizon, 'predicted_return': result['ensemble_prediction'], 'signal': result['signal'], 'confidence': result['confidence'], 'lgbm_prediction': result.get('lgbm_prediction'), 'lstm_prediction': result.get('lstm_prediction'), 'ensemble_prediction': result['ensemble_prediction'], 'current_price': current_price, 'target_price': current_price * (1 + result['ensemble_prediction'])} def get_multi_horizon_from_df(self, df, use_lstm=True): """Get multi-horizon predictions from a pre-built DataFrame (for HFT).""" current_price = float(df['Close'].iloc[-1]) predictions = {}; signals = []; confidences = [] for h in self.horizons: model = self.models[h] result = model.predict_latest(df, use_lstm=use_lstm) result['target_price'] = current_price * (1 + result['ensemble_prediction']) predictions[h] = result; signals.append(result['signal']); confidences.append(result['confidence']) buy_w = sum(c for s, c in zip(signals, confidences) if s == 'BUY') sell_w = sum(c for s, c in zip(signals, confidences) if s == 'SELL') hold_w = sum(c for s, c in zip(signals, confidences) if s == 'HOLD') if buy_w > sell_w and buy_w > hold_w: consensus, cc = 'BUY', buy_w / sum(confidences) elif sell_w > buy_w and sell_w > hold_w: consensus, cc = 'SELL', sell_w / sum(confidences) else: consensus, cc = 'HOLD', hold_w / sum(confidences) return {'ticker': self.ticker, 'timestamp': datetime.now().isoformat(), 'latest_bar': str(df.index[-1]), 'current_price': current_price, 'predictions': predictions, 'consensus': consensus, 'consensus_confidence': cc, 'signals': signals} def get_signal(self, horizon=1, use_lstm=True): if horizon not in self.models: raise ValueError(f"Horizon {horizon} not trained. Available: {self.horizons}") df = self._get_latest_data() current_price = float(df['Close'].iloc[-1]) model = self.models[horizon] result = model.predict_latest(df, use_lstm=use_lstm) return {'ticker': self.ticker, 'timestamp': datetime.now().isoformat(), 'latest_bar': str(df.index[-1]), 'horizon_days': horizon, 'predicted_return': result['ensemble_prediction'], 'signal': result['signal'], 'confidence': result['confidence'], 'lgbm_prediction': result.get('lgbm_prediction'), 'lstm_prediction': result.get('lstm_prediction'), 'ensemble_prediction': result['ensemble_prediction'], 'current_price': current_price, 'target_price': current_price * (1 + result['ensemble_prediction'])} def get_multi_horizon(self, use_lstm=True): df = self._get_latest_data() current_price = float(df['Close'].iloc[-1]) predictions = {}; signals = []; confidences = [] for h in self.horizons: model = self.models[h] result = model.predict_latest(df, use_lstm=use_lstm) result['target_price'] = current_price * (1 + result['ensemble_prediction']) predictions[h] = result; signals.append(result['signal']); confidences.append(result['confidence']) buy_w = sum(c for s, c in zip(signals, confidences) if s == 'BUY') sell_w = sum(c for s, c in zip(signals, confidences) if s == 'SELL') hold_w = sum(c for s, c in zip(signals, confidences) if s == 'HOLD') if buy_w > sell_w and buy_w > hold_w: consensus, cc = 'BUY', buy_w / sum(confidences) elif sell_w > buy_w and sell_w > hold_w: consensus, cc = 'SELL', sell_w / sum(confidences) else: consensus, cc = 'HOLD', hold_w / sum(confidences) return {'ticker': self.ticker, 'timestamp': datetime.now().isoformat(), 'latest_bar': str(df.index[-1]), 'current_price': current_price, 'predictions': predictions, 'consensus': consensus, 'consensus_confidence': cc, 'signals': signals} def predict_batch(self, df, horizon=1, use_lstm=True): if horizon not in self.models: raise ValueError(f"Horizon {horizon} not trained. Available: {self.horizons}") if 'RSI_14' not in df.columns: df = build_all_features(df) return self.models[horizon].predict(df, use_lstm=use_lstm) def get_feature_importance(self, horizon=1, top_n=20): if horizon not in self.models: raise ValueError(f"Horizon {horizon} not trained.") return self.models[horizon].lgbm.feature_importance(top_n=top_n) def print_signal(signal): print(f"\n{'═'*50}") print(f" {signal['ticker']} | Horizon: {signal['horizon_days']}d") print(f" Latest Bar: {signal['latest_bar']}") print(f" Current Price: ${signal['current_price']:,.2f}") print(f" Target Price: ${signal['target_price']:,.2f}") print(f" Predicted Return: {signal['predicted_return']:+.2%}") print(f" ─────────────────────────────") print(f" LightGBM: {signal.get('lgbm_prediction', 0):+.4f}") if signal.get('lstm_prediction') is not None: print(f" LSTM: {signal['lstm_prediction']:+.4f}") print(f" Ensemble: {signal['ensemble_prediction']:+.4f}") print(f" ─────────────────────────────") emoji = {'BUY': '🟢', 'SELL': '🔴', 'HOLD': '🟡'}[signal['signal']] print(f" SIGNAL: {emoji} {signal['signal']} (confidence: {signal['confidence']:.0%})") print(f"{'═'*50}") def print_multi_horizon(result): print(f"\n{'═'*60}") print(f" {result['ticker']} | Multi-Horizon Predictions") print(f" Latest Bar: {result['latest_bar']}") print(f" Current Price: ${result['current_price']:,.2f}") print(f"{'═'*60}") for h, pred in result['predictions'].items(): emoji = {'BUY': '🟢', 'SELL': '🔴', 'HOLD': '🟡'}[pred['signal']] print(f" {h:>2}d: {emoji} {pred['signal']:<6} | ret={pred['ensemble_prediction']:+.2%} | target=${pred['target_price']:,.2f} | conf={pred['confidence']:.0%}") print(f"{'─'*60}") emoji = {'BUY': '🟢', 'SELL': '🔴', 'HOLD': '🟡'}[result['consensus']] print(f" CONSENSUS: {emoji} {result['consensus']} (confidence: {result['consensus_confidence']:.0%})") print(f" Signals: {result['signals']}") print(f"{'═'*60}\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Crypto Prediction CLI") parser.add_argument('--ticker', type=str, default=cfg.primary_ticker) parser.add_argument('--no-lstm', action='store_true', help='Fast mode: LightGBM only') parser.add_argument('--horizon', type=int, default=None) parser.add_argument('--features', action='store_true', help='Show feature importance') args = parser.parse_args() predictor = CryptoPredictor(ticker=args.ticker) if args.horizon: print_signal(predictor.get_signal(horizon=args.horizon, use_lstm=not args.no_lstm)) else: print_multi_horizon(predictor.get_multi_horizon(use_lstm=not args.no_lstm)) if args.features: print("\nTop 20 Features (1d horizon):") print(predictor.get_feature_importance(horizon=1, top_n=20).to_string(index=False))