| |
| """build_data_30f.py — 30F特征 -> 每日快照训练数据 |
| |
| A0=30F:缠引擎在30F上跑,每日取最后一条30F快照作为当日特征。 |
| 与 daily quant features (all_features_v2.parquet) 合并后训练 Ranker。 |
| |
| 流程: |
| 1. 加载 30F OHLCV (from HF dataset) |
| 2. 每只股票:30F量化特征 + ChanEngine(30min) + V5 continuous features |
| 3. 每日取最后一条30F快照 |
| 4. 合并 daily quant features |
| 5. 创建标签 (forward_20d_ret decile) |
| 6. 保存 |
| """ |
| import os, sys, gc, warnings, time, json |
| from datetime import datetime |
| from pathlib import Path |
| import numpy as np |
| import pandas as pd |
|
|
| warnings.filterwarnings("ignore") |
|
|
| |
| DS = "cedwyh/jinjing-shared-data" |
| hf_token = os.environ.get("HF_TOKEN") |
| from huggingface_hub import HfApi, hf_hub_download |
| api = HfApi() |
|
|
| |
| |
| TARBALL = "chan_engine_v5.5.1.tar.gz" |
| ENGINE_DIR = "/tmp/chan_engine" |
|
|
| def _ensure_engine(): |
| if os.path.exists(ENGINE_DIR): |
| return |
| import tarfile |
| p = hf_hub_download(repo_id=DS, filename=TARBALL, repo_type="dataset") |
| |
| os.makedirs(ENGINE_DIR, exist_ok=True) |
| with tarfile.open(p) as f: |
| |
| for member in f.getmembers(): |
| member.name = f"engine_chan_v3/{member.name}" |
| f.extract(member, path="/tmp") |
| |
| init_file = os.path.join(ENGINE_DIR, "__init__.py") |
| if not os.path.exists(init_file): |
| Path(init_file).touch() |
| print(f" Chan engine extracted to {ENGINE_DIR}") |
|
|
| _ensure_engine() |
| sys.path.insert(0, "/tmp") |
| import engine_chan_v3 |
| from engine_chan_v3.engine import ChanEngineV3 |
| from engine_chan_v3.features import compute_continuous_features |
| from engine_chan_v3.chan_config import ChanConfig |
| from engine_chan_v3.bspoints import BuySellType as BST |
|
|
| |
| EPOCH = datetime(1970, 1, 1) |
|
|
| CHAN_FEATURE_COLS = [ |
| "buy1", "buy2", "buy3", "sell1", "sell2", "sell3", |
| "bi_strength", "zhongshu_amplitude", "dist_last_buy", "bi_zhongshu_count", |
| ] |
|
|
| 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", |
| ] |
|
|
| |
| ALL_30F_FEATURES = CHAN_FEATURE_COLS + V5_FEATURE_COLS |
|
|
| |
| def rank_percentile(series): |
| ranks = series.rank(method="average", ascending=True) |
| return (ranks - 1) / max(ranks.max() - 1, 1) |
|
|
|
|
| def compute_30f_features(sym_df): |
| """Compute 30F chan engine features for one stock. |
| Only initializes placeholder columns — actual values filled by run_chan_engine_30f().""" |
| n = len(sym_df) |
| feat = pd.DataFrame(index=sym_df.index) |
| feat["symbol"] = sym_df["symbol"].values |
| feat["datetime"] = sym_df["datetime"].values |
| feat["date"] = pd.to_datetime(sym_df["datetime"]).dt.date.astype(str) |
|
|
| |
| for col in CHAN_FEATURE_COLS + V5_FEATURE_COLS: |
| feat[col] = 0.0 |
|
|
| return feat |
|
|
|
|
| def run_chan_engine_30f(sym_df, feat_df, engine, sym_name): |
| """Run ChanEngineV3 with 30min config, populate V5 and buy/sell features.""" |
| n = len(sym_df) |
|
|
| |
| chan_input = sym_df.rename(columns={ |
| "datetime": "date", |
| "open": "open", |
| "high": "high", |
| "low": "low", |
| "close": "close", |
| "volume": "volume", |
| }) |
| |
| chan_input["date"] = pd.to_datetime(chan_input["date"]) |
|
|
| |
| |
| |
| |
|
|
| result_dict = engine.analyze(chan_input) |
| if not result_dict.get("success") or result_dict.get("result") is None: |
| return |
|
|
| result = result_dict["result"] |
|
|
| |
| cf = compute_continuous_features(result, chan_input) |
| for name in V5_FEATURE_COLS + ["bi_strength", "zhongshu_amplitude", "bi_zhongshu_count"]: |
| arr = cf.get(name) |
| if arr is not None and len(arr) == n: |
| feat_df[name] = arr.astype(np.float64) |
|
|
| |
| buy1 = np.zeros(n, dtype=np.int32) |
| buy2 = np.zeros(n, dtype=np.int32) |
| buy3 = np.zeros(n, dtype=np.int32) |
| sell1 = np.zeros(n, dtype=np.int32) |
| sell2 = np.zeros(n, dtype=np.int32) |
| sell3 = np.zeros(n, dtype=np.int32) |
| last_buy = -1 |
|
|
| for bp in result.bspoints: |
| idx = bp.kline_idx |
| if idx < 0 or idx >= n: |
| continue |
| if bp.bstype == BST.BUY1: buy1[idx] = 1; last_buy = idx |
| elif bp.bstype == BST.BUY2: buy2[idx] = 1; last_buy = idx |
| elif bp.bstype == BST.BUY3: buy3[idx] = 1; last_buy = idx |
| elif bp.bstype == BST.SELL1: sell1[idx] = 1 |
| elif bp.bstype == BST.SELL2: sell2[idx] = 1 |
| elif bp.bstype == BST.SELL3: sell3[idx] = 1 |
|
|
| feat_df["buy1"] = buy1 |
| feat_df["buy2"] = buy2 |
| feat_df["buy3"] = buy3 |
| feat_df["sell1"] = sell1 |
| feat_df["sell2"] = sell2 |
| feat_df["sell3"] = sell3 |
|
|
| |
| distances = np.full(n, 9999, dtype=np.int32) |
| if last_buy >= 0: |
| distances[last_buy] = 0 |
| for i in range(last_buy + 1, n): |
| distances[i] = distances[i-1] + 1 |
| feat_df["dist_last_buy"] = distances |
|
|
|
|
| def main(): |
| t0 = time.time() |
|
|
| print("=" * 60) |
| print("30F Fire Eye V8 — Training Data Builder") |
| print("A0 = 30min (8 bars/day)") |
| print("=" * 60) |
| print() |
|
|
| |
| print("[1/6] Loading 30F OHLCV from HF...") |
| ohlcv_path = hf_hub_download(repo_id=DS, filename="ohlcv_30m.parquet", repo_type="dataset") |
| print(f" Downloading {ohlcv_path}...") |
|
|
| |
| import pyarrow.parquet as pq |
| pf = pq.ParquetFile(ohlcv_path) |
| n_rows = pf.metadata.num_rows |
| print(f" Total rows: {n_rows:,}") |
|
|
| |
| symbols_df = pd.read_parquet(ohlcv_path, columns=["symbol"]) |
| all_symbols = sorted(symbols_df["symbol"].unique()) |
| print(f" Unique symbols: {len(all_symbols)}") |
|
|
| |
| print("[2/6] Initializing ChanEngineV3 (A0=30min)...") |
| engine = ChanEngineV3(config=ChanConfig.for_frequency("30min")) |
|
|
| |
| print("[3/6] Computing 30F features per symbol...") |
| snapshots = [] |
| t_start = time.time() |
| n_processed = 0 |
| n_errors = 0 |
|
|
| |
| daily_closes = [] |
|
|
| for s_idx, symbol in enumerate(all_symbols): |
| if (s_idx + 1) % 100 == 0: |
| elapsed = time.time() - t_start |
| rate = (s_idx + 1) / elapsed |
| eta = (len(all_symbols) - s_idx - 1) / rate if rate > 0 else 0 |
| print(f" [{s_idx+1}/{len(all_symbols)}] {symbol} | {elapsed:.0f}s elapsed, ETA {eta:.0f}s") |
|
|
| try: |
| |
| sym_data = pd.read_parquet( |
| ohlcv_path, |
| filters=[("symbol", "=", symbol)], |
| columns=["symbol", "datetime", "open", "high", "low", "close", "volume"], |
| ) |
| sym_data = sym_data.sort_values("datetime").reset_index(drop=True) |
|
|
| if len(sym_data) < 160: |
| n_errors += 1 |
| continue |
|
|
| |
| feat = compute_30f_features(sym_data) |
|
|
| |
| run_chan_engine_30f(sym_data, feat, engine, symbol) |
|
|
| |
| feat["date"] = pd.to_datetime(feat["datetime"]).dt.date.astype(str) |
| daily_last = feat.groupby("date").last().reset_index() |
|
|
| |
| sym_data["date_str"] = pd.to_datetime(sym_data["datetime"]).dt.date.astype(str) |
| daily_close = sym_data.groupby("date_str").last()[["close"]].reset_index() |
| daily_close.columns = ["date", "close"] |
| daily_close["symbol"] = symbol |
| daily_closes.append(daily_close[["date", "symbol", "close"]]) |
|
|
| |
| keep = ["date", "symbol"] + ALL_30F_FEATURES |
| available = [c for c in keep if c in daily_last.columns] |
| snapshots.append(daily_last[available]) |
|
|
| n_processed += 1 |
|
|
| except Exception as e: |
| n_errors += 1 |
| if n_errors <= 5: |
| print(f" ⚠️ Error processing {symbol}: {e}") |
| continue |
|
|
| print(f" Processed: {n_processed}/{len(all_symbols)}, Errors: {n_errors}") |
| print(f" Time: {time.time() - t_start:.0f}s") |
|
|
| if not snapshots: |
| print(" ❌ No snapshots generated!") |
| sys.exit(1) |
|
|
| |
| print("[4/6] Combining daily snapshots...") |
| df_30f = pd.concat(snapshots, ignore_index=True) |
| df_30f["date"] = pd.to_datetime(df_30f["date"]) |
| print(f" 30F snapshot features: {len(df_30f):,} rows x {len(df_30f.columns)} cols") |
| print(f" Unique dates: {df_30f['date'].nunique()}") |
| print(f" Date range: {df_30f['date'].min().date()} → {df_30f['date'].max().date()}") |
|
|
| |
| print("[5/6] Merging with daily quant features...") |
| v2_path = hf_hub_download(repo_id=DS, filename="all_features_v2.parquet", repo_type="dataset") |
| df_v2 = pd.read_parquet(v2_path) |
|
|
| |
| df_30f["date"] = pd.to_datetime(df_30f["date"], format="mixed").dt.strftime("%Y-%m-%d") |
| df_v2["date"] = pd.to_datetime(df_v2["date"], format="mixed").dt.strftime("%Y-%m-%d") |
| df_v2["symbol"] = df_v2["symbol"].astype(str) |
| df_30f["symbol"] = df_30f["symbol"].astype(str) |
|
|
| |
| v2_quant = [ |
| "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", |
| ] |
| v2_keep = ["date", "symbol"] + [c for c in v2_quant if c in df_v2.columns] |
| |
| for c in ["close", "open", "high", "low", "volume"]: |
| if c in df_v2.columns and c not in v2_keep: |
| v2_keep.append(c) |
|
|
| df_v2_sub = df_v2[v2_keep].copy() |
|
|
| |
| df = pd.merge(df_30f, df_v2_sub, on=["date", "symbol"], how="inner") |
| print(f" Merged with V2: {len(df):,} rows x {len(df.columns)} cols") |
|
|
| |
| if daily_closes: |
| df_close = pd.concat(daily_closes, ignore_index=True) |
| df_close["date"] = pd.to_datetime(df_close["date"], format="mixed").dt.strftime("%Y-%m-%d") |
| df_close["symbol"] = df_close["symbol"].astype(str) |
| pre = len(df) |
| df = pd.merge(df, df_close, on=["date", "symbol"], how="left") |
| print(f" Merged close prices: {len(df):,} rows (from {pre:,})") |
| |
| close_nan = df["close"].isna().sum() |
| if close_nan > 0: |
| print(f" ⚠️ {close_nan} rows missing close price ({100*close_nan/len(df):.1f}%)") |
|
|
| |
| print("[6/6] Creating rank features and label...") |
|
|
| |
| if "bi_strength" in df.columns: |
| df["rank_bi_strength"] = df.groupby("date")["bi_strength"].transform(rank_percentile) |
|
|
| if "zhongshu_amplitude" in df.columns: |
| df["rank_zhongshu"] = df.groupby("date")["zhongshu_amplitude"].transform(rank_percentile) |
|
|
| |
| rank_mom_col = None |
| for c in ["ret_20d", "ret_10d", "ret_5d"]: |
| if c in df.columns: |
| rank_mom_col = c |
| break |
| if rank_mom_col: |
| df["rank_momentum"] = df.groupby("date")[rank_mom_col].transform(rank_percentile) |
|
|
| |
| rank_vol_col = None |
| for c in ["vol_ma5", "vol_ma20"]: |
| 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) |
|
|
| RANK_FEATURE_COLS = ["rank_bi_strength", "rank_zhongshu", "rank_momentum", "rank_volume"] |
|
|
| |
| |
| HORIZONS = [5, 10, 20] |
| if "close" in df.columns: |
| df = df.sort_values(["symbol", "date"]).reset_index(drop=True) |
|
|
| |
| for N in HORIZONS: |
| df[f"forward_{N}d_ret"] = df.groupby("symbol")["close"].transform( |
| lambda x: x.shift(-N) / x - 1 |
| ) |
|
|
| |
| n_before = len(df) |
| df = df.dropna(subset=[f"forward_{HORIZONS[-1]}d_ret"]).reset_index(drop=True) |
| n_dropped = n_before - len(df) |
| print(f" Dropped {n_dropped} rows with NaN forward return (longest horizon={HORIZONS[-1]}d)") |
|
|
| |
| for N in HORIZONS: |
| col = f"forward_{N}d_ret" |
| label_col = f"label_rank_{N}d" |
| df[label_col] = ( |
| df.groupby("date")[col] |
| .transform(lambda x: pd.qcut(x, 10, labels=False, duplicates="drop") + 1) |
| ) |
| |
| if df[label_col].isna().any(): |
| n_filled = df[label_col].isna().sum() |
| df[label_col] = ( |
| df.groupby("date")[col] |
| .transform(lambda x: np.ceil(x.rank(method="first") / max(len(x) / 10, 1)).astype(int).clip(1, 10)) |
| ) |
| print(f" Filled {n_filled} NaN labels for {N}d horizon") |
|
|
| print(f" Label distributions:") |
| for N in HORIZONS: |
| label_col = f"label_rank_{N}d" |
| print(f" --- {N}d horizon ---") |
| for k, v in sorted(df[label_col].value_counts().items()): |
| print(f" Decile {int(k):2d}: {v:>8,}") |
| else: |
| print(" ⚠️ No price column found, cannot compute forward return labels") |
| for N in HORIZONS: |
| df[f"label_rank_{N}d"] = np.nan |
|
|
| |
| df["label_rank"] = df["label_rank_20d"] |
|
|
| |
| 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) |
|
|
| |
| all_features = ALL_30F_FEATURES + [c for c in v2_quant if c in df.columns] + RANK_FEATURE_COLS |
| all_features = [c for c in all_features if c in df.columns] |
| print(f" Total feature columns: {len(all_features)}") |
|
|
| |
| print(f" Label range: {int(df['label_rank'].min())} - {int(df['label_rank'].max())}") |
| print(f" Label mean: {df['label_rank'].mean():.4f}") |
|
|
| |
| output_cols = ["date", "symbol", "query_group", "close"] + all_features + [f"label_rank_{N}d" for N in HORIZONS] + ["label_rank"] |
| output_cols = [c for c in output_cols if c in df.columns] |
|
|
| df_out = df[output_cols].copy() |
|
|
| |
| rows_before = len(df_out) |
| df_out = df_out.dropna(subset=all_features).reset_index(drop=True) |
| print(f" Rows after dropna: {len(df_out):,} (dropped {rows_before - len(df_out):,})") |
|
|
| |
| out_path = "/tmp/ranking_train_30f.parquet" |
| df_out.to_parquet(out_path, index=False) |
| print(f" Saved to {out_path}") |
|
|
| |
| try: |
| api = HfApi() |
| api.upload_file( |
| path_or_fileobj=out_path, |
| path_in_repo="ranking_train_30f_v1.parquet", |
| repo_id=DS, |
| repo_type="dataset", |
| ) |
| print(" ✅ Uploaded to HF dataset") |
| except Exception as e: |
| print(f" ⚠️ Upload failed: {e}") |
|
|
| |
| elapsed = time.time() - t0 |
| print() |
| print("=" * 60) |
| print("SUMMARY") |
| print("=" * 60) |
| print(f" Rows: {len(df_out):,}") |
| print(f" Columns: {len(df_out.columns)}") |
| print(f" Feature columns: {len(all_features)}") |
| print(f" Unique dates: {df_out['date'].nunique()}") |
| print(f" Date range: {df_out['date'].min()} → {df_out['date'].max()}") |
| print(f" Unique symbols: {df_out['symbol'].nunique()}") |
| print(f" NaN in features: {df_out[all_features].isna().sum().sum()}") |
| print(f" Total time: {elapsed:.0f}s ({elapsed/60:.1f}min)") |
| print("Done.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|