| |
| """ |
| train_ranker.py — LGBMRanker walk-forward training for Jinjing V2 Fire Eye v8. |
| |
| Reads ranking training data (parquet), trains on walk-forward windows, |
| evaluates NDCG and Rank IC, saves model and predictions. |
| """ |
|
|
| import argparse |
| import os |
| import sys |
| import warnings |
| from pathlib import Path |
|
|
| import numpy as np |
| import pandas as pd |
| import pyarrow.parquet as pq |
| from scipy.stats import spearmanr |
| import lightgbm as lgb |
| from typing import Optional |
|
|
| warnings.filterwarnings("ignore") |
|
|
| |
| |
| |
|
|
| |
| NON_FEATURE_COLS = { |
| "date", "symbol", "query_group", "label", "label_rank", |
| "forward_20d_ret", "trend_type", |
| |
| "pred_rank", |
| } |
|
|
| TARGET_COL = "label_rank" |
|
|
| |
| FEATURE_COLS: list[str] = [] |
|
|
| QUERY_GROUP_COL = "query_group" |
| DATE_COL = "date" |
| SYMBOL_COL = "symbol" |
|
|
| WINDOWS = [ |
| ("2018-01-01", "2022-11-30", "2023-01-01", "2024-06-30"), |
| ("2018-06-01", "2023-06-01", "2023-07-01", "2024-12-31"), |
| ("2019-01-01", "2024-05-31", "2024-07-01", "2025-06-30"), |
| ("2019-06-01", "2024-12-31", "2025-01-01", "2025-12-31"), |
| ("2020-01-01", "2024-12-31", "2025-01-01", "2026-04-10"), |
| ] |
|
|
| RANKER_PARAMS = { |
| "objective": "lambdarank", |
| "boosting_type": "gbdt", |
| "metric": "ndcg", |
| "ndcg_eval_at": [20, 50], |
| "num_leaves": 63, |
| "learning_rate": 0.05, |
| "min_data_in_leaf": 100, |
| "feature_fraction": 0.6, |
| "subsample": 0.8, |
| "subsample_freq": 1, |
| "lambda_l1": 0.1, |
| "lambda_l2": 1.0, |
| "verbosity": -1, |
| } |
|
|
| NUM_BOOST_ROUND = 300 |
| EARLY_STOPPING_ROUNDS = 50 |
|
|
| |
| PRIOR_FACTOR_NAMES = [ |
| "momentum_12m", "reversal_1m", "volatility_idio", "beta_60d", "turnover_avg", |
| "size", "pe", "pb", "ps", "dividend_yield", |
| "roe", "gross_margin", "asset_growth", |
| ] |
| PRIOR_PREFIXES = ["prior_"] |
|
|
| MODEL_VERSION = "v9" |
|
|
|
|
| |
| |
| |
|
|
| def infer_feature_cols(df: pd.DataFrame) -> list[str]: |
| """Auto-detect feature columns. |
| |
| Excludes known non-feature columns (date, symbol, query_group, label, etc.) |
| and any non-numeric columns. Returns only numeric feature columns. |
| """ |
| candidates = list(df.columns) |
| candidates = [c for c in candidates if c not in NON_FEATURE_COLS] |
| numeric_cols = [c for c in candidates if pd.api.types.is_numeric_dtype(df[c])] |
| if not numeric_cols: |
| print("ERROR: No numeric feature columns found after auto-detection") |
| print(f" Available columns: {list(df.columns)}") |
| sys.exit(1) |
| print(f"[features] Auto-detected {len(numeric_cols)} feature columns") |
| return numeric_cols |
|
|
|
|
| def load_data(data_path: str, sample: Optional[int] = None) -> pd.DataFrame: |
| """Load parquet from *data_path* or fallback to HuggingFace dataset. |
| |
| Auto-detects feature columns and sets the module-level FEATURE_COLS. |
| """ |
| global FEATURE_COLS |
|
|
| path = Path(data_path) |
| if path.exists(): |
| print(f"[data] Loading local parquet: {path}") |
| df = pd.read_parquet(path) |
| else: |
| print(f"[data] Local path not found, trying HuggingFace dataset...") |
| hf_token = os.environ.get("HF_TOKEN") |
| if not hf_token: |
| print("ERROR: HF_TOKEN environment variable not set") |
| sys.exit(1) |
| from huggingface_hub import hf_hub_download |
| parquet_path = hf_hub_download( |
| repo_id="cedwyh/jinjing-shared-data", |
| filename="ranking_train_data_v3.parquet", |
| repo_type="dataset", |
| token=hf_token, |
| ) |
| df = pd.read_parquet(parquet_path) |
|
|
| print(f"[data] Loaded {len(df):,} rows, {len(df.columns)} columns") |
|
|
| |
| if QUERY_GROUP_COL not in df.columns: |
| print(f"[data] Creating {QUERY_GROUP_COL} column...") |
| dates = df[DATE_COL].unique() |
| date_map = {d: i for i, d in enumerate(sorted(dates))} |
| df[QUERY_GROUP_COL] = df[DATE_COL].map(date_map) |
| print(f"[data] Created {len(dates)} query groups from dates") |
|
|
| |
| for col in [TARGET_COL, DATE_COL, QUERY_GROUP_COL, SYMBOL_COL]: |
| if col not in df.columns: |
| print(f"ERROR: Required column '{col}' not found in data") |
| print(f" Available columns: {list(df.columns)}") |
| sys.exit(1) |
|
|
| |
| if sample is not None and sample < len(df): |
| df = df.sample(n=sample, random_state=42).reset_index(drop=True) |
| print(f"[data] Sampled to {len(df):,} rows") |
|
|
| |
| FEATURE_COLS = infer_feature_cols(df) |
|
|
| |
| df[DATE_COL] = pd.to_datetime(df[DATE_COL]).dt.date |
| df[FEATURE_COLS] = df[FEATURE_COLS].astype(np.float32) |
| df[TARGET_COL] = df[TARGET_COL].astype(np.int32) |
| df[QUERY_GROUP_COL] = df[QUERY_GROUP_COL].astype(np.int32) |
|
|
| return df |
|
|
|
|
| def build_query_groups(df: pd.DataFrame) -> np.ndarray: |
| """Build group array for LGBMRanker: counts of samples per query (date).""" |
| counts = df.groupby(DATE_COL, observed=True).size().values |
| return counts.astype(np.int32) |
|
|
|
|
| def _dcg(scores: np.ndarray, k: int) -> float: |
| """Discounted Cumulative Gain @ k.""" |
| scores = scores[:k] |
| |
| gains = np.power(2.0, scores) - 1.0 |
| denom = np.log2(np.arange(2, len(scores) + 2)) |
| return float(np.sum(gains / denom)) |
|
|
|
|
| def evaluate_ndcg(y_true: np.ndarray, y_pred: np.ndarray, groups: np.ndarray, k: int) -> float: |
| """Compute average NDCG@k across query groups.""" |
| ndcgs = [] |
| idx = 0 |
| for g in groups: |
| if g < 2: |
| idx += g |
| continue |
| true_chunk = y_true[idx: idx + g].astype(np.float64) |
| pred_chunk = y_pred[idx: idx + g] |
|
|
| |
| order = np.argsort(pred_chunk)[::-1] |
| ranked_true = true_chunk[order] |
|
|
| |
| ideal = np.sort(true_chunk)[::-1] |
|
|
| dcg_val = _dcg(ranked_true, k) |
| idcg_val = _dcg(ideal, k) |
| if idcg_val > 0: |
| ndcgs.append(dcg_val / idcg_val) |
| idx += g |
| return float(np.mean(ndcgs)) if ndcgs else 0.0 |
|
|
|
|
| def evaluate_rank_ic( |
| y_true: np.ndarray, y_pred: np.ndarray, groups: np.ndarray |
| ) -> float: |
| """Spearman correlation between predicted and actual ranks, averaged across queries.""" |
| ics = [] |
| idx = 0 |
| for g in groups: |
| if g < 2: |
| idx += g |
| continue |
| true_chunk = y_true[idx: idx + g] |
| pred_chunk = y_pred[idx: idx + g] |
| |
| if len(np.unique(true_chunk)) < 2 or len(np.unique(pred_chunk)) < 2: |
| idx += g |
| continue |
| rho, _ = spearmanr(true_chunk, pred_chunk) |
| if not np.isnan(rho): |
| ics.append(rho) |
| idx += g |
| return float(np.mean(ics)) if ics else 0.0 |
|
|
|
|
| def train_window( |
| train_df: pd.DataFrame, |
| val_df: pd.DataFrame, |
| window_idx: int, |
| window_label: str, |
| ) -> tuple: |
| """Train LGBMRanker on one walk-forward window and return (model, preds_df).""" |
| print(f"\n{'='*60}") |
| print(f"Window {window_idx + 1}: {window_label}") |
| print(f"{'='*60}") |
|
|
| |
| X_train = train_df[FEATURE_COLS].values |
| y_train = train_df[TARGET_COL].values |
| train_groups = build_query_groups(train_df) |
| print(f" Train: {len(train_df):,} rows, {len(train_groups)} dates") |
|
|
| |
| X_val = val_df[FEATURE_COLS].values |
| y_val = val_df[TARGET_COL].values |
| val_groups = build_query_groups(val_df) |
| print(f" Val: {len(val_df):,} rows, {len(val_groups)} dates") |
|
|
| |
| |
| |
| |
| train_data = lgb.Dataset(X_train, label=y_train, group=train_groups, feature_name=FEATURE_COLS) |
| val_data = lgb.Dataset(X_val, label=y_val, group=val_groups, reference=train_data) |
|
|
| |
| model = lgb.train( |
| RANKER_PARAMS, |
| train_data, |
| valid_sets=[val_data], |
| num_boost_round=NUM_BOOST_ROUND, |
| callbacks=[ |
| lgb.early_stopping(EARLY_STOPPING_ROUNDS), |
| lgb.log_evaluation(50), |
| ], |
| ) |
|
|
| |
| val_pred = model.predict(X_val) |
| val_df = val_df.copy() |
| val_df["pred_rank"] = val_pred |
|
|
| |
| ndcg_20 = evaluate_ndcg(y_val, val_pred, val_groups, 20) |
| ndcg_50 = evaluate_ndcg(y_val, val_pred, val_groups, 50) |
| rank_ic = evaluate_rank_ic(y_val, val_pred, val_groups) |
|
|
| print(f" Results -> NDCG@20: {ndcg_20:.4f}, NDCG@50: {ndcg_50:.4f}, Rank IC: {rank_ic:.4f}") |
| print(f" Best iteration: {model.best_iteration}") |
|
|
| return model, val_df, ndcg_20, ndcg_50, rank_ic |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description=f"Train LGBMRanker for Jinjing V2 Fire Eye {MODEL_VERSION} ranking model" |
| ) |
| parser.add_argument( |
| "--data", |
| type=str, |
| default=None, |
| help=( |
| "Path to local parquet file. If not provided, tries " |
| "/tmp/ranking_train_data.parquet then HF dataset." |
| ), |
| ) |
| parser.add_argument( |
| "--output", |
| type=str, |
| default="/tmp", |
| help="Output directory for model and predictions (default: /tmp)", |
| ) |
| parser.add_argument( |
| "--sample", |
| type=int, |
| default=None, |
| help="Random subset of rows for fast testing", |
| ) |
| parser.add_argument( |
| "--use-priors", |
| action=argparse.BooleanOptionalAction, |
| default=True, |
| help="Enable PRISM-VQ prior_* feature columns (default: True)", |
| ) |
| args = parser.parse_args() |
|
|
| |
| data_path = args.data |
| if data_path is None: |
| default_local = "/tmp/ranking_train_data.parquet" |
| if os.path.exists(default_local): |
| data_path = default_local |
| else: |
| data_path = default_local |
|
|
| |
| df = load_data(data_path, sample=args.sample) |
| print(f"[data] Date range: {df[DATE_COL].min()} to {df[DATE_COL].max()}") |
| print(f"[data] Unique dates: {df[DATE_COL].nunique()}, symbols: {df[SYMBOL_COL].nunique()}") |
|
|
| |
| prior_cols_in_data = sorted([c for c in df.columns if c.startswith("prior_")]) |
| if args.use_priors and prior_cols_in_data: |
| print(f"[priors] Found {len(prior_cols_in_data)} prior_* columns in data: {prior_cols_in_data}") |
| elif args.use_priors and not prior_cols_in_data: |
| print("[priors] No prior_* columns found in data (running without priors)") |
| elif not args.use_priors and prior_cols_in_data: |
| print(f"[priors] --use-priors=False: excluding {len(prior_cols_in_data)} prior_* columns from features") |
| |
| global FEATURE_COLS |
| FEATURE_COLS = [c for c in FEATURE_COLS if not c.startswith("prior_")] |
| print(f"[features] After prior exclusion: {len(FEATURE_COLS)} feature columns") |
| else: |
| print("[priors] No prior columns and --use-priors=False: nothing to do") |
|
|
| |
| non_prior_feature_cols = [c for c in FEATURE_COLS if not c.startswith("prior_")] |
| has_priors = args.use_priors and len(prior_cols_in_data) > 0 and len(non_prior_feature_cols) < len(FEATURE_COLS) |
|
|
| |
| before = len(df) |
| df = df.drop_duplicates(subset=[DATE_COL, SYMBOL_COL]).reset_index(drop=True) |
| after = len(df) |
| if after < before: |
| print(f"[data] Deduplicated: {before:,} → {after:,} rows ({before - after:,} duplicates removed)") |
|
|
| |
| all_predictions = [] |
| results = [] |
| best_model = None |
|
|
| for idx, (train_start, train_end, val_start, val_end) in enumerate(WINDOWS): |
| train_start_ts = pd.Timestamp(train_start).date() |
| train_end_ts = pd.Timestamp(train_end).date() |
| val_start_ts = pd.Timestamp(val_start).date() |
| val_end_ts = pd.Timestamp(val_end).date() |
|
|
| train_mask = (df[DATE_COL] >= train_start_ts) & (df[DATE_COL] <= train_end_ts) |
| val_mask = (df[DATE_COL] >= val_start_ts) & (df[DATE_COL] <= val_end_ts) |
|
|
| train_df = df.loc[train_mask].reset_index(drop=True) |
| val_df = df.loc[val_mask].reset_index(drop=True) |
|
|
| if len(train_df) == 0 or len(val_df) == 0: |
| print(f"\n[skip] Window {idx+1}: no data in train or val range, skipping") |
| continue |
|
|
| label = f"{train_start}..{train_end} => {val_start}..{val_end}" |
| model, pred_df, ndcg_20, ndcg_50, rank_ic = train_window( |
| train_df, val_df, idx, label, |
| ) |
| all_predictions.append(pred_df) |
| results.append( |
| { |
| "window": idx + 1, |
| "train_range": f"{train_start} -> {train_end}", |
| "val_range": f"{val_start} -> {val_end}", |
| "NDCG@20": ndcg_20, |
| "NDCG@50": ndcg_50, |
| "Rank IC": rank_ic, |
| "best_iteration": model.best_iteration, |
| "n_train": len(train_df), |
| "n_val": len(val_df), |
| } |
| ) |
| best_model = model |
|
|
| |
| print(f"\n{'='*80}") |
| print("SUMMARY") |
| print(f"{'='*80}") |
| print(f"{'Window':>6} | {'NDCG@20':>8} | {'NDCG@50':>8} | {'Rank IC':>8} | Best Iter | Train Rows | Val Rows") |
| print("-" * 80) |
| avg_ndcg20, avg_ndcg50, avg_rankic = 0.0, 0.0, 0.0 |
| for r in results: |
| print( |
| f"{r['window']:>6} | {r['NDCG@20']:>8.4f} | {r['NDCG@50']:>8.4f} | " |
| f"{r['Rank IC']:>8.4f} | {r['best_iteration']:>9} | {r['n_train']:>10,} | {r['n_val']:>8,}" |
| ) |
| avg_ndcg20 += r["NDCG@20"] |
| avg_ndcg50 += r["NDCG@50"] |
| avg_rankic += r["Rank IC"] |
| n = len(results) |
| if n > 0: |
| avg_ndcg20 /= n |
| avg_ndcg50 /= n |
| avg_rankic /= n |
| print("-" * 80) |
| print( |
| f"{'AVG':>6} | {avg_ndcg20:>8.4f} | {avg_ndcg50:>8.4f} | " |
| f"{avg_rankic:>8.4f} | {'':>9} | {'':>10} | {'':>8}" |
| ) |
| print(f"{'='*80}\n") |
|
|
| |
| all_pred_df = pd.concat(all_predictions, ignore_index=True) if all_predictions else None |
|
|
| |
| output_dir = Path(args.output) |
| output_dir.mkdir(parents=True, exist_ok=True) |
| model_path = output_dir / f"lgbm_ranker_{MODEL_VERSION}.txt" |
| if best_model is not None: |
| best_model.save_model(str(model_path)) |
| print(f"[output] Model saved: {model_path}") |
| |
| try: |
| from huggingface_hub import HfApi |
| api = HfApi(token=os.environ.get("HF_TOKEN")) |
| api.upload_file( |
| path_or_fileobj=str(model_path), |
| path_in_repo=f"models/lgbm_ranker_{MODEL_VERSION}.txt", |
| repo_id="cedwyh/jinjing-shared-data", |
| repo_type="dataset", |
| ) |
| print(f"[output] Uploaded: cedwyh/jinjing-shared-data/models/lgbm_ranker_{MODEL_VERSION}.txt") |
| except Exception as e: |
| print(f"[output] WARNING: HF upload failed: {e}") |
| |
| |
| if has_priors: |
| print(f"\n{'='*60}") |
| print("PRIOR FACTOR IC COMPARISON (Hold-out / Last Window)") |
| print(f"{'='*60}") |
| |
| val_df_last = all_predictions[-1] if all_predictions else None |
| if val_df_last is not None and len(non_prior_feature_cols) > 0: |
| |
| last_val_groups = build_query_groups(val_df_last) |
| y_last = val_df_last[TARGET_COL].values |
| pred_with = val_df_last["pred_rank"].values |
| ic_with = evaluate_rank_ic(y_last, pred_with, last_val_groups) |
| ndcg20_with = evaluate_ndcg(y_last, pred_with, last_val_groups, 20) |
| ndcg50_with = evaluate_ndcg(y_last, pred_with, last_val_groups, 50) |
| |
| |
| print(" Training baseline model (without priors) for comparison...") |
| train_df_last = None |
| |
| for idx, (train_s, train_e, val_s, val_e) in enumerate(WINDOWS): |
| if idx == len(results) - 1: |
| train_start_ts = pd.Timestamp(train_s).date() |
| train_end_ts = pd.Timestamp(train_e).date() |
| train_df_last = df.loc[ |
| (df[DATE_COL] >= train_start_ts) & (df[DATE_COL] <= train_end_ts) |
| ].reset_index(drop=True) |
| break |
| |
| if train_df_last is not None and len(train_df_last) > 0: |
| baseline_features = [c for c in non_prior_feature_cols if c in train_df_last.columns] |
| if len(baseline_features) > 0: |
| X_base_train = train_df_last[baseline_features].values.astype(np.float32) |
| y_base_train = train_df_last[TARGET_COL].values |
| base_train_groups = build_query_groups(train_df_last) |
| |
| |
| X_base_val = val_df_last[baseline_features].values.astype(np.float32) |
| |
| base_train_data = lgb.Dataset( |
| X_base_train, label=y_base_train, |
| group=base_train_groups, feature_name=baseline_features, |
| ) |
| base_val_data = lgb.Dataset( |
| X_base_val, label=y_last, group=last_val_groups, |
| reference=base_train_data, |
| ) |
| |
| base_model = lgb.train( |
| RANKER_PARAMS, base_train_data, |
| valid_sets=[base_val_data], |
| num_boost_round=NUM_BOOST_ROUND, |
| callbacks=[lgb.early_stopping(EARLY_STOPPING_ROUNDS), lgb.log_evaluation(0)], |
| ) |
| pred_without = base_model.predict(X_base_val) |
| ic_without = evaluate_rank_ic(y_last, pred_without, last_val_groups) |
| ndcg20_without = evaluate_ndcg(y_last, pred_without, last_val_groups, 20) |
| ndcg50_without = evaluate_ndcg(y_last, pred_without, last_val_groups, 50) |
| |
| print(f"\n {'Metric':>12} | {'With Priors':>12} | {'Without':>12} | {'Delta':>12}") |
| print(f" {'-'*12} | {'-'*12} | {'-'*12} | {'-'*12}") |
| print(f" {'NDCG@20':>12} | {ndcg20_with:>12.4f} | {ndcg20_without:>12.4f} | {ndcg20_with - ndcg20_without:>+12.4f}") |
| print(f" {'NDCG@50':>12} | {ndcg50_with:>12.4f} | {ndcg50_without:>12.4f} | {ndcg50_with - ndcg50_without:>+12.4f}") |
| print(f" {'Rank IC':>12} | {ic_with:>12.4f} | {ic_without:>12.4f} | {ic_with - ic_without:>+12.4f}") |
| print(f" {'='*54}") |
| print(f" Prior columns: {prior_cols_in_data}") |
| else: |
| print(" WARNING: No baseline (non-prior) features available for comparison") |
| else: |
| print(" WARNING: Could not locate last training window data") |
| else: |
| print(" WARNING: No validation predictions available for IC comparison") |
| |
| |
| if all_pred_df is not None: |
| try: |
| import io |
| buf = io.BytesIO() |
| all_pred_df.to_parquet(buf, index=False) |
| buf.seek(0) |
| api.upload_file( |
| path_or_fileobj=buf, |
| path_in_repo="models/ranker_predictions.parquet", |
| repo_id="cedwyh/jinjing-shared-data", |
| repo_type="dataset", |
| ) |
| print(f"[output] Uploaded predictions to HF dataset") |
| except Exception as e: |
| print(f"[output] WARNING: Predictions upload failed: {e}") |
| else: |
| print("[output] No model trained, nothing saved") |
|
|
| |
| if all_pred_df is not None: |
| pred_path = output_dir / "ranker_predictions.parquet" |
| all_pred_df.to_parquet(pred_path, index=False) |
| print(f"[output] Predictions saved: {pred_path} ({len(all_pred_df):,} rows)") |
| else: |
| print("[output] No predictions to save") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|