#!/usr/bin/env python3 """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") # ── env ── DS = "cedwyh/jinjing-shared-data" hf_token = os.environ.get("HF_TOKEN") from huggingface_hub import HfApi, hf_hub_download api = HfApi() # ── chan engine setup ── # Download and extract chan engine tarball 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") # Extract into engine_chan_v3/ subdirectory os.makedirs(ENGINE_DIR, exist_ok=True) with tarfile.open(p) as f: # The tarball has no subdirectory prefix, extract into engine_chan_v3/ for member in f.getmembers(): member.name = f"engine_chan_v3/{member.name}" f.extract(member, path="/tmp") # Verify 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") # engine_chan_v3/ is at /tmp/engine_chan_v3/ 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 # ── constants ── 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", ] # 30F 特征 = 仅 chan engine 特征(量化特征用日线 all_features_v2.parquet) ALL_30F_FEATURES = CHAN_FEATURE_COLS + V5_FEATURE_COLS # ── helpers ── 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) # Initialize placeholder columns 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) # Prepare DataFrame with column names expected by chan engine chan_input = sym_df.rename(columns={ "datetime": "date", "open": "open", "high": "high", "low": "low", "close": "close", "volume": "volume", }) # Ensure date is datetime chan_input["date"] = pd.to_datetime(chan_input["date"]) # NOTE: engine already initialized with ChanConfig.for_frequency("30min") in main() # Do NOT reassign engine.config here — ChanConfig is a dataclass without .get(), # and engine internally uses config.get() which will fail silently. # See verify_30f_v8.py:30F-features-all-zero root cause result_dict = engine.analyze(chan_input) if not result_dict.get("success") or result_dict.get("result") is None: return result = result_dict["result"] # V5 continuous features 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) # Buy/sell points 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 # dist_last_buy 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() # ── Step 1: Load 30F OHLCV ── 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}...") # Read in chunks to avoid OOM import pyarrow.parquet as pq pf = pq.ParquetFile(ohlcv_path) n_rows = pf.metadata.num_rows print(f" Total rows: {n_rows:,}") # Group by symbol in the script symbols_df = pd.read_parquet(ohlcv_path, columns=["symbol"]) all_symbols = sorted(symbols_df["symbol"].unique()) print(f" Unique symbols: {len(all_symbols)}") # ── Step 2: Init chan engine ── print("[2/6] Initializing ChanEngineV3 (A0=30min)...") engine = ChanEngineV3(config=ChanConfig.for_frequency("30min")) # ── Step 3: Process each symbol ── print("[3/6] Computing 30F features per symbol...") snapshots = [] t_start = time.time() n_processed = 0 n_errors = 0 # Collect daily close prices for label computation 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: # Read this symbol's data 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: # need at least 20 trading days n_errors += 1 continue # Compute 30F features feat = compute_30f_features(sym_data) # Run chan engine run_chan_engine_30f(sym_data, feat, engine, symbol) # Take last bar per day as daily snapshot feat["date"] = pd.to_datetime(feat["datetime"]).dt.date.astype(str) daily_last = feat.groupby("date").last().reset_index() # Extract daily close price for forward return computation 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 only needed columns 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) # ── Step 4: Combine snapshots ── 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()}") # ── Step 5: Merge with daily quant features ── 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) # Normalize dates 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) # Select V2 quant columns (non-chan features) 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] # Also keep price columns for forward return 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() # Merge: 30F features (left) + V2 quant (right) 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") # Merge daily close prices (from 30F data) 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:,})") # Report close NaN rate close_nan = df["close"].isna().sum() if close_nan > 0: print(f" ⚠️ {close_nan} rows missing close price ({100*close_nan/len(df):.1f}%)") # ── Step 6: Rank features + Label ── print("[6/6] Creating rank features and label...") # Cross-sectional rank features 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_momentum: use daily ret_20d (available after merge with V2) 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_volume 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"] # Labels: forward Nd return deciles for multiple horizons # Use daily close price (merged from 30F data) HORIZONS = [5, 10, 20] if "close" in df.columns: df = df.sort_values(["symbol", "date"]).reset_index(drop=True) # Compute forward returns for all horizons simultaneously for N in HORIZONS: df[f"forward_{N}d_ret"] = df.groupby("symbol")["close"].transform( lambda x: x.shift(-N) / x - 1 ) # Drop rows where the LONGEST horizon has NaN (most conservative) 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)") # Generate decile labels for each horizon 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) ) # Fill any NaN labels (from dates with too few stocks) 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 # Use 20d as default label_rank (for train_ranker backward compat) df["label_rank"] = df["label_rank_20d"] # Query group 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) # Feature cols 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)}") # Label distribution print(f" Label range: {int(df['label_rank'].min())} - {int(df['label_rank'].max())}") print(f" Label mean: {df['label_rank'].mean():.4f}") # ── Save ── 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() # Drop NaN in features 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):,})") # Save out_path = "/tmp/ranking_train_30f.parquet" df_out.to_parquet(out_path, index=False) print(f" Saved to {out_path}") # Upload 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}") # Summary 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()