| |
| """ |
| train_metalabeler.py — Binary Meta-Labeler for Jinjing (金睛) V2 v1.0 |
| |
| Trains a binary LightGBM classifier on top of ranking model candidates. |
| Reads ranking data from HF Hub, simulates a Top-K candidate selection |
| using noisy ranking scores, and trains a meta-labeler that filters |
| false positives from the ranker's Top-200 list. |
| |
| Usage: |
| export HF_TOKEN=hf_... |
| python train_metalabeler.py [--top-k 200] [--cv-folds 5] |
| [--output /tmp/meta_labeler_v1.txt] |
| |
| Output: |
| - /tmp/meta_labeler_v1.txt (LightGBM Booster text dump) |
| - Console: AUC, Precision@K, best threshold, confusion matrix |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import os |
| import sys |
| import warnings |
| from pathlib import Path |
|
|
| import numpy as np |
| import pandas as pd |
| from huggingface_hub import hf_hub_download |
| from sklearn.metrics import ( |
| auc as sk_auc, |
| confusion_matrix, |
| precision_score, |
| roc_auc_score, |
| roc_curve, |
| ) |
| from sklearn.model_selection import StratifiedKFold |
|
|
| |
| |
| |
| 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" |
| HF_FILE = "ranking_train_data_v1.parquet" |
| DEFAULT_TOP_K = 200 |
| DEFAULT_CV_FOLDS = 5 |
| DEFAULT_LABEL_THRESH_HIGH = 8 |
| DEFAULT_LABEL_THRESH_LOW = 3 |
| DEFAULT_OUTPUT = "/tmp/meta_labeler_v1.txt" |
| RANDOM_STATE = 42 |
|
|
|
|
| |
| |
| |
| def load_data(hf_token: str | None = None) -> pd.DataFrame: |
| """Download and load the ranking parquet from Hugging Face Hub.""" |
| print("[1/6] Loading data from Hugging Face Hub …", flush=True) |
| local_path = hf_hub_download( |
| repo_id=HF_REPO, |
| filename=HF_FILE, |
| repo_type="dataset", |
| token=hf_token, |
| ) |
| df = pd.read_parquet(local_path) |
| print(f" Loaded {len(df):,} rows × {len(df.columns)} cols", flush=True) |
| return df |
|
|
|
|
| |
| |
| |
| def build_meta_dataset( |
| df: pd.DataFrame, |
| top_k: int = DEFAULT_TOP_K, |
| thr_high: int = DEFAULT_LABEL_THRESH_HIGH, |
| thr_low: int = DEFAULT_LABEL_THRESH_LOW, |
| noise_scale: float = 0.8, |
| rng_seed: int = RANDOM_STATE, |
| ) -> pd.DataFrame: |
| """ |
| Simulate a ranker's predicted scores and build a binary meta-label |
| training set. |
| |
| Strategy |
| -------- |
| - `label_rank` (1-10) is the ground-truth decile rank. |
| - We simulate *predicted scores* as ``label_rank + N(0, noise_scale)`` |
| so the meta-labeler sees realistic imperfect rankings. |
| - Within each date, the top-*top_k* stocks by simulated score are |
| kept as *candidates*. |
| - A candidate gets meta-label = 1 if its true rank >= thr_high (good), |
| 0 if its true rank <= thr_low (bad). Middle ranks are discarded. |
| """ |
| rng = np.random.default_rng(rng_seed) |
|
|
| print("[2/6] Simulating ranking scores …", flush=True) |
|
|
| |
| date_col = "date" if "date" in df.columns else df.columns[0] |
| rank_col = "label_rank" if "label_rank" in df.columns else None |
| if rank_col is None: |
| print("[FATAL] Column 'label_rank' not found in dataset.", flush=True) |
| sys.exit(1) |
|
|
| df = df.copy() |
| |
| df["_pred_score"] = df[rank_col] + rng.normal(0, noise_scale, size=len(df)) |
|
|
| |
| print(f" Selecting top-{top_k} candidates per date …", flush=True) |
| candidates = ( |
| df.groupby(date_col, group_keys=False) |
| .apply(lambda g: g.nlargest(top_k, "_pred_score"), include_groups=False) |
| .reset_index(drop=True) |
| ) |
|
|
| |
| candidates["_meta_label"] = np.nan |
| candidates.loc[candidates[rank_col] >= thr_high, "_meta_label"] = 1 |
| candidates.loc[candidates[rank_col] <= thr_low, "_meta_label"] = 0 |
|
|
| before = len(candidates) |
| candidates = candidates.dropna(subset=["_meta_label"]).reset_index(drop=True) |
| candidates["_meta_label"] = candidates["_meta_label"].astype(int) |
| print( |
| f" Discarded middle ranks ({thr_low+1}–{thr_high-1}): " |
| f"{before - len(candidates)} rows removed.", |
| flush=True, |
| ) |
| print(f" Meta-label training set: {len(candidates):,} rows", flush=True) |
|
|
| |
| pos = (candidates["_meta_label"] == 1).sum() |
| neg = (candidates["_meta_label"] == 0).sum() |
| print(f" Positives (label=1, rank≥{thr_high}): {pos:,} " |
| f"Negatives (label=0, rank≤{thr_low}): {neg:,} " |
| f"Ratio: {pos/neg:.3f}", flush=True) |
|
|
| return candidates |
|
|
|
|
| |
| |
| |
| def get_feature_columns(df: pd.DataFrame) -> list[str]: |
| """Identify feature columns (exclude metadata / label columns).""" |
| exclude = { |
| "date", "stock_id", "symbol", "ticker", "ts_code", |
| "label_rank", "_pred_score", "_meta_label", "index", |
| } |
| return [c for c in df.columns if c.lower() not in exclude] |
|
|
|
|
| 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) |
|
|
| return X, y, None |
|
|
|
|
| |
| |
| |
| def train_cv( |
| X: pd.DataFrame, |
| y: np.ndarray, |
| n_folds: int = DEFAULT_CV_FOLDS, |
| random_state: int = RANDOM_STATE, |
| ) -> tuple[lgb.Booster, float, float]: |
| """ |
| 5-fold stratified cross-validation with early stopping. |
| |
| Parameters |
| ---------- |
| X, y : training data |
| n_folds : number of CV folds (default 5) |
| |
| Returns |
| ------- |
| (trained_booster, mean_val_auc, oof_auc) |
| """ |
| print(f"[3/6] Training LightGBM with {n_folds}-fold CV …", flush=True) |
|
|
| skf = StratifiedKFold( |
| n_splits=n_folds, shuffle=True, random_state=random_state |
| ) |
|
|
| 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, |
| "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(skf.split(X, y)): |
| 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=0), |
| ], |
| num_boost_round=2000, |
| ) |
|
|
| 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}", 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 dataset …", 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)], |
| ) |
|
|
| return final_model, oof_auc, oof_preds |
|
|
|
|
| |
| |
| |
| def evaluate( |
| y_true: np.ndarray, |
| y_pred: np.ndarray, |
| thresholds: list[float] | None = None, |
| ) -> tuple[float, list[tuple[int, float, float]]]: |
| """ |
| Evaluate binary classifier. |
| |
| Returns |
| ------- |
| (best_threshold, precision_at_k_list) |
| where precision_at_k_list = [(K, precision, threshold_for_K), ...] |
| """ |
| print("[4/6] Evaluating on out-of-fold predictions …", 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): |
| prec_k = float(precision_score(y_sorted[:k], np.ones(k), 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_v1.txt" |
| model.save_model(tmp_path) |
| print(f" Model saved to {tmp_path}") |
| |
| |
| if path and path != tmp_path: |
| try: |
| shutil.copy(tmp_path, path) |
| print(f" Copied to {path}") |
| except Exception as e: |
| print(f" WARNING: Could not copy to {path}: {e}") |
| |
| |
| 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_v1.txt", |
| repo_id="cedwyh/jinjing-shared-data", |
| repo_type="dataset", |
| ) |
| print(f" Uploaded: cedwyh/jinjing-shared-data/models/meta_labeler_v1.txt") |
| except Exception as e: |
| print(f" WARNING: HF upload failed: {e}") |
| print(f" Model saved ({os.path.getsize(tmp_path)/1024:.1f} KB).", flush=True) |
|
|
|
|
| |
| |
| |
| def print_summary( |
| auc: float, |
| precisions: list[tuple[int, float, float]], |
| best_thr: float, |
| ) -> None: |
| """Final summary table.""" |
| print(f"[6/6] Final Summary", flush=True) |
| print("=" * 52, flush=True) |
| print(f" {'Metric':<22s} {'Value':>10s}", flush=True) |
| print("-" * 52, flush=True) |
| print(f" {'AUC':<22s} {auc:>10.5f}", flush=True) |
| for k, p, _ in precisions: |
| print(f" {'Precision@' + str(k):<22s} {p:>10.5f}", flush=True) |
| print(f" {'Best threshold':<22s} {best_thr:>10.5f}", flush=True) |
| print("=" * 52, flush=True) |
|
|
|
|
| |
| |
| |
| def parse_args(argv: list[str] | None = None) -> argparse.Namespace: |
| parser = argparse.ArgumentParser( |
| description="Train a binary meta-labeler for Jinjing V2.", |
| formatter_class=argparse.ArgumentDefaultsHelpFormatter, |
| ) |
| parser.add_argument( |
| "--top-k", |
| type=int, |
| default=DEFAULT_TOP_K, |
| help="Number of top candidates per date to keep.", |
| ) |
| 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( |
| "--noise-scale", |
| type=float, |
| default=0.8, |
| help="Standard deviation of Gaussian noise added to label_rank " |
| "for simulated predictions.", |
| ) |
| parser.add_argument( |
| "--high-threshold", |
| type=int, |
| default=DEFAULT_LABEL_THRESH_HIGH, |
| help="label_rank >= this value => positive class.", |
| ) |
| parser.add_argument( |
| "--low-threshold", |
| type=int, |
| default=DEFAULT_LABEL_THRESH_LOW, |
| help="label_rank <= this value => negative class.", |
| ) |
| 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) |
|
|
| |
| df = load_data(hf_token) |
|
|
| |
| meta_df = build_meta_dataset( |
| df, |
| top_k=args.top_k, |
| thr_high=args.high_threshold, |
| thr_low=args.low_threshold, |
| noise_scale=args.noise_scale, |
| ) |
|
|
| |
| feat_cols = get_feature_columns(meta_df) |
| print(f" Using {len(feat_cols)} feature columns.", flush=True) |
| X, y, _ = prepare_xy(meta_df, feat_cols) |
|
|
| |
| model, oof_auc, oof_preds = train_cv(X, y, n_folds=args.cv_folds) |
|
|
| |
| best_thr, precisions = evaluate(y, oof_preds) |
|
|
| |
| save_model(model, args.output) |
|
|
| |
| print_summary(oof_auc, precisions, best_thr) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|