jinjing-shared-data / scripts /full_pipeline_v4.py
cedwyh's picture
Upload scripts/full_pipeline_v4.py with huggingface_hub
d737214 verified
Raw
History Blame Contribute Delete
9.32 kB
#!/usr/bin/env python3
"""
Full pipeline: new engine → features → build_data → train_ranker
Self-contained — does NOT exec external scripts. Uses subprocess for each step.
"""
import os, sys, gc, warnings, subprocess, tarfile, time, uuid, shutil
from pathlib import Path
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
DS = "cedwyh/jinjing-shared-data"
ENGINE_TAG = "chan_engine_v5.5.1.tar.gz"
hf_token = os.environ.get("HF_TOKEN")
from huggingface_hub import HfApi, hf_hub_download
api = HfApi()
print("=" * 60)
print(f"Full Pipeline: new engine → features → data → Ranker")
print(f"Engine: {ENGINE_TAG}")
print("=" * 60)
def _download_and_patch(src_name, dest_path, patches=None):
"""Download from HF dataset, apply patches, write to dest_path"""
p = hf_hub_download(repo_id=DS, filename=src_name, repo_type="dataset")
with open(p) as f:
content = f.read()
if patches:
for old, new in patches:
assert old in content, f"Patch target not found in {src_name}"
content = content.replace(old, new)
with open(dest_path, "w") as f:
f.write(content)
return dest_path
# ====================================================================
# Step 0: Prepare new engine
# ====================================================================
print("\n[0/4] Downloading engine...")
tarball_path = hf_hub_download(repo_id=DS, filename=ENGINE_TAG, repo_type="dataset")
engine_dir = "/tmp/engine_v3"
os.makedirs(engine_dir, exist_ok=True)
with tarfile.open(tarball_path) as tf:
# Files are at root of tarball, need engine_chan_v3/ prefix for imports
tf.extractall(path=engine_dir)
# Move all files into engine_chan_v3/ subdirectory
v3_dir = os.path.join(engine_dir, "engine_chan_v3")
os.makedirs(v3_dir, exist_ok=True)
for f in os.listdir(engine_dir):
if f.endswith(".py") and f != "engine_chan_v3":
shutil.move(os.path.join(engine_dir, f), os.path.join(v3_dir, f))
sys.path.insert(0, engine_dir)
# Verify beichi fix
with open(os.path.join(v3_dir, "beichi.py")) as f:
assert "up_relevant" in f.read(), "beichi.py missing fix!"
print(" ✅ Engine ready + imported")
# ====================================================================
# Step 1: Load OHLCV & run engine on all stocks
# ====================================================================
print("\n[1/4] Loading OHLCV data...")
ohlcv_path = hf_hub_download(repo_id=DS, filename="cn_and_us_unified.parquet", repo_type="dataset")
df_ohlcv = pd.read_parquet(ohlcv_path)
print(f" {len(df_ohlcv):,} rows, {df_ohlcv['symbol'].nunique()} symbols")
# Run engine on all stocks
from engine_chan_v3.engine import ChanEngineV3
symbols = sorted(df_ohlcv['symbol'].unique())
total = len(symbols)
print(f"\nRunning engine on {total} stocks...")
FEATURE_COLS = [
'buy1','buy2','buy3','sell1','sell2','sell3',
'bi_strength','zhongshu_amplitude','dist_last_buy','bi_zhongshu_count',
'buy_decay','sell_decay','zs_pos','zs_width','zs_time',
'momentum_div','volume_div','slope','trend_consistency',
'regime_prob','leg_progress','structure_progress',
]
all_chunks = []
count, errors, skipped = 0, 0, 0
start_ts = time.time()
engine = ChanEngineV3()
checkpoint = "/tmp/processed_symbols.txt"
processed = set()
if os.path.exists(checkpoint):
with open(checkpoint) as f:
processed = set(line.strip() for line in f)
print(f" Resuming from checkpoint: {len(processed)} already done")
for sym in symbols:
if sym in processed:
count += 1
continue
try:
sdf = df_ohlcv[df_ohlcv['symbol'] == sym].sort_values('date').reset_index(drop=True)
if len(sdf) < 60:
skipped += 1; continue
result_dict = engine.analyze(sdf)
if not result_dict.get('success'):
skipped += 1; continue
result_obj = result_dict['result'] # SingleLevelResult
feat = result_obj.continuous_features # already computed inside analyze()
# Build rows: feature values for EVERY K-line (not just last one)
n_rows = len(sdf)
sdf_dates = sdf['date'].values
for ki in range(n_rows):
row = {'symbol': sym}
# Store date: match format to all_features_v2 (string YYYY-MM-DD)
raw_d = sdf_dates[ki]
try:
row['date'] = pd.Timestamp(raw_d).strftime('%Y-%m-%d')
except Exception:
row['date'] = str(raw_d)[:10].replace('-', '')[:8]
# insert hyphens: 20100104 -> 2010-01-04
if len(row['date']) == 8 and row['date'].isdigit():
row['date'] = f"{row['date'][:4]}-{row['date'][4:6]}-{row['date'][6:]}"
for col in FEATURE_COLS:
vals = feat.get(col, np.array([0.0]))
row[col] = float(vals[ki]) if ki < len(vals) else 0.0
all_chunks.append(row)
count += 1
if count % 200 == 0:
elapsed = time.time() - start_ts
rate = count / elapsed * 60 if elapsed > 0 else 0
print(f" [{count}/{total}] {rate:.0f} stocks/min, {len(all_chunks)} rows buffered")
with open(checkpoint, "a") as f:
f.write(f"{sym}\n")
except Exception as e:
errors += 1
if errors <= 5:
print(f" ❌ {sym}: {e}")
elapsed = time.time() - start_ts
print(f"\n Done: {count} processed, {skipped} skipped, {errors} errors in {elapsed/60:.1f}m")
# Save features
df_feat = pd.DataFrame(all_chunks) if all_chunks else pd.DataFrame(columns=['date','symbol']+FEATURE_COLS)
df_feat.to_parquet("/tmp/chan_features_v3.parquet", index=False)
print(f"✅ Features: {len(df_feat):,} rows x {len(df_feat.columns)} cols")
del df_feat, df_ohlcv; gc.collect()
api.upload_file(
path_or_fileobj="/tmp/chan_features_v3.parquet",
path_in_repo="chan_engine_features_v5.5.1.parquet",
repo_id=DS, repo_type="dataset"
)
print(" ✅ Uploaded chan_engine_features_v5.5.1.parquet")
# ====================================================================
# Step 2: Build ranking training data
# ====================================================================
print("\n[2/4] Building ranking training data...")
bd_patched = _download_and_patch(
"build_data.py", "/tmp/build_data_patched.py",
[
("from factor_priors import compute_all_priors, PRIOR_COLUMNS",
"try:\n from factor_priors import compute_all_priors, PRIOR_COLUMNS\nexcept ImportError:\n compute_all_priors = None\n PRIOR_COLUMNS = []"),
('"chan_engine_features.parquet"', '"chan_engine_features_v5.5.1.parquet"'),
]
)
bd_result = subprocess.run(
[sys.executable, bd_patched, "--output", "/tmp/ranking_train_v8.parquet",
"--dataset", DS, "--no-use-priors"],
capture_output=True, text=True, timeout=7200
)
print(bd_result.stdout[-500:] if len(bd_result.stdout) > 500 else bd_result.stdout)
if bd_result.returncode != 0:
bd_err = (bd_result.stderr or "")[-500:]
print(f"❌ Build data failed: {bd_err}")
sys.exit(1)
df = pd.read_parquet("/tmp/ranking_train_v8.parquet")
print(f"✅ Build data: {len(df):,} rows x {len(df.columns)} cols, dates {df['date'].min()}..{df['date'].max()}")
n_dates = df["date"].nunique()
if n_dates < 200:
print(f" ❌ RED LINE: only {n_dates} unique dates — merge silently dropped rows!")
sys.exit(1)
del df; gc.collect()
api.upload_file(path_or_fileobj="/tmp/ranking_train_v8.parquet",
path_in_repo="ranking_train_v8.parquet",
repo_id=DS, repo_type="dataset")
print(" ✅ Uploaded ranking_train_v8.parquet")
# ====================================================================
# Step 3: Train LGBMRanker
# ====================================================================
print("\n[3/4] Training LGBMRanker...")
tr_patched = _download_and_patch(
"scripts/train_ranker.py", "/tmp/train_ranker_patched.py",
[('TARGET_COL = "label"', 'TARGET_COL = "label_rank"')]
)
output_dir = "/tmp/v10_ranker"
Path(output_dir).mkdir(exist_ok=True)
tr_result = subprocess.run(
[sys.executable, tr_patched, "--data", "/tmp/ranking_train_v8.parquet",
"--output", output_dir],
capture_output=True, text=True, timeout=14400
)
print(tr_result.stdout[-1000:] if len(tr_result.stdout) > 1000 else tr_result.stdout)
if tr_result.returncode != 0:
tr_err = (tr_result.stderr or "")[-500:]
print(f"❌ Ranker training failed: {tr_err}")
sys.exit(1)
# Upload models
for f in sorted(Path(output_dir).glob("*.txt")):
api.upload_file(path_or_fileobj=str(f), path_in_repo=f"models/v10_{f.name}",
repo_id=DS, repo_type="dataset")
print(f" ✅ models/v10_{f.name}")
pred_file = Path(output_dir) / "ranker_predictions.parquet"
if pred_file.exists():
api.upload_file(path_or_fileobj=str(pred_file),
path_in_repo="models/ranker_v10_predictions.parquet",
repo_id=DS, repo_type="dataset")
print(" ✅ Uploaded predictions")
print("\n" + "=" * 60)
print("✅ FULL PIPELINE COMPLETE")
print(f" Engine: {ENGINE_TAG}")
print(" Features: chan_engine_features_v5.5.1.parquet")
print(" Data: ranking_train_v8.parquet")
print(" Models: models/v10_lgbm_w*.txt")
print("=" * 60)