File size: 3,464 Bytes
7b003e5 | 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 | """
Main Training Pipeline: download → features → labels → walk-forward train → save
Usage: python train.py [--ticker BTC-USD] [--no-backtest]
"""
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# CRYPTO PREDICTIVE MODEL — TRAINING PIPELINE\n# Asset: {ticker}\n{'#'*70}\n")
print("Step 1: Downloading data...")
df = download(ticker)
print(f" Range: {df.index[0]} → {df.index[-1]} ({len(df)} rows)\n")
print("Step 2: Engineering features...")
df = build_all_features(df)
print("Step 3: Adding labels...")
df = add_all_labels(df)
label_cols = get_label_columns(df)
print(f" Labels: {len(label_cols)}\n")
feature_cols = get_feature_columns(df)
feature_cols = [c for c in feature_cols if c not in label_cols]
print(f"Step 4: Feature set: {len(feature_cols)} features\n")
initial_len = len(df)
df = df.dropna(subset=feature_cols, how='all')
print(f" Dropped {initial_len - len(df)} warmup rows\n")
if skip_backtest:
print("Step 5: Quick training (no walk-forward)...")
train_end = int(len(df) * 0.8)
train_df, val_df = df.iloc[:train_end], df.iloc[train_end:]
models = {}
for h in cfg.horizons:
print(f"\n Training horizon {h}d...")
model = EnsemblePredictor(horizon=h)
model.train(train_df, val_df, feature_cols)
model.save(os.path.join(cfg.model_dir, ticker))
models[h] = model
print(f"\n✓ Models saved to {cfg.model_dir}/{ticker}/")
return models
print("Step 5: Walk-forward backtest...")
results = run_walk_forward(df, feature_cols, horizons=cfg.horizons)
print(f"\n\nStep 6: Saving final models to {cfg.model_dir}/{ticker}/...")
model_dir = os.path.join(cfg.model_dir, ticker)
os.makedirs(model_dir, exist_ok=True)
for h, res in results.items():
if res['model'] is not None:
res['model'].save(model_dir)
meta = {'ticker': ticker, 'feature_cols': feature_cols, 'horizons': cfg.horizons,
'data_range': [str(df.index[0]), str(df.index[-1])], 'n_rows': len(df)}
with open(os.path.join(model_dir, '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} {'R²':<8} {'Alpha':<10} {'Sharpe':<8}")
print(f"{'─'*58}")
for h, res in results.items():
m, s = res['metrics'], res['strategy']
print(f"{h}d {m['rmse']:<12.6f} {m['directional_accuracy']:<10.1%} {m['r2']:<8.4f} {s['alpha']:<+10.2%} {s['sharpe']:<8.2f}")
print(f"\nModels saved to: {cfg.model_dir}/{ticker}/")
return results
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Crypto Predictive Model Training")
parser.add_argument('--ticker', type=str, default=None)
parser.add_argument('--no-backtest', action='store_true')
args = parser.parse_args()
main(ticker=args.ticker, skip_backtest=args.no_backtest)
|