File size: 26,160 Bytes
26ee395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
#!/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...")

    # Compute forward_20d_ret from CLOSE PRICE (not ret_20d which is backward-looking).
    # ret_20d is a legitimate momentum FEATURE — using it as label causes leakage.
    # Priority: 1) precomputed forward_20d_ret, 2) compute from close price.
    label_source = None
    for candidate in ["forward_20d_ret"]:
        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]
        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 close price...")
        try:
            df = compute_forward_return(df, period=20)
        except KeyError as e:
            print(f"  ERROR: Cannot compute forward return — {e}")
            print("  Need 'close' column in input data. Aborting.")
            sys.exit(1)

    # 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()