| |
| """ |
| train_metalabeler_v3.py — Binary Meta-Labeler for Jinjing V3 |
| |
| Trains a binary LightGBM classifier using REAL ranker predictions |
| (from ranzer_predictions_v3.parquet or similar). |
| |
| Strategy |
| -------- |
| - Load predictions parquet with columns: date, symbol, label, pred_rank, +features |
| - For each date, select top-K candidates by pred_rank (default top-200) |
| - Use 'label' column (0/1) directly as the meta-label |
| - Time-based train/test split (80/20 by date) |
| - Train binary LightGBM with 5-fold time-aware CV |
| - Evaluate AUC, precision, recall, confusion matrix |
| - Upload model to HF dataset |
| |
| Usage: |
| export HF_TOKEN=hf_... |
| python train_metalabeler_v3.py \ |
| --predictions /tmp/ranker_predictions_v3.parquet \ |
| --output /tmp/meta_labeler_v3.txt |
| |
| Output: |
| - /tmp/meta_labeler_v3.txt (LightGBM Booster text dump) |
| - Uploaded to cedwyh/jinjing-shared-data/models/meta_labeler_v3.txt |
| - Console: AUC, Precision@K, best threshold, confusion matrix |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import os |
| import sys |
| import warnings |
| from pathlib import Path |
|
|
| import numpy as np |
| import pandas as pd |
| from sklearn.metrics import ( |
| confusion_matrix, |
| precision_score, |
| recall_score, |
| roc_auc_score, |
| roc_curve, |
| ) |
| from sklearn.model_selection import TimeSeriesSplit |
|
|
| |
| |
| |
| warnings.filterwarnings("ignore", category=UserWarning, module="lightgbm") |
| try: |
| import lightgbm as lgb |
| except ImportError as exc: |
| print(f"[FATAL] lightgbm is required — install with: pip install lightgbm") |
| sys.exit(1) |
|
|
|
|
| |
| |
| |
| HF_REPO = "cedwyh/jinjing-shared-data" |
| DEFAULT_TOP_K = 200 |
| DEFAULT_CV_FOLDS = 5 |
| DEFAULT_OUTPUT = "/tmp/meta_labeler_v3.txt" |
| DEFAULT_PREDICTIONS = "/tmp/ranker_predictions_v3.parquet" |
| RANDOM_STATE = 42 |
| TRAIN_SPLIT = 0.8 |
| SCRIPT_DIR = Path(__file__).parent.resolve() |
| RESULTS_DIR = SCRIPT_DIR / "results" |
|
|
|
|
| |
| |
| |
| def load_predictions(path: str) -> pd.DataFrame: |
| """Load the predictions parquet file. If not found locally, download from HF dataset.""" |
| import os |
| if not os.path.isfile(path): |
| print(f" Local file not found: {path}", flush=True) |
| print(f" Downloading from HF dataset cedwyh/jinjing-shared-data/models/ranker_predictions.parquet ...", flush=True) |
| from huggingface_hub import hf_hub_download |
| token = os.environ.get("HF_TOKEN") |
| path = hf_hub_download( |
| repo_id="cedwyh/jinjing-shared-data", |
| filename="models/ranker_predictions.parquet", |
| repo_type="dataset", |
| token=token, |
| ) |
| print(f" Downloaded to cache: {path}", flush=True) |
| print(f"[1/7] Loading predictions from {path} …", flush=True) |
| df = pd.read_parquet(path) |
| required = {"date", "symbol", "label", "pred_rank"} |
| missing = required - set(df.columns) |
| if missing: |
| print(f"[FATAL] Missing required columns: {missing}", flush=True) |
| sys.exit(1) |
| print(f" Loaded {len(df):,} rows × {len(df.columns)} cols", flush=True) |
| print(f" Date range: {df['date'].min()} to {df['date'].max()}", flush=True) |
| print(f" Symbols: {df['symbol'].nunique():,}", flush=True) |
| return df |
|
|
|
|
| |
| |
| |
| def build_meta_dataset( |
| df: pd.DataFrame, |
| top_k: int = DEFAULT_TOP_K, |
| ) -> pd.DataFrame: |
| """ |
| For each date, select top-K stocks by pred_rank, use label directly as meta_label. |
| |
| Parameters |
| ---------- |
| df : DataFrame with columns [date, symbol, label, pred_rank, ...features] |
| top_k : number of top candidates per date to keep |
| |
| Returns |
| ------- |
| DataFrame with meta_label (0/1) and feature columns. |
| """ |
| print(f"[2/7] Selecting top-{top_k} candidates per date by pred_rank …", flush=True) |
|
|
| |
| df = df.copy() |
| df["_rank_in_date"] = df.groupby("date")["pred_rank"].rank( |
| method="dense", ascending=False |
| ) |
| candidates = df[df["_rank_in_date"] <= top_k].copy() |
| candidates = candidates.drop(columns=["_rank_in_date"]) |
|
|
| |
| candidates["_meta_label"] = candidates["label"].astype(int) |
|
|
| print(f" Candidates selected: {len(candidates):,} rows", flush=True) |
|
|
| |
| pos = (candidates["_meta_label"] == 1).sum() |
| neg = (candidates["_meta_label"] == 0).sum() |
| print(f" Positives (label=1): {pos:,} " |
| f"Negatives (label=0): {neg:,} " |
| f"Ratio: {pos/neg:.3f}", flush=True) |
|
|
| |
| print(f" Date range: {candidates['date'].min()} to {candidates['date'].max()}", flush=True) |
| print(f" Unique dates: {candidates['date'].nunique()}", flush=True) |
|
|
| return candidates |
|
|
|
|
| |
| |
| |
| def get_feature_columns(df: pd.DataFrame) -> list[str]: |
| """Identify feature columns (exclude metadata / id / label columns).""" |
| exclude = { |
| "date", "symbol", "label", "pred_rank", "query_group", "trend_type", |
| "_meta_label", "_pred_score", "_rank_in_date", "index", |
| } |
| return [ |
| c for c in df.columns |
| if c.lower() not in exclude and not c.startswith("__") |
| ] |
|
|
|
|
| def prepare_xy( |
| df: pd.DataFrame, |
| feature_cols: list[str] | None = None, |
| ) -> tuple[pd.DataFrame, pd.Series, np.ndarray | None]: |
| """Extract feature matrix X, target y, and optional sample weights.""" |
| if feature_cols is None: |
| feature_cols = get_feature_columns(df) |
|
|
| X = df[feature_cols].copy() |
| y = df["_meta_label"].values |
|
|
| |
| assert X.shape[1] > 0, "No feature columns found!" |
| assert y.ndim == 1 |
|
|
| |
| nan_count = X.isna().sum().sum() |
| if nan_count > 0: |
| print(f" Warning: {nan_count} NaN values in features — filling with 0.", |
| flush=True) |
| X = X.fillna(0) |
|
|
| |
| for col in X.columns: |
| if X[col].dtype == "object": |
| print(f" Warning: dropping non-numeric feature '{col}'", flush=True) |
| X = X.drop(columns=[col]) |
|
|
| return X, y, None |
|
|
|
|
| |
| |
| |
| def time_split( |
| df: pd.DataFrame, |
| train_frac: float = TRAIN_SPLIT, |
| ) -> tuple[pd.DataFrame, pd.DataFrame]: |
| """Split by date: oldest train_frac fraction of dates for training, rest for test.""" |
| dates = sorted(df["date"].unique()) |
| split_idx = int(len(dates) * train_frac) |
| train_dates = set(dates[:split_idx]) |
| test_dates = set(dates[split_idx:]) |
|
|
| train_df = df[df["date"].isin(train_dates)].copy() |
| test_df = df[df["date"].isin(test_dates)].copy() |
|
|
| print(f"[3/7] Time-based split: {len(train_dates)} train dates " |
| f"({df[df['date'].isin(train_dates)]['_meta_label'].sum():,} positives), " |
| f"{len(test_dates)} test dates " |
| f"({df[df['date'].isin(test_dates)]['_meta_label'].sum():,} positives)", |
| flush=True) |
| print(f" Train: {len(train_df):,} rows, Test: {len(test_df):,} rows", |
| flush=True) |
|
|
| return train_df, test_df |
|
|
|
|
| |
| |
| |
| def train_cv( |
| X: pd.DataFrame, |
| y: np.ndarray, |
| n_folds: int = DEFAULT_CV_FOLDS, |
| random_state: int = RANDOM_STATE, |
| ) -> tuple[lgb.Booster, float, np.ndarray]: |
| """ |
| Time-series cross-validation using expanding window. |
| |
| Splits are sequential — train on past, validate on future — matching |
| how the model will be used in production. |
| |
| Returns |
| ------- |
| (trained_booster, mean_val_auc, oof_preds) |
| """ |
| print(f"[4/7] Training LightGBM with {n_folds}-fold time-series CV …", flush=True) |
|
|
| tscv = TimeSeriesSplit(n_splits=n_folds) |
|
|
| params = { |
| "objective": "binary", |
| "metric": "auc", |
| "boosting_type": "gbdt", |
| "num_leaves": 63, |
| "learning_rate": 0.05, |
| "feature_fraction": 0.8, |
| "bagging_fraction": 0.8, |
| "bagging_freq": 5, |
| "reg_alpha": 0.1, |
| "reg_lambda": 1.0, |
| "verbose": -1, |
| "seed": random_state, |
| "first_metric_only": True, |
| } |
|
|
| fold_models: list[lgb.Booster] = [] |
| fold_aucs: list[float] = [] |
| oof_preds = np.zeros(len(y), dtype=np.float64) |
|
|
| for fold, (train_idx, val_idx) in enumerate(tscv.split(X)): |
| X_tr, X_val = X.iloc[train_idx], X.iloc[val_idx] |
| y_tr, y_val = y[train_idx], y[val_idx] |
|
|
| train_data = lgb.Dataset(X_tr, label=y_tr) |
| val_data = lgb.Dataset(X_val, label=y_val, reference=train_data) |
|
|
| model = lgb.train( |
| params=params, |
| train_set=train_data, |
| valid_sets=[val_data], |
| valid_names=["valid"], |
| callbacks=[ |
| lgb.early_stopping(stopping_rounds=50, verbose=False), |
| lgb.log_evaluation(period=10), |
| ], |
| num_boost_round=1000, |
| ) |
|
|
| fold_pred = model.predict(X_val, num_iteration=model.best_iteration) |
| fold_auc = roc_auc_score(y_val, fold_pred) |
| oof_preds[val_idx] = fold_pred |
|
|
| fold_models.append(model) |
| fold_aucs.append(fold_auc) |
| print(f" Fold {fold + 1}/{n_folds} — AUC = {fold_auc:.5f} " |
| f"(best_iter={model.best_iteration})", flush=True) |
|
|
| mean_val_auc = float(np.mean(fold_aucs)) |
| oof_auc = roc_auc_score(y, oof_preds) |
|
|
| print(f" Mean CV AUC = {mean_val_auc:.5f}", flush=True) |
| print(f" Out-of-fold AUC = {oof_auc:.5f}", flush=True) |
|
|
| |
| print(" Retraining on full training set …", flush=True) |
| full_data = lgb.Dataset(X, label=y) |
| best_rounds = int(np.median([m.best_iteration for m in fold_models])) |
| final_model = lgb.train( |
| params=params, |
| train_set=full_data, |
| num_boost_round=best_rounds, |
| valid_sets=[full_data], |
| valid_names=["train"], |
| callbacks=[lgb.log_evaluation(period=0)], |
| ) |
|
|
| |
| RESULTS_DIR.mkdir(parents=True, exist_ok=True) |
| metrics = { |
| "fold_aucs": [float(a) for a in fold_aucs], |
| "mean_cv_auc": mean_val_auc, |
| "oof_auc": oof_auc, |
| "best_iterations": [m.best_iteration for m in fold_models], |
| "median_best_iteration": best_rounds, |
| "n_folds": n_folds, |
| "n_train": len(X), |
| } |
| metrics_path = RESULTS_DIR / "train_metalabeler_v3_metrics.json" |
| try: |
| with open(metrics_path, "w") as fh: |
| json.dump(metrics, fh, indent=2) |
| print(f" Metrics saved to {metrics_path}", flush=True) |
| except Exception as e: |
| print(f" WARNING: Could not save metrics: {e}", flush=True) |
|
|
| return final_model, oof_auc, oof_preds |
|
|
|
|
| |
| |
| |
| def evaluate( |
| y_true: np.ndarray, |
| y_pred: np.ndarray, |
| label: str = "Test", |
| ) -> tuple[float, list[tuple[int, float, float]]]: |
| """ |
| Evaluate binary classifier on a hold-out set. |
| |
| Returns |
| ------- |
| (best_threshold, precision_at_k_list) |
| """ |
| print(f"[5/7] Evaluating on {label} set …", flush=True) |
|
|
| auc = roc_auc_score(y_true, y_pred) |
| fpr, tpr, roc_thresholds = roc_curve(y_true, y_pred) |
|
|
| |
| youden = tpr - fpr |
| best_idx = int(np.argmax(youden)) |
| best_thr = float(roc_thresholds[best_idx]) |
|
|
| print(f" AUC = {auc:.5f}", flush=True) |
| print(f" Best threshold = {best_thr:.5f} (Youden index)", flush=True) |
|
|
| |
| order = np.argsort(y_pred)[::-1] |
| y_sorted = y_true[order] |
| precisions: list[tuple[int, float, float]] = [] |
| for k in (10, 20, 50, 100, 200): |
| if k <= len(y_sorted): |
| prec_k = float(precision_score(y_sorted[:k], np.ones(k), zero_division=0.0)) |
| else: |
| prec_k = float(precision_score(y_sorted, np.ones(len(y_sorted)), zero_division=0.0)) |
| precisions.append((k, prec_k, best_thr)) |
| print(f" Precision@{k:<3d} = {prec_k:.5f}", flush=True) |
|
|
| |
| y_pred_bin = (y_pred >= best_thr).astype(int) |
| tn, fp, fn, tp = confusion_matrix(y_true, y_pred_bin).ravel() |
| print(f"\n Confusion Matrix @ threshold = {best_thr:.5f}", flush=True) |
| print(f" Pred Neg Pred Pos", flush=True) |
| print(f" Actual Neg {tn:>8d} {fp:>8d}", flush=True) |
| print(f" Actual Pos {fn:>8d} {tp:>8d}", flush=True) |
| total = tn + fp + fn + tp |
| acc = (tn + tp) / total |
| prec = tp / (tp + fp) if (tp + fp) > 0 else 0.0 |
| rec = tp / (tp + fn) if (tp + fn) > 0 else 0.0 |
| f1 = 2 * prec * rec / (prec + rec) if (prec + rec) > 0 else 0.0 |
| print(f" Accuracy = {acc:.5f}", flush=True) |
| print(f" Precision = {prec:.5f}", flush=True) |
| print(f" Recall = {rec:.5f}", flush=True) |
| print(f" F1 = {f1:.5f}", flush=True) |
|
|
| return best_thr, precisions |
|
|
|
|
| |
| |
| |
| def save_model(model: lgb.Booster, path: str) -> None: |
| """Save LightGBM booster in text format and upload to HF dataset.""" |
| import shutil |
|
|
| |
| tmp_path = "/tmp/meta_labeler_v3.txt" |
| model.save_model(tmp_path) |
| print(f" Model saved to {tmp_path}", flush=True) |
|
|
| |
| if path and path != tmp_path: |
| try: |
| shutil.copy(tmp_path, path) |
| print(f" Copied to {path}", flush=True) |
| except Exception as e: |
| print(f" WARNING: Could not copy to {path}: {e}", flush=True) |
|
|
| |
| try: |
| from huggingface_hub import HfApi |
| api = HfApi(token=os.environ.get("HF_TOKEN")) |
| api.upload_file( |
| path_or_fileobj=tmp_path, |
| path_in_repo="models/meta_labeler_v3.txt", |
| repo_id="cedwyh/jinjing-shared-data", |
| repo_type="dataset", |
| ) |
| print(f" Uploaded: cedwyh/jinjing-shared-data/models/meta_labeler_v3.txt", |
| flush=True) |
| except Exception as e: |
| print(f" WARNING: HF upload failed: {e}", flush=True) |
|
|
| fsize = os.path.getsize(tmp_path) / 1024 |
| print(f" Model saved ({fsize:.1f} KB).", flush=True) |
|
|
|
|
| |
| |
| |
| def print_summary( |
| oof_auc: float, |
| test_auc: float, |
| test_threshold: float, |
| test_precisions: list[tuple[int, float, float]], |
| feature_cols: list[str], |
| ) -> None: |
| """Final summary table.""" |
| print(f"[7/7] Final Summary", flush=True) |
| print("=" * 60, flush=True) |
| print(f" {'Metric':<25s} {'Value':>12s}", flush=True) |
| print("-" * 60, flush=True) |
| print(f" {'CV OOF AUC':<25s} {oof_auc:>12.5f}", flush=True) |
| print(f" {'Test AUC':<25s} {test_auc:>12.5f}", flush=True) |
| print(f" {'Test best threshold':<25s} {test_threshold:>12.5f}", flush=True) |
| for k, p, _ in test_precisions: |
| print(f" {'Test Precision@' + str(k):<25s} {p:>12.5f}", flush=True) |
| print(f" {'Features':<25s} {len(feature_cols):>12d}", flush=True) |
| print("=" * 60, flush=True) |
|
|
|
|
| |
| |
| |
| def parse_args(argv: list[str] | None = None) -> argparse.Namespace: |
| parser = argparse.ArgumentParser( |
| description="Train a binary meta-labeler for Jinjing V3 using real ranker predictions.", |
| formatter_class=argparse.ArgumentDefaultsHelpFormatter, |
| ) |
| parser.add_argument( |
| "--predictions", |
| type=str, |
| default=DEFAULT_PREDICTIONS, |
| help="Path to predictions parquet file.", |
| ) |
| parser.add_argument( |
| "--top-k", |
| type=int, |
| default=DEFAULT_TOP_K, |
| help="Number of top candidates per date by pred_rank.", |
| ) |
| parser.add_argument( |
| "--cv-folds", |
| type=int, |
| default=DEFAULT_CV_FOLDS, |
| help="Number of cross-validation folds.", |
| ) |
| parser.add_argument( |
| "--output", |
| type=str, |
| default=DEFAULT_OUTPUT, |
| help="Path to save the trained LightGBM model (text format).", |
| ) |
| parser.add_argument( |
| "--train-split", |
| type=float, |
| default=TRAIN_SPLIT, |
| help="Fraction of dates (oldest) for training.", |
| ) |
| parser.add_argument( |
| "--hf-token", |
| type=str, |
| default=None, |
| help="Hugging Face token (default: $HF_TOKEN).", |
| ) |
| return parser.parse_args(argv) |
|
|
|
|
| |
| |
| |
| def main() -> None: |
| args = parse_args() |
| hf_token = args.hf_token or os.environ.get("HF_TOKEN") |
| if not hf_token: |
| print( |
| "[FATAL] HF_TOKEN not set. Provide via --hf-token or " |
| "the HF_TOKEN environment variable.", |
| flush=True, |
| ) |
| sys.exit(1) |
|
|
| |
| if not 0 < args.train_split < 1: |
| print(f"[FATAL] --train-split must be between 0 and 1 (got {args.train_split})", |
| flush=True) |
| sys.exit(1) |
|
|
| |
| df = load_predictions(args.predictions) |
|
|
| |
| meta_df = build_meta_dataset(df, top_k=args.top_k) |
|
|
| |
| feat_cols = get_feature_columns(meta_df) |
| print(f"[3/7] Using {len(feat_cols)} feature columns: " |
| f"{', '.join(feat_cols)}", flush=True) |
|
|
| |
| train_df, test_df = time_split(meta_df, train_frac=args.train_split) |
|
|
| |
| train_df = train_df.sort_values("date").reset_index(drop=True) |
|
|
| |
| X_tr, y_tr, _ = prepare_xy(train_df, feat_cols) |
| X_te, y_te, _ = prepare_xy(test_df, feat_cols) |
|
|
| |
| model, oof_auc, oof_preds = train_cv(X_tr, y_tr, n_folds=args.cv_folds) |
|
|
| |
| test_preds = model.predict(X_te, num_iteration=model.best_iteration) |
| test_thr, test_precisions = evaluate(y_te, test_preds, label="Test") |
|
|
| |
| save_model(model, args.output) |
|
|
| |
| print_summary(oof_auc, roc_auc_score(y_te, test_preds), test_thr, test_precisions, feat_cols) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|