jinjing-shared-data / build_data.py
cedwyh's picture
Upload build_data.py with huggingface_hub
dda9a3d verified
Raw
History Blame Contribute Delete
26.4 kB
#!/usr/bin/env python3
"""
build_ranking_data.py — Jinjing V2 Ranking Training Data Construction
Builds a training matrix for LGBMRanker (lambdarank) by:
1. Loading chan_engine_features + all_features_v2 from HuggingFace dataset
2. Merging on (date, symbol)
3. Adding 4 cross-sectional rank features per date
4. Computing PRISM-VQ prior_* factor columns (13 classic cross-sectional priors)
5. Creating ranking label (forward_20d_ret decile 1-10)
6. Adding query_group column (sequential group ID per date)
7. Dropping rows with any NaN in feature columns
8. Saving to parquet
Usage:
python build_ranking_data.py --output /tmp/ranking_train_data.parquet
python build_ranking_data.py --output /tmp/ranking_train_data.parquet --sample 1000
Environment:
HF_TOKEN: HuggingFace token for dataset access
"""
import argparse
import os
import sys
import warnings
from datetime import datetime
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore")
# ── PRISM-VQ prior factors (optional) ──
try:
from factor_priors import compute_all_priors, PRIOR_COLUMNS
except ImportError:
compute_all_priors = None
PRIOR_COLUMNS = []
# ---------------------------------------------------------------------------
# Column definitions
# ---------------------------------------------------------------------------
CHAN_FEATURE_COLS = [
"buy1", "buy2", "buy3", "sell1", "sell2", "sell3",
"bi_strength", "zhongshu_amplitude", "dist_last_buy", "bi_zhongshu_count",
]
# V5 proxy features in V2 parquet (actual names, not f1_ prefix)
V5_FEATURE_COLS = [
"buy_decay", "sell_decay", "zs_pos", "zs_width", "zs_time",
"momentum_div", "volume_div", "slope", "trend_consistency",
"regime_prob", "leg_progress", "structure_progress",
]
# Selected quant + technical features that exist in V2 parquet
V2_QUANT_FEATURE_COLS = [
"ret_1d", "ret_5d", "ret_10d", "ret_20d", "ret_30d", "ret_60d",
"ma_5", "ma_20", "ma_60",
"volatility_10d", "volatility_20d",
"vol_ma5", "vol_ma20",
"rsi_12", "rsi_24",
"macd_hist",
"atr_14",
"close_pos_20d", "close_pos_60d",
"vol_ratio_5", "vol_ratio_20",
]
RANK_FEATURE_COLS = [
"rank_bi_strength", "rank_zhongshu", "rank_momentum", "rank_volume",
]
ID_COLS = ["date", "symbol"]
LABEL_COL = "label_rank"
ALL_FEATURE_COLS = (
CHAN_FEATURE_COLS + V5_FEATURE_COLS + V2_QUANT_FEATURE_COLS + RANK_FEATURE_COLS
)
OUTPUT_COLS = ID_COLS + ["query_group"] + ALL_FEATURE_COLS + [LABEL_COL]
def load_hf_parquet(dataset_name: str, file_name: str, token: str | None = None) -> pd.DataFrame:
"""Load a parquet file from a HuggingFace dataset using hf_hub_download."""
try:
from huggingface_hub import hf_hub_download
path = hf_hub_download(repo_id=dataset_name, filename=file_name, repo_type="dataset")
return pd.read_parquet(path)
except Exception:
import io, urllib.request
url = f"https://huggingface.co/datasets/{dataset_name}/resolve/main/{file_name}?download=1"
if token:
headers = {"Authorization": f"Bearer {token}"}
else:
headers = {}
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=300) as resp:
data = resp.read()
return pd.read_parquet(io.BytesIO(data))
def try_load_sample(path: str) -> pd.DataFrame | None:
"""Try loading a local sample parquet file (for dev/testing)."""
if os.path.exists(path):
print(f" Loading sample from {path}")
return pd.read_parquet(path)
return None
def rank_percentile(series: pd.Series) -> pd.Series:
"""Compute within-group percentile rank (0-1)."""
ranks = series.rank(method="average", ascending=True)
return (ranks - 1) / max(ranks.max() - 1, 1)
def compute_forward_return(
df: pd.DataFrame, price_col: str = "close", period: int = 20
) -> pd.DataFrame:
"""
Compute forward_{period}d_ret for each symbol.
Uses price_col; if not found, looks for 'close' or raises.
"""
if price_col not in df.columns:
candidates = [c for c in df.columns if "close" in c.lower()]
if candidates:
price_col = candidates[0]
else:
raise KeyError(
f"Price column '{price_col}' not found in V2 features and no close-like column available. "
"Cannot compute forward returns."
)
df = df.copy()
df = df.sort_values(["symbol", "date"])
df[f"forward_{period}d_ret"] = (
df.groupby("symbol")[price_col].shift(-period) / df[price_col] - 1
)
return df
def main():
parser = argparse.ArgumentParser(
description="Jinjing V2 Ranking Training Data Construction"
)
parser.add_argument(
"--output",
type=str,
default="/tmp/ranking_train_data.parquet",
help="Output parquet path (default: /tmp/ranking_train_data.parquet)",
)
parser.add_argument(
"--sample",
type=int,
default=None,
help="Sample N rows for testing (default: use all data)",
)
parser.add_argument(
"--dataset",
type=str,
default="cedwyh/jinjing-shared-data",
help="HuggingFace dataset name (default: cedwyh/jinjing-shared-data)",
)
parser.add_argument(
"--use-priors",
action=argparse.BooleanOptionalAction,
default=True,
help="Compute PRISM-VQ prior_* feature columns (default: True). Requires OHLCV columns.",
)
args = parser.parse_args()
hf_token = os.environ.get("HF_TOKEN")
if not hf_token:
print("[WARN] HF_TOKEN not set. Trying without token (public dataset)...")
print("=" * 60)
print("Jinjing V2 — Ranking Training Data Builder")
print("=" * 60)
print(f"Output: {args.output}")
if args.sample:
print(f"Sample mode: {args.sample} rows")
print()
# -----------------------------------------------------------------------
# Step 1: Load data
# -----------------------------------------------------------------------
print("[1/7] Loading data...")
# Try local samples first (dev environment)
df_chan = try_load_sample("/tmp/chan_sample.parquet")
if df_chan is None:
print(" Loading chan_engine_features.parquet from HuggingFace...")
df_chan = load_hf_parquet(
args.dataset, "chan_engine_features.parquet", hf_token
)
df_v2 = try_load_sample("/tmp/v2_sample.parquet")
if df_v2 is None:
print(" Loading all_features_v2.parquet from HuggingFace...")
df_v2 = load_hf_parquet(args.dataset, "all_features_v2.parquet", hf_token)
print(f" chan_engine_features: {df_chan.shape[0]:,} rows x {df_chan.shape[1]} cols")
print(f" all_features_v2: {df_v2.shape[0]:,} rows x {df_v2.shape[1]} cols")
print()
# -----------------------------------------------------------------------
# Step 2: Merge on (date, symbol)
# -----------------------------------------------------------------------
print("[2/7] Merging chan + V2 features on (date, symbol)...")
# ── Date type defense layer 1: normalize all sources to string YYYY-MM-DD ──
for name, d in [("chan", df_chan), ("v2", df_v2)]:
if "date" in d.columns:
before = str(d["date"].dtype)
# Use format='mixed' to handle YYYY-MM-DD, 20100104, 2010-01-04 00:00:00 etc.
d["date"] = pd.to_datetime(
d["date"], format="mixed", errors="coerce"
).dt.strftime("%Y-%m-%d")
n_null = d["date"].isna().sum()
if n_null > 0:
print(
f" ⚠️ {name}: {n_null} date values still failed to parse"
f" (sampling NaNs: {d.loc[d['date'].isna(), 'date'].head(3).tolist()})"
)
# Fallback 1: brute-force truncation for any that coerce failed
d["date"] = d["date"].fillna(
d["date"].astype(str).str[:10]
)
n_null2 = d["date"].isna().sum()
print(f" {name}: {before}{d['date'].dtype} (nulls={n_null}{n_null2})")
# Ensure symbol columns are string
for d in [df_chan, df_v2]:
if "symbol" in d.columns:
d["symbol"] = d["symbol"].astype(str)
# Determine which V2 columns to keep
# We keep: V2_QUANT_FEATURE_COLS + V5 features
# plus any label/price columns needed later
v2_keep_cols = list(
set(
ID_COLS
+ V2_QUANT_FEATURE_COLS
+ V5_FEATURE_COLS
+ ["ret_5d"] # ensure we have at least one ret col as fallback label
)
)
# Also check what label columns exist
existing_label_cols = [
c
for c in df_v2.columns
if "forward" in c.lower()
or "label" in c.lower()
or "ret_" in c.lower()
or "return" in c.lower()
]
# Keep any label columns found
for c in existing_label_cols:
if c not in v2_keep_cols:
v2_keep_cols.append(c)
# Also keep price columns for forward return computation
price_candidates = [
c for c in df_v2.columns if "close" in c.lower() or "price" in c.lower()
]
for c in price_candidates:
if c not in v2_keep_cols:
v2_keep_cols.append(c)
# When priors are enabled, also keep raw OHLCV columns for factor computation
if args.use_priors:
ohlcv_raw = ["open", "high", "low", "volume"]
for c in ohlcv_raw:
if c in df_v2.columns and c not in v2_keep_cols:
v2_keep_cols.append(c)
# Filter to columns that actually exist
v2_keep_cols = [c for c in v2_keep_cols if c in df_v2.columns]
df_v2_sub = df_v2[v2_keep_cols].copy()
df = pd.merge(df_chan, df_v2_sub, on=["date", "symbol"], how="inner")
print(f" Merged shape: {df.shape[0]:,} rows x {df.shape[1]} cols")
# ── Fix BUG 1: reconcile _x/_y suffix from overlapping columns ──
# Both engine and V2 parquets share V5 features; merge renames them.
# Keep engine version (_x from left=df_chan), drop V2 version (_y).
x_cols = [c for c in df.columns if c.endswith("_x")]
y_cols = [c for c in df.columns if c.endswith("_y")]
if x_cols:
for xc in x_cols:
base = xc[:-2]
df[base] = df[xc]
df = df.drop(columns=x_cols + y_cols)
print(f" Reconciled {len(x_cols)} overlapping columns ({[c[:-2] for c in x_cols]})")
del x_cols, y_cols
# ── Merge validation defense layer 2: sanity-check the output ──
n_dates = df["date"].nunique()
n_syms = df["symbol"].nunique()
print(f" Unique dates: {n_dates}")
print(f" Unique symbols: {n_syms}")
print(f" Date range: {df['date'].min()}{df['date'].max()}")
if n_dates < 200:
print(
" ❌ RED LINE: only {n_dates} unique dates — merge likely silently"
" dropped most rows due to date type mismatch!"
)
sys.exit(1)
# ── Early sample: apply BEFORE Step 3 & 4 so prior computation is fast ──
if args.sample and args.sample < len(df):
df = df.sample(n=args.sample, random_state=42).reset_index(drop=True)
print(f" Early sample (reduced to {len(df):,} rows)")
print()
# -----------------------------------------------------------------------
# Step 3: Add cross-sectional rank features per date
# -----------------------------------------------------------------------
print("[3/7] Adding cross-sectional rank features...")
# rank_bi_strength
if "bi_strength" in df.columns:
df["rank_bi_strength"] = df.groupby("date")["bi_strength"].transform(
rank_percentile
)
else:
print(" WARNING: bi_strength not found, rank_bi_strength set to NaN")
df["rank_bi_strength"] = np.nan
# rank_zhongshu
if "zhongshu_amplitude" in df.columns:
df["rank_zhongshu"] = df.groupby("date")["zhongshu_amplitude"].transform(
rank_percentile
)
else:
print(" WARNING: zhongshu_amplitude not found, rank_zhongshu set to NaN")
df["rank_zhongshu"] = np.nan
# rank_momentum
rank_momentum_col = None
for c in ["ret_10d", "ret_5d", "ret_3d"]:
if c in df.columns:
rank_momentum_col = c
break
if rank_momentum_col:
df["rank_momentum"] = df.groupby("date")[rank_momentum_col].transform(
rank_percentile
)
else:
print(" WARNING: no return column found, rank_momentum set to NaN")
df["rank_momentum"] = np.nan
# rank_volume
rank_vol_col = None
for c in ["vol_ma5", "vol_ma10"]:
if c in df.columns:
rank_vol_col = c
break
if rank_vol_col:
df["rank_volume"] = df.groupby("date")[rank_vol_col].transform(
rank_percentile
)
else:
print(" WARNING: no volume column found, rank_volume set to NaN")
df["rank_volume"] = np.nan
print(" Rank features added:", RANK_FEATURE_COLS)
print()
# -----------------------------------------------------------------------
# Step 4: Compute PRISM-VQ prior factors
# -----------------------------------------------------------------------
print("[4/7] Computing PRISM-VQ prior factors...")
if args.use_priors:
from factor_priors import load_cached_ohlcv
ohlcv_cols = [c for c in ["open", "high", "low", "close", "volume"] if c in df.columns]
has_ohlcv = all(c in df.columns for c in ["open", "high", "low", "close", "volume"])
# 初始化先验因子列为 NaN
for col in PRIOR_COLUMNS:
df[col] = np.nan
symbols = df["symbol"].unique()
n_stock = len(symbols)
print(f" 加载 {n_stock:,} 只股票的 OHLCV(优先从缓存,否则 yfinance 下载)...")
t_start = datetime.now()
total_rows_processed = 0
cache_hits = 0
cache_misses = 0
for s_idx, symbol in enumerate(symbols):
if (s_idx + 1) % 100 == 0:
elapsed = (datetime.now() - t_start).total_seconds()
print(f" [{s_idx+1}/{n_stock}] symbols ({total_rows_processed:,} rows, "
f"cache_hits={cache_hits}, cache_misses={cache_misses}, {elapsed:.0f}s)")
# 尝试从缓存加载 OHLCV
ohlcv = load_cached_ohlcv(symbol)
if ohlcv is not None:
cache_hits += 1
elif not has_ohlcv:
# 缓存未命中,从 yfinance 下载
cache_misses += 1
yf_sym = symbol if (symbol.endswith(".SS") or symbol.endswith(".SZ")) else symbol
try:
import yfinance as yf
ticker = yf.Ticker(yf_sym)
ohlcv_raw = ticker.history(period="5y")
if ohlcv_raw.empty:
continue
ohlcv_raw = ohlcv_raw.reset_index()
ohlcv_raw["date"] = pd.to_datetime(ohlcv_raw["Date"]).dt.tz_localize(None)
ohlcv = ohlcv_raw.rename(columns={
"Open": "open", "High": "high", "Low": "low",
"Close": "close", "Volume": "volume"
})[["date", "open", "high", "low", "close", "volume"]]
except Exception:
continue
else:
# 数据中有 OHLCV,直接使用
mask = df["symbol"] == symbol
sym_data = df.loc[mask].sort_values("date")
ohlcv = sym_data[ohlcv_cols + ["date"]].copy()
if ohlcv is None or len(ohlcv) < 2:
continue
# 获取该股票的所有行并计算先验因子
mask = df["symbol"] == symbol
sym_indices = df.index[mask]
sym_data = df.loc[sym_indices].sort_values("date")
for orig_idx, row in zip(sym_data.index, sym_data.itertuples()):
target_date = row.date
try:
# use_cache=True 表示优先从缓存读取 info/financial 数据
priors = compute_all_priors(ohlcv, symbol, target_date, use_cache=True)
for k, v in priors.items():
if v is not None and np.isfinite(v):
df.at[orig_idx, k] = v
except Exception:
pass
total_rows_processed += 1
elapsed = (datetime.now() - t_start).total_seconds()
print(f" 处理完成: {total_rows_processed:,} 行, "
f"cache_hits={cache_hits}, cache_misses={cache_misses}, 耗时 {elapsed:.0f}s")
# 统计各列非空率
for col in PRIOR_COLUMNS:
non_null = df[col].notna().sum()
total = len(df)
pct = 100.0 * non_null / total if total > 0 else 0
print(f" {col}: {non_null:,}/{total:,} non-null ({pct:.1f}%)")
print(f" 先验因子列数: {len(PRIOR_COLUMNS)}")
else:
print(" --use-priors=False: 跳过先验因子计算")
for col in PRIOR_COLUMNS:
df[col] = np.nan
print(f" Prior columns initialized as NaN: {len(PRIOR_COLUMNS)}")
print()
# -----------------------------------------------------------------------
# Step 5: Create ranking label (forward_20d_ret decile 1-10)
# -----------------------------------------------------------------------
print("[5/7] Creating ranking label...")
# Check if a pre-computed forward return column exists
# NOTE: 'label' is binary 0/1, NOT a forward return — skip it
label_source = None
for candidate in ["forward_20d_ret", "ret_20d", "ret_60d", "ret_30d"]:
if candidate in df.columns:
label_source = candidate
break
if label_source:
print(f" Using existing column '{label_source}' as label source")
df["forward_20d_ret"] = df[label_source]
# Drop rows where forward return is NaN — the qcut/rank can't handle them
n_nan = df["forward_20d_ret"].isna().sum()
if n_nan > 0:
print(f" Dropping {n_nan} rows with NaN forward return ({100*n_nan/len(df):.1f}%)")
df = df.dropna(subset=["forward_20d_ret"]).reset_index(drop=True)
else:
print(" Computing forward_20d_ret from price data...")
try:
df = compute_forward_return(df, period=20)
except KeyError as e:
print(f" WARNING: {e}")
print(" Trying to compute from ret_5d scaled extrapolation...")
# Fallback: use ret_5d * 4 as a rough proxy (only if no better option)
if "ret_5d" in df.columns:
df["forward_20d_ret"] = df["ret_5d"] * 4
else:
print(" ERROR: Cannot compute forward return. Setting to NaN.")
df["forward_20d_ret"] = np.nan
# Decile rank within each date (1 = lowest forward return, 10 = highest)
df[LABEL_COL] = (
df.groupby("date")["forward_20d_ret"]
.transform(lambda x: pd.qcut(x, 10, labels=False, duplicates="drop") + 1)
)
# If qcut fails due to ties, use rank-based alternative
if df[LABEL_COL].isna().any():
print(" qcut had issues (ties too many), using rank-based deciles instead")
df[LABEL_COL] = (
df.groupby("date")["forward_20d_ret"]
.transform(
lambda x: np.ceil(x.rank(method="first") / max(len(x) / 10, 1)).astype(
int
)
)
)
df[LABEL_COL] = df[LABEL_COL].clip(1, 10)
label_dist = df[LABEL_COL].value_counts().sort_index()
print(f" Label distribution (forward return decile, 1=lowest, 10=highest):")
for k in range(1, 11):
count = label_dist.get(k, 0)
print(f" Decile {k:2d}: {count:>8,}")
print()
# -----------------------------------------------------------------------
# Step 6: Add query_group column
# -----------------------------------------------------------------------
print("[6/7] Adding query_group column and cleaning...")
# Sort dates and assign sequential group ID
unique_dates = sorted(df["date"].unique())
date_to_group = {d: i for i, d in enumerate(unique_dates)}
df["query_group"] = df["date"].map(date_to_group).astype(int)
print(f" Unique dates: {len(unique_dates)}")
print(f" Query groups: {df['query_group'].nunique()}")
# -----------------------------------------------------------------------
# Step 7: Clean and filter
# -----------------------------------------------------------------------
print("[7/7] Filtering complete cases and saving...")
# Determine all feature columns (including priors if enabled)
all_expected_features = list(
CHAN_FEATURE_COLS + V5_FEATURE_COLS + V2_QUANT_FEATURE_COLS + RANK_FEATURE_COLS
)
if args.use_priors:
all_expected_features.extend(PRIOR_COLUMNS)
# Ensure all feature columns exist; fill missing with NaN so they get dropped
for col in all_expected_features:
if col not in df.columns:
print(f" WARNING: column '{col}' not found in merged data, filling with NaN")
df[col] = np.nan
# Build output column list dynamically (including priors if enabled)
output_cols = ID_COLS + ["query_group"] + all_expected_features + [LABEL_COL]
# Subset to output columns
available_out = [c for c in output_cols if c in df.columns]
missing_out = [c for c in output_cols if c not in df.columns]
if missing_out:
print(f" WARNING: output columns not available: {missing_out}")
df_out = df[available_out].copy()
# Track NaNs before dropping
nan_before = df_out[all_expected_features].isna().sum().sum()
rows_before = len(df_out)
# Print NaN rates per column
nan_rates = df_out[all_expected_features].isna().mean()
high_nan = nan_rates[nan_rates > 0].sort_values(ascending=False)
if len(high_nan) > 0:
print(f" NaN rates per column (>0%):")
for col, rate in high_nan.items():
print(f" {col}: {rate*100:.1f}%")
# Drop columns with >50% NaN first
cols_to_drop = list(nan_rates[nan_rates > 0.5].index)
if cols_to_drop:
print(f" Dropping {len(cols_to_drop)} columns with >50% NaN: {cols_to_drop}")
df_out = df_out.drop(columns=cols_to_drop)
# Update feature cols reference (not modifying list, just for dropna)
drop_cols_internal = [c for c in all_expected_features if c not in cols_to_drop]
else:
drop_cols_internal = all_expected_features
# Keep only rows with NO NaN in remaining feature columns
df_out = df_out.dropna(subset=drop_cols_internal).reset_index(drop=True)
rows_after = len(df_out)
actual_feature_cols_in_out = [c for c in all_expected_features if c in df_out.columns]
nan_after = df_out[actual_feature_cols_in_out].isna().sum().sum()
dropped = rows_before - rows_after
print(f" Rows before dropna: {rows_before:,}")
print(f" Rows after dropna: {rows_after:,}")
print(f" Dropped: {dropped:,} ({100*dropped/max(rows_before,1):.1f}%)")
print(f" NaN values remaining in features: {nan_after}")
# Optionally sample for testing
if args.sample and args.sample < len(df_out):
df_out = df_out.sample(n=args.sample, random_state=42).reset_index(drop=True)
print(f" Sampled to {len(df_out):,} rows for testing")
# Save to local
os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True)
df_out.to_parquet(args.output, index=False)
print(f" Saved to {args.output}")
# Also upload to HF dataset if not in sample mode
if not args.sample:
try:
from huggingface_hub import HfApi
_hf_token = os.environ.get("HF_TOKEN")
api = HfApi(token=_hf_token)
api.upload_file(
path_or_fileobj=args.output,
path_in_repo="ranking_train_data_v1.parquet",
repo_id="cedwyh/jinjing-shared-data",
repo_type="dataset",
)
print(f" Uploaded to HF dataset: cedwyh/jinjing-shared-data/ranking_train_data_v1.parquet")
except Exception:
print(" WARNING: Failed to upload to HF dataset (token not exposed in logs)")
# NOTE: token deliberately omitted from log message to avoid leaking
# in CI/build logs if HfApi raises an exception.
# -----------------------------------------------------------------------
# Summary stats
# -----------------------------------------------------------------------
print()
print("=" * 60)
print("SUMMARY STATS")
print("=" * 60)
print(f" Rows: {len(df_out):,}")
print(f" Columns: {len(df_out.columns)}")
print(f" Feature columns: {len(all_expected_features)}")
print(f" Unique dates: {df_out['date'].nunique()}")
print(f" Unique symbols: {df_out['symbol'].nunique()}")
print(
f" Date range: {df_out['date'].min()} to {df_out['date'].max()}"
)
print(f" Query groups: {df_out['query_group'].nunique()}")
if len(df_out) > 0:
print(f" Label range: {int(df_out[LABEL_COL].min())} - {int(df_out[LABEL_COL].max())}")
print(f" Label mean (stdev): {df_out[LABEL_COL].mean():.4f} (+/- {df_out[LABEL_COL].std():.4f})")
else:
print(f" Label range: N/A (no data)")
print()
# Per-column NaN count (use columns that actually exist in the output)
existing_feature_cols = [c for c in all_expected_features if c in df_out.columns]
nan_counts = df_out[existing_feature_cols].isna().sum()
nans_present = nan_counts[nan_counts > 0]
if len(nans_present) > 0:
print(" NaN counts per feature column:")
for col, cnt in nans_present.items():
print(f" {col}: {cnt}")
else:
print(" All feature columns have zero NaN values.")
print()
print("Done.")
print("=" * 60)
if __name__ == "__main__":
main()