Upload batch_train.py with huggingface_hub
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Batch train all assets — LightGBM only, saves models + results."""import os, sys, json, time, tracebackimport numpy as np, pandas as pd, joblibfrom config import cfgfrom data_loader import download, download_all, get_asset_namefrom features import build_all_features, get_feature_columnsfrom labels import add_all_labelsfrom models import EnsemblePredictorfrom backtest import quick_split, evaluate_predictionsimport warnings; warnings.filterwarnings('ignore')
def train_one(ticker, all_data): try: df = all_data.get(ticker) if df is None or len(df) < 500: return {'ticker': ticker, 'status': 'skip', 'reason': f'insufficient data ({len(df) if df is not None else 0})'} df = build_all_features(df, ticker=ticker, all_data=all_data) df = add_all_labels(df) feature_cols = get_feature_columns(df) feature_cols = [c for c in feature_cols if not df[c].isna().all()] clean = df.dropna(subset=feature_cols + [f'Target_Return_{h}' for h in cfg.horizons], how='any') if len(clean) < 500: return {'ticker': ticker, 'status': 'skip', 'reason': f'clean rows < 500 ({len(clean)})'} splits = quick_split(len(clean)) tr_s, tr_e, va_s, va_e, te_s, te_e = splits[0] tr, va, te = clean.iloc[tr_s:tr_e], clean.iloc[va_s:va_e], clean.iloc[te_s:te_e] results = [] for h in cfg.horizons: model = EnsemblePredictor(horizon=h) model.lgbm.train(tr, va, feature_cols) preds = model.lgbm.predict(te) tgt = f'Target_Return_{h}' y = te[tgt].values; m = ~np.isnan(y) metrics = evaluate_predictions(y[m], preds[m]) metrics.update({'horizon': h, 'ticker': ticker}) results.append(metrics) # Save LightGBM model only md = os.path.join(cfg.model_dir, ticker) os.makedirs(md, exist_ok=True) model.lgbm.save(os.path.join(md, f'lgbm_h{h}.joblib')) joblib.dump(model.lgbm.weights if hasattr(model.lgbm, 'weights') else cfg.ensemble_weights, os.path.join(md, f'weights_h{h}.joblib')) print(f' {ticker} h={h}: Dir.Acc={metrics["dir_acc"]:.1%} Sharpe={metrics["sharpe"]:.2f} RMSE={metrics["rmse"]:.6f}') # Save metadata md = os.path.join(cfg.model_dir, ticker) joblib.dump(feature_cols, os.path.join(md, 'feature_cols.joblib')) meta = {'ticker': ticker, 'name': get_asset_name(ticker), 'horizons': cfg.horizons, 'n_features': len(feature_cols), 'interval': cfg.interval} with open(os.path.join(md, 'meta.json'), 'w') as f: json.dump(meta, f, indent=2) os.makedirs(cfg.results_dir, exist_ok=True) with open(os.path.join(cfg.results_dir, f'{ticker}_results.json'), 'w') as f: json.dump({'quick_eval': results}, f, indent=2, default=str) return {'ticker': ticker, 'status': 'ok', 'results': results} except Exception as e: traceback.print_exc() return {'ticker': ticker, 'status': 'error', 'reason': str(e)}
if __name__ == '__main__': os.makedirs(cfg.model_dir, exist_ok=True) os.makedirs(cfg.results_dir, exist_ok=True) all_data = download_all() # Train each asset for ticker in cfg.tickers: if ticker not in all_data: continue print(f'\n{"="*50}\n {ticker} ({get_asset_name(ticker)})\n{"="*50}') t0 = time.time() r = train_one(ticker, all_data) print(f' Time: {time.time()-t0:.1f}s Status: {r["status"]}') # Flush stdout sys.stdout.flush()batch_train.pyAdded+70