File size: 10,016 Bytes
4f20938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""
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))