File size: 2,995 Bytes
e6b703b | 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 | """Forex Training Pipeline: download → features → labels → walk-forward → save"""
import sys, os, json, argparse, warnings
sys.path.insert(0, os.path.dirname(__file__))
warnings.filterwarnings('ignore')
from config import cfg
from data_loader import download
from features import build_all_features, get_feature_columns
from labels import add_all_labels, get_label_columns
from backtest import run_walk_forward
from models import EnsemblePredictor
def main(ticker=None, skip_backtest=False):
ticker = ticker or cfg.primary_ticker
print(f"\n{'#'*70}\n# FOREX PREDICTIVE MODEL — TRAINING\n# Pair: {ticker}\n{'#'*70}\n")
print("Step 1: Downloading FX data..."); df = download(ticker)
print(f" Range: {df.index[0]} → {df.index[-1]} ({len(df)} bars)\n")
print("Step 2: Engineering features..."); df = build_all_features(df)
print("Step 3: Adding labels..."); df = add_all_labels(df, ticker)
lc = get_label_columns(df); print(f" Labels: {len(lc)}\n")
fc = [c for c in get_feature_columns(df) if c not in lc]
print(f"Step 4: {len(fc)} features\n"); df = df.dropna(subset=fc, how='all')
if skip_backtest:
te = int(len(df) * 0.8); tr, va = df.iloc[:te], df.iloc[te:]; models = {}
for h in cfg.horizons:
print(f"\n Training {h}h...")
m = EnsemblePredictor(horizon=h); m.train(tr, va, fc)
m.save(os.path.join(cfg.model_dir, ticker.replace('=','_'))); models[h] = m
meta = {'ticker': ticker, 'feature_cols': fc, 'horizons': cfg.horizons,
'data_range': [str(df.index[0]), str(df.index[-1])], 'n_bars': len(df)}
with open(os.path.join(cfg.model_dir, ticker.replace('=','_'), 'meta.json'), 'w') as f: json.dump(meta, f, indent=2)
print(f"\n✓ Saved"); return models
print("Step 5: Walk-forward backtest..."); results = run_walk_forward(df, fc, horizons=cfg.horizons)
md = os.path.join(cfg.model_dir, ticker.replace('=','_')); os.makedirs(md, exist_ok=True)
for h, r in results.items():
if r['model']: r['model'].save(md)
meta = {'ticker': ticker, 'feature_cols': fc, 'horizons': cfg.horizons,
'data_range': [str(df.index[0]), str(df.index[-1])], 'n_bars': len(df)}
with open(os.path.join(md, 'meta.json'), 'w') as f: json.dump(meta, f, indent=2)
print(f"\n{'#'*70}\n# TRAINING COMPLETE\n{'#'*70}\n")
print(f"{'Horizon':<10} {'RMSE':<12} {'Dir.Acc':<10} {'Pips':<10} {'Sharpe':<8} {'WinRate':<8}")
print(f"{'─'*58}")
for h, r in results.items():
m, s = r['metrics'], r['strategy']
print(f"{h}h {m['rmse']:<12.6f} {m['dir_acc']:<10.1%} {s['total_pips']:<10.0f} {s['sharpe']:<8.2f} {s['win_rate']:<8.1%}")
return results
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument('--ticker', type=str, default=None)
p.add_argument('--no-backtest', action='store_true')
args = p.parse_args(); main(ticker=args.ticker, skip_backtest=args.no_backtest)
|