File size: 6,132 Bytes
8a23062 | 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 | """Forex Prediction API β BUY/SELL/NEUTRAL signals with pip targets."""
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, get_pip_size
from features import build_all_features
from models import EnsemblePredictor
class ForexPredictor:
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.replace('=','_'))
mp = os.path.join(self.model_dir, 'meta.json')
if not os.path.exists(mp): raise FileNotFoundError(f"No model at {self.model_dir}. Run train.py first.")
with open(mp) as f: self.meta = json.load(f)
self.feature_cols = self.meta['feature_cols']; self.horizons = self.meta['horizons']
self.pip_size = get_pip_size(self.ticker); self.models = {}
for h in self.horizons: self.models[h] = EnsemblePredictor(horizon=h).load(self.model_dir)
print(f"β Loaded FX models for {self.ticker} (horizons: {self.horizons}h)")
def _get_latest_data(self, n=250):
df = download(self.ticker, period="30d", interval="1h"); df = build_all_features(df); return df.tail(n)
def get_signal_from_df(self, df, horizon=1, use_lstm=True):
if horizon not in self.models: raise ValueError(f"Horizon {horizon} not trained.")
price = float(df['Close'].iloc[-1]); r = self.models[horizon].predict_latest(df, use_lstm=use_lstm)
pr = r['ensemble_prediction']; pp = pr * price / self.pip_size
return {'pair': self.ticker, 'timestamp': datetime.now().isoformat(), 'latest_bar': str(df.index[-1]),
'horizon_hours': horizon, 'current_price': price, 'predicted_return': pr, 'predicted_pips': pp,
'target_price': price * (1 + pr), 'signal': r['signal'], 'confidence': r['confidence'],
'lgbm_prediction': r.get('lgbm_prediction'), 'lstm_prediction': r.get('lstm_prediction'),
'ensemble_prediction': r['ensemble_prediction'], 'pip_size': self.pip_size}
def get_multi_horizon_from_df(self, df, use_lstm=True):
price = float(df['Close'].iloc[-1]); preds = {}; sigs = []; confs = []
for h in self.horizons:
r = self.models[h].predict_latest(df, use_lstm=use_lstm)
r['target_price'] = price * (1 + r['ensemble_prediction'])
r['predicted_pips'] = r['ensemble_prediction'] * price / self.pip_size
preds[h] = r; sigs.append(r['signal']); confs.append(r['confidence'])
bw = sum(c for s, c in zip(sigs, confs) if s == 'BUY')
sw = sum(c for s, c in zip(sigs, confs) if s == 'SELL')
if bw > sw: cons, cc = 'BUY', bw / sum(confs)
elif sw > bw: cons, cc = 'SELL', sw / sum(confs)
else: cons, cc = 'NEUTRAL', 0.5
return {'pair': self.ticker, 'timestamp': datetime.now().isoformat(), 'latest_bar': str(df.index[-1]),
'current_price': price, 'predictions': preds, 'consensus': cons,
'consensus_confidence': cc, 'signals': sigs}
def get_signal(self, horizon=1, use_lstm=True):
return self.get_signal_from_df(self._get_latest_data(), horizon, use_lstm)
def get_multi_horizon(self, use_lstm=True):
return self.get_multi_horizon_from_df(self._get_latest_data(), use_lstm)
def predict_batch(self, df, horizon=1, use_lstm=True):
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):
return self.models[horizon].lgbm.feature_importance(top_n=top_n)
def print_signal(s):
print(f"\n{'β'*55}\n {s['pair']} | Horizon: {s['horizon_hours']}h")
print(f" Latest Bar: {s['latest_bar']}\n Current Price: {s['current_price']:.5f}")
print(f" Target Price: {s['target_price']:.5f}")
print(f" Predicted: {s['predicted_pips']:+.1f} pips ({s['predicted_return']:+.4%})")
print(f" ββββββββββββββββββββββββββββββ")
print(f" LightGBM: {s.get('lgbm_prediction', 0):+.6f}")
if s.get('lstm_prediction') is not None: print(f" LSTM: {s['lstm_prediction']:+.6f}")
print(f" Ensemble: {s['ensemble_prediction']:+.6f}")
print(f" ββββββββββββββββββββββββββββββ")
e = {'BUY': 'π’', 'SELL': 'π΄', 'NEUTRAL': 'π‘'}[s['signal']]
print(f" SIGNAL: {e} {s['signal']} (confidence: {s['confidence']:.0%})\n{'β'*55}")
def print_multi(r):
print(f"\n{'β'*60}\n {r['pair']} | Multi-Horizon FX Predictions")
print(f" Latest Bar: {r['latest_bar']}\n Current Price: {r['current_price']:.5f}\n{'β'*60}")
for h, p in r['predictions'].items():
e = {'BUY': 'π’', 'SELL': 'π΄', 'NEUTRAL': 'π‘'}[p['signal']]
print(f" {h:>2}h: {e} {p['signal']:<8} | {p.get('predicted_pips',0):>+6.1f} pips | target={p['target_price']:.5f} | conf={p['confidence']:.0%}")
print(f"{'β'*60}")
e = {'BUY': 'π’', 'SELL': 'π΄', 'NEUTRAL': 'π‘'}[r['consensus']]
print(f" CONSENSUS: {e} {r['consensus']} (confidence: {r['consensus_confidence']:.0%})")
print(f" Signals: {r['signals']}\n{'β'*60}\n")
if __name__ == "__main__":
p = argparse.ArgumentParser(description="Forex Prediction CLI")
p.add_argument('--ticker', type=str, default=cfg.primary_ticker)
p.add_argument('--no-lstm', action='store_true')
p.add_argument('--horizon', type=int, default=None)
p.add_argument('--features', action='store_true')
args = p.parse_args()
pred = ForexPredictor(ticker=args.ticker)
if args.horizon: print_signal(pred.get_signal(horizon=args.horizon, use_lstm=not args.no_lstm))
else: print_multi(pred.get_multi_horizon(use_lstm=not args.no_lstm))
if args.features: print("\nTop 20 Features:"); print(pred.get_feature_importance(horizon=1, top_n=20).to_string(index=False))
|