Upload scripts
Browse files- scripts/inference.py +165 -0
- scripts/run_hf_jobs.py +250 -0
- scripts/run_hf_sandbox.sh +23 -0
- scripts/run_local_test.py +132 -0
- scripts/validate_with_moneyflow.py +101 -0
scripts/inference.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
加载已训练追踪器,处理新交易日。
|
| 4 |
+
|
| 5 |
+
用法:
|
| 6 |
+
# 处理单个新日
|
| 7 |
+
python scripts/inference.py --date 20260401 --tracker outputs/tracker_state.pkl --output outputs/new_day/
|
| 8 |
+
|
| 9 |
+
# 批量处理
|
| 10 |
+
python scripts/inference.py --date 20260401,20260402,20260403 --tracker outputs/tracker_state.pkl
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
|
| 22 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
| 23 |
+
|
| 24 |
+
from src.data.loader import load_l2_day, BLACKLIST_DATES
|
| 25 |
+
from src.features.passive_orders import (
|
| 26 |
+
compute_vwap,
|
| 27 |
+
extract_passive_orders,
|
| 28 |
+
prepare_features,
|
| 29 |
+
select_candidates,
|
| 30 |
+
)
|
| 31 |
+
from src.clustering.daily_cluster import cluster_candidates
|
| 32 |
+
from src.matching.cross_day_match import match_multi_window
|
| 33 |
+
from src.tracking.entity_tracker import EntityTracker
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def process_new_day(
|
| 37 |
+
tracker: EntityTracker,
|
| 38 |
+
date: int,
|
| 39 |
+
max_cost: float = 3.5,
|
| 40 |
+
) -> dict:
|
| 41 |
+
"""处理一个新交易日,更新追踪器并返回信号。"""
|
| 42 |
+
if date in BLACKLIST_DATES:
|
| 43 |
+
print(f"[{date}] blacklisted, skip")
|
| 44 |
+
return {"date": date, "score": 0.0, "error": "blacklisted"}
|
| 45 |
+
|
| 46 |
+
# 加载数据
|
| 47 |
+
try:
|
| 48 |
+
data = load_l2_day(date)
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"[{date}] load failed: {e}")
|
| 51 |
+
return {"date": date, "score": 0.0, "error": str(e)}
|
| 52 |
+
|
| 53 |
+
trades = data["trades"]
|
| 54 |
+
if "is_cancellation" in trades.columns:
|
| 55 |
+
trades = trades[~trades["is_cancellation"]]
|
| 56 |
+
trades = trades[trades["bs_flag_desc"].isin(["active_buy", "active_sell"])]
|
| 57 |
+
if trades.empty:
|
| 58 |
+
return {"date": date, "score": 0.0, "error": "empty trades"}
|
| 59 |
+
|
| 60 |
+
# 被动单 + 聚类
|
| 61 |
+
vwap = compute_vwap(trades)
|
| 62 |
+
passive = extract_passive_orders(trades, vwap)
|
| 63 |
+
candidates = select_candidates(passive, top_n=150)
|
| 64 |
+
if candidates.empty or len(candidates) < 5:
|
| 65 |
+
return {"date": date, "score": 0.0, "error": "too few candidates"}
|
| 66 |
+
|
| 67 |
+
feats = prepare_features(candidates)
|
| 68 |
+
_, centroids = cluster_candidates(candidates, feats)
|
| 69 |
+
|
| 70 |
+
if not centroids:
|
| 71 |
+
return {"date": date, "score": 0.0, "n_clusters": 0}
|
| 72 |
+
|
| 73 |
+
# 跨日匹配:往前看最近已处理日
|
| 74 |
+
recent = {}
|
| 75 |
+
for prev_date in sorted(tracker._processed_dates)[-2:]:
|
| 76 |
+
# 收集该日的簇信息(通过 cluster_registry 反查)
|
| 77 |
+
day_clusters = {
|
| 78 |
+
cid: tracker.entities[eid]
|
| 79 |
+
for (d, cid), eid in tracker.cluster_registry.items()
|
| 80 |
+
if d == prev_date and eid in tracker.entities
|
| 81 |
+
}
|
| 82 |
+
if day_clusters:
|
| 83 |
+
# 重建 centroid 信息(用最近一次记录的)
|
| 84 |
+
recent[prev_date] = {}
|
| 85 |
+
for cid, e in day_clusters.items():
|
| 86 |
+
if e.get("centroids"):
|
| 87 |
+
recent[prev_date][int(cid)] = {
|
| 88 |
+
"centroid_scaled": e["centroids"][-1][1]
|
| 89 |
+
if isinstance(e["centroids"][-1], tuple)
|
| 90 |
+
else e["centroids"][-1],
|
| 91 |
+
"centroid": e["centroids"][-1][1]
|
| 92 |
+
if isinstance(e["centroids"][-1], tuple)
|
| 93 |
+
else e["centroids"][-1],
|
| 94 |
+
"total_amount": e.get("total_amount_latest", 0),
|
| 95 |
+
"size": e.get("cluster_count", 1),
|
| 96 |
+
"dominant_side": e.get("dominant_sides", ["unknown"])[-1],
|
| 97 |
+
"bid_ratio": e.get("bid_ratio", 0.5),
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
matches = match_multi_window(date, centroids, recent, max_cost=max_cost)
|
| 101 |
+
|
| 102 |
+
# 更新追踪器
|
| 103 |
+
tracker.process_day(date, centroids, matches)
|
| 104 |
+
signal = tracker.compute_position_signal(date)
|
| 105 |
+
signal["date"] = date
|
| 106 |
+
|
| 107 |
+
print(
|
| 108 |
+
f"[{date}] clusters={len(centroids)}, "
|
| 109 |
+
f"matches={len(matches)}, "
|
| 110 |
+
f"entities={len(tracker.entities)}, "
|
| 111 |
+
f"score={signal['score']:.4f}"
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
return signal
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def main():
|
| 118 |
+
parser = argparse.ArgumentParser(description="新日推理")
|
| 119 |
+
parser.add_argument("--date", required=True, help="日期 YYYYMMDD,多个用逗号分隔")
|
| 120 |
+
parser.add_argument("--tracker", default="./outputs/tracker_state.pkl", help="追踪器状态文件")
|
| 121 |
+
parser.add_argument("--output", default="./outputs/new_day", help="输出目录")
|
| 122 |
+
parser.add_argument("--save-state", action="store_true", help="推理后保存更新状态")
|
| 123 |
+
args = parser.parse_args()
|
| 124 |
+
|
| 125 |
+
# 加载追踪器
|
| 126 |
+
print(f"Loading tracker from {args.tracker}")
|
| 127 |
+
tracker = EntityTracker.load_state(args.tracker)
|
| 128 |
+
print(f" Loaded: {len(tracker.entities)} entities, {len(tracker._processed_dates)} processed days")
|
| 129 |
+
print(f" Last processed: {max(tracker._processed_dates) if tracker._processed_dates else 'N/A'}")
|
| 130 |
+
|
| 131 |
+
dates = [int(d.strip()) for d in args.date.split(",")]
|
| 132 |
+
|
| 133 |
+
os.makedirs(args.output, exist_ok=True)
|
| 134 |
+
|
| 135 |
+
signals = []
|
| 136 |
+
for date in sorted(dates):
|
| 137 |
+
sig = process_new_day(tracker, date)
|
| 138 |
+
signals.append(sig)
|
| 139 |
+
|
| 140 |
+
signals_df = pd.DataFrame(signals)
|
| 141 |
+
|
| 142 |
+
# 合并历史信号
|
| 143 |
+
hist_signals = tracker.get_daily_signals()
|
| 144 |
+
all_signals = pd.concat([hist_signals, signals_df], ignore_index=True)
|
| 145 |
+
|
| 146 |
+
sig_path = os.path.join(args.output, "position_signal_daily.parquet")
|
| 147 |
+
all_signals.to_parquet(sig_path)
|
| 148 |
+
print(f"\nSignals saved to {sig_path}")
|
| 149 |
+
|
| 150 |
+
if args.save_state:
|
| 151 |
+
state_path = os.path.join(args.output, "tracker_state_updated.pkl")
|
| 152 |
+
tracker.save_state(state_path)
|
| 153 |
+
|
| 154 |
+
# 最新信号
|
| 155 |
+
print("\n===== 最新信号 =====")
|
| 156 |
+
for sig in signals:
|
| 157 |
+
print(
|
| 158 |
+
f" {sig['date']}: score={sig.get('score', 'N/A')}, "
|
| 159 |
+
f"bid={sig.get('bid_entities', 'N/A')}, "
|
| 160 |
+
f"ask={sig.get('ask_entities', 'N/A')}"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
if __name__ == "__main__":
|
| 165 |
+
main()
|
scripts/run_hf_jobs.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
HF Jobs 全量运行脚本:流水线 + 结果上传到 HF Dataset。
|
| 4 |
+
|
| 5 |
+
在 HF Jobs 中运行:
|
| 6 |
+
hf jobs run --flavor cpu-large --timeout 12h --detach --secrets HF_TOKEN \\
|
| 7 |
+
--env DATASET_REPO=kangkangchen/cross-day-mainforce-600809 \\
|
| 8 |
+
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime -- \\
|
| 9 |
+
/bin/sh -lc '
|
| 10 |
+
pip install pandas pyarrow numpy scipy scikit-learn huggingface_hub tqdm
|
| 11 |
+
python scripts/run_hf_jobs.py
|
| 12 |
+
'
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
from datetime import datetime
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
| 24 |
+
|
| 25 |
+
from huggingface_hub import HfApi, create_repo, upload_folder
|
| 26 |
+
|
| 27 |
+
from src.scripts.pipeline import run_pipeline
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def generate_dates(start: int, end: int):
|
| 31 |
+
"""生成交易日期列表(周一-周五,排除黑名单)。"""
|
| 32 |
+
from datetime import timedelta
|
| 33 |
+
from src.data.loader import BLACKLIST_DATES
|
| 34 |
+
|
| 35 |
+
start_dt = datetime.strptime(str(start), "%Y%m%d")
|
| 36 |
+
end_dt = datetime.strptime(str(end), "%Y%m%d")
|
| 37 |
+
dates = []
|
| 38 |
+
curr = start_dt
|
| 39 |
+
while curr <= end_dt:
|
| 40 |
+
d = int(curr.strftime("%Y%m%d"))
|
| 41 |
+
if d not in BLACKLIST_DATES and curr.weekday() < 5:
|
| 42 |
+
dates.append(d)
|
| 43 |
+
curr += timedelta(days=1)
|
| 44 |
+
return dates
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main():
|
| 48 |
+
output_base = os.environ.get("OUTPUT_DIR", "./outputs")
|
| 49 |
+
dataset_repo = os.environ.get("DATASET_REPO", "kangkangchen/cross-day-mainforce-600809")
|
| 50 |
+
start_date = int(os.environ.get("START_DATE", "20230101"))
|
| 51 |
+
end_date = int(os.environ.get("END_DATE", "20260331"))
|
| 52 |
+
|
| 53 |
+
print(f"===== Cross-Day Main Force Pipeline =====")
|
| 54 |
+
print(f"Range: {start_date} ~ {end_date}")
|
| 55 |
+
print(f"Output: {output_base}")
|
| 56 |
+
print(f"Target dataset: {dataset_repo}")
|
| 57 |
+
print(f"Start: {datetime.now().isoformat()}")
|
| 58 |
+
|
| 59 |
+
# 1. 确保数据集 repo 存在
|
| 60 |
+
api = HfApi()
|
| 61 |
+
try:
|
| 62 |
+
create_repo(dataset_repo, repo_type="dataset", exist_ok=True)
|
| 63 |
+
print(f"Dataset repo {dataset_repo} ready")
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"Create repo warning: {e}")
|
| 66 |
+
|
| 67 |
+
# 2. 生成日期 & 运行流水线
|
| 68 |
+
dates = generate_dates(start_date, end_date)
|
| 69 |
+
print(f"Total trading days: {len(dates)}")
|
| 70 |
+
|
| 71 |
+
run_pipeline(dates, output_base, save_intermediate=False)
|
| 72 |
+
|
| 73 |
+
# 3. 复制源码到输出目录(方便 dataset 自包含)
|
| 74 |
+
import shutil
|
| 75 |
+
src_dest = os.path.join(output_base, "src")
|
| 76 |
+
if os.path.exists(src_dest):
|
| 77 |
+
shutil.rmtree(src_dest)
|
| 78 |
+
shutil.copytree("src", src_dest)
|
| 79 |
+
shutil.copy("DESIGN.md", os.path.join(output_base, "DESIGN.md"))
|
| 80 |
+
shutil.copy("README.md", os.path.join(output_base, "README.md"))
|
| 81 |
+
|
| 82 |
+
# 4. 写到 dataset README
|
| 83 |
+
write_dataset_readme(output_base)
|
| 84 |
+
|
| 85 |
+
# 5. 上传到 HF Dataset
|
| 86 |
+
print(f"\nUploading to {dataset_repo} ...")
|
| 87 |
+
upload_folder(
|
| 88 |
+
repo_id=dataset_repo,
|
| 89 |
+
folder_path=output_base,
|
| 90 |
+
repo_type="dataset",
|
| 91 |
+
commit_message=f"Full run {start_date}-{end_date} @ {datetime.now().isoformat()}",
|
| 92 |
+
)
|
| 93 |
+
print(f"Upload complete: https://huggingface.co/datasets/{dataset_repo}")
|
| 94 |
+
|
| 95 |
+
print(f"\nDone: {datetime.now().isoformat()}")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def write_dataset_readme(output_base: str):
|
| 99 |
+
"""生成 dataset 的 README(包含模型使用说明)。"""
|
| 100 |
+
readme = """---
|
| 101 |
+
license: mit
|
| 102 |
+
task_categories:
|
| 103 |
+
- time-series-forecasting
|
| 104 |
+
tags:
|
| 105 |
+
- finance
|
| 106 |
+
- a-share
|
| 107 |
+
- level-2
|
| 108 |
+
- main-force
|
| 109 |
+
- position-tracking
|
| 110 |
+
pretty_name: Cross-Day Main Force Position Inference for 600809.SH
|
| 111 |
+
---
|
| 112 |
+
|
| 113 |
+
# Cross-Day Main Force Position Inference for 600809.SH
|
| 114 |
+
|
| 115 |
+
跨日主力行为指纹追踪——不追踪"谁",追踪"某种行为模式在增强还是衰减"。
|
| 116 |
+
|
| 117 |
+
## 数据
|
| 118 |
+
|
| 119 |
+
- 股票: `600809.SH` (山西汾酒)
|
| 120 |
+
- 覆盖区间: 2023-01-01 ~ 2026-03-31
|
| 121 |
+
- 数据源: [a-share-l2-600809](https://huggingface.co/datasets/kangkangchen/a-share-l2-600809)
|
| 122 |
+
|
| 123 |
+
## 核心方法
|
| 124 |
+
|
| 125 |
+
上交所 L2 order_id 每日重置,无法跨日追踪同一账户。本方案利用**行为指纹**跨日匹配:
|
| 126 |
+
|
| 127 |
+
1. **被动单提取**: 利用 `active_buy → ask_order_id`, `active_sell → bid_order_id` 语义,每日提取 top 150 被动挂单的行为特征
|
| 128 |
+
2. **日级聚类**: OPTICS 密度聚类,发现"主力行为模式"
|
| 129 |
+
3. **跨日匹配**: 匈牙利算法 + T→T+1/T+2 多窗口匹配
|
| 130 |
+
4. **实体追踪**: 匹配对连成实体链,追踪金额/方向趋势
|
| 131 |
+
5. **仓位推断**: 聚合活跃实体,计算日级主力仓位方向
|
| 132 |
+
|
| 133 |
+
详细设计见 [DESIGN.md](./DESIGN.md)。
|
| 134 |
+
|
| 135 |
+
## 输出文件
|
| 136 |
+
|
| 137 |
+
| 文件 | 内容 |
|
| 138 |
+
|---|---|
|
| 139 |
+
| `entity_timeline.parquet` | 每个实体的完整生命周期(first_seen, last_seen, dominant_side, amount_growth 等)|
|
| 140 |
+
| `cluster_registry.parquet` | 每日每个簇到实体的映射 |
|
| 141 |
+
| `signals/position_signal_daily.parquet` | **日级仓位推断信号**(核心输出) |
|
| 142 |
+
| `matches/match_pairs.parquet` | 跨日匹配记录 |
|
| 143 |
+
| `tracker_state.pkl` | 完整追踪器状态(可加载继续处理新日) |
|
| 144 |
+
| `reports/summary.json` | 汇总���计 |
|
| 145 |
+
|
| 146 |
+
## 信号字段说明
|
| 147 |
+
|
| 148 |
+
`position_signal_daily.parquet` 核心字段:
|
| 149 |
+
|
| 150 |
+
| 字段 | 含义 |
|
| 151 |
+
|---|---|
|
| 152 |
+
| `date` | 交易日 YYYYMMDD |
|
| 153 |
+
| `score` | 仓位方向原始分(正值=吸筹倾向,负值=出货倾向) |
|
| 154 |
+
| `score_z` | 滚动 20 日 z-score 归一化后的分值 |
|
| 155 |
+
| `bid_entities` | 当日活跃的买方实体数 |
|
| 156 |
+
| `ask_entities` | 当日活跃的卖方实体数 |
|
| 157 |
+
| `n_active_entities` | 当日活跃实体总数 |
|
| 158 |
+
| `n_total_entities` | 历史累计发现的实体总数 |
|
| 159 |
+
| `accumulation_entities` | 正在扩张的买方实体 ID 列表 |
|
| 160 |
+
| `distribution_entities` | 正在扩张的卖方实体 ID 列表 |
|
| 161 |
+
|
| 162 |
+
**重要**: 所有分数和概率都应读成"证据强度",不是交易信号,不是买卖建议。
|
| 163 |
+
|
| 164 |
+
## 如何使用(加载模型处理新日)
|
| 165 |
+
|
| 166 |
+
### 1. 加载已训练的追踪器
|
| 167 |
+
|
| 168 |
+
```python
|
| 169 |
+
import sys
|
| 170 |
+
sys.path.insert(0, 'src/')
|
| 171 |
+
from src.tracking.entity_tracker import EntityTracker
|
| 172 |
+
|
| 173 |
+
# 加载追踪器状态
|
| 174 |
+
tracker = EntityTracker.load_state("tracker_state.pkl")
|
| 175 |
+
print(f"Loaded: {len(tracker.entities)} entities")
|
| 176 |
+
print(f"Last date: {max(tracker._processed_dates)}")
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
### 2. 处理新交易日
|
| 180 |
+
|
| 181 |
+
```python
|
| 182 |
+
import sys
|
| 183 |
+
sys.path.insert(0, 'src/')
|
| 184 |
+
from scripts.inference import process_new_day
|
| 185 |
+
|
| 186 |
+
# 处理单个新日
|
| 187 |
+
signal = process_new_day(tracker, 20260401)
|
| 188 |
+
print(f"Score: {signal['score']:.4f}, bid={signal['bid_entities']}, ask={signal['ask_entities']}")
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
### 3. 批量推理
|
| 192 |
+
|
| 193 |
+
```bash
|
| 194 |
+
python scripts/inference.py \
|
| 195 |
+
--date 20260401,20260402,20260403 \
|
| 196 |
+
--tracker outputs/tracker_state.pkl \
|
| 197 |
+
--save-state
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
### 4. 查看实体详情
|
| 201 |
+
|
| 202 |
+
```python
|
| 203 |
+
import pandas as pd
|
| 204 |
+
entities = pd.read_parquet("entity_timeline.parquet")
|
| 205 |
+
|
| 206 |
+
# 最活跃的买方实体
|
| 207 |
+
entities[entities['dominant_side'] == 'bid'].nlargest(10, 'active_days')
|
| 208 |
+
|
| 209 |
+
# 按金额增长排
|
| 210 |
+
entities.nlargest(10, 'amount_growth')
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
## 信号解读指南
|
| 214 |
+
|
| 215 |
+
1. **score_z > 1.5**: 当日买方实体扩张显著强于卖方,可能有吸筹行为
|
| 216 |
+
2. **score_z < -1.5**: 卖方实体扩张显著强于买方,可能有出货行为
|
| 217 |
+
3. **bid_entities 持续 > ask_entities + 3**: 多日买方实体占优,可能处于吸筹阶段
|
| 218 |
+
4. **实体集中新生/退出**: 旧实体批量退出 + 新实体批量出现 = 主力换防事件
|
| 219 |
+
|
| 220 |
+
⚠️ 信号需要结合盘口复盘(价格、成交量、OBI 变化)验证,不可单独使用。
|
| 221 |
+
|
| 222 |
+
## 校验
|
| 223 |
+
|
| 224 |
+
与 Tushare `moneyflow_dc_daily` 主力净流入对比,确认推断方向不严重矛盾:
|
| 225 |
+
|
| 226 |
+
```bash
|
| 227 |
+
python scripts/validate_with_moneyflow.py \
|
| 228 |
+
--signal outputs/signals/position_signal_daily.parquet
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
## 限制
|
| 232 |
+
|
| 233 |
+
- 仅 600809.SH 单只股票
|
| 234 |
+
- 不预测涨跌,只输出行为仓位方向
|
| 235 |
+
- 每日仅 150 个候选被动单,可能遗漏小主力
|
| 236 |
+
- 主力换防事件的识别依赖匹配阈值调优
|
| 237 |
+
- 需要至少 10 个交易日的历史才能产生有意义信号
|
| 238 |
+
|
| 239 |
+
## 研究声明
|
| 240 |
+
|
| 241 |
+
本项目仅供研究学习,不构成投资建议。所有分数、信号和实体标签都需要结合原始盘口数据和人工经验复核。
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
with open(os.path.join(output_base, "README.md"), "w") as f:
|
| 245 |
+
f.write(readme)
|
| 246 |
+
print("Dataset README written.")
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
main()
|
scripts/run_hf_sandbox.sh
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# HF Sandbox / Jobs 全量运行脚本
|
| 3 |
+
# 用法: bash scripts/run_hf_sandbox.sh
|
| 4 |
+
|
| 5 |
+
set -e
|
| 6 |
+
|
| 7 |
+
echo "===== Cross-Day Main Force Position Inference ====="
|
| 8 |
+
echo "Start: $(date)"
|
| 9 |
+
|
| 10 |
+
# 安装依赖(HF sandbox 里 huggingface_hub 通常已预装)
|
| 11 |
+
pip install -q pandas pyarrow numpy scipy scikit-learn tqdm
|
| 12 |
+
|
| 13 |
+
# 全量流水线
|
| 14 |
+
python src/scripts/pipeline.py \
|
| 15 |
+
--start 20230101 \
|
| 16 |
+
--end 20260331 \
|
| 17 |
+
--output ./outputs \
|
| 18 |
+
--full \
|
| 19 |
+
--save-intermediate
|
| 20 |
+
|
| 21 |
+
echo "===== Done: $(date) ====="
|
| 22 |
+
echo "Output files:"
|
| 23 |
+
find ./outputs -type f -name "*.parquet" -o -name "*.json" | sort
|
scripts/run_local_test.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
本地最小验证:5 个交易日,验证 pipeline 正确性。
|
| 4 |
+
|
| 5 |
+
用法:
|
| 6 |
+
python scripts/run_local_test.py
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
# 保证项目根在 path 里
|
| 14 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
| 15 |
+
|
| 16 |
+
from src.data.loader import load_l2_day, BLACKLIST_DATES
|
| 17 |
+
from src.features.passive_orders import (
|
| 18 |
+
compute_vwap,
|
| 19 |
+
extract_passive_orders,
|
| 20 |
+
prepare_features,
|
| 21 |
+
select_candidates,
|
| 22 |
+
)
|
| 23 |
+
from src.clustering.daily_cluster import cluster_candidates
|
| 24 |
+
from src.matching.cross_day_match import match_clusters, match_multi_window
|
| 25 |
+
from src.tracking.entity_tracker import EntityTracker
|
| 26 |
+
|
| 27 |
+
# 测试日期:2024年3月第二周(避开黑名单)
|
| 28 |
+
TEST_DATES = [20240311, 20240312, 20240313, 20240314, 20240315]
|
| 29 |
+
|
| 30 |
+
OUTPUT_DIR = os.path.join(
|
| 31 |
+
os.path.dirname(__file__), "..", "outputs", "local_test"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def main():
|
| 36 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 37 |
+
print(f"本地测试: {len(TEST_DATES)} 天, 输出目录: {OUTPUT_DIR}\n")
|
| 38 |
+
|
| 39 |
+
tracker = EntityTracker(inactive_threshold=5)
|
| 40 |
+
recent_history = {}
|
| 41 |
+
|
| 42 |
+
for i, date in enumerate(TEST_DATES):
|
| 43 |
+
print(f"--- {date} ---")
|
| 44 |
+
|
| 45 |
+
# 1. 加载
|
| 46 |
+
try:
|
| 47 |
+
data = load_l2_day(date)
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f" SKIP: 加载失败 ({e})")
|
| 50 |
+
continue
|
| 51 |
+
|
| 52 |
+
trades = data["trades"]
|
| 53 |
+
orders = data["orders"]
|
| 54 |
+
if "is_cancellation" in trades.columns:
|
| 55 |
+
trades = trades[~trades["is_cancellation"]]
|
| 56 |
+
|
| 57 |
+
print(f" trades={len(trades):,}, orders={len(orders):,}")
|
| 58 |
+
|
| 59 |
+
# 2. VWAP + 被动单
|
| 60 |
+
vwap = compute_vwap(trades)
|
| 61 |
+
passive = extract_passive_orders(trades, vwap)
|
| 62 |
+
candidates = select_candidates(passive, top_n=150)
|
| 63 |
+
print(f" passive_orders={len(passive):,}, candidates={len(candidates)}")
|
| 64 |
+
print(f" VWAP={vwap:.2f}, bid_candidates={len(candidates[candidates['side']=='bid'])}, ask_candidates={len(candidates[candidates['side']=='ask'])}")
|
| 65 |
+
|
| 66 |
+
if candidates.empty:
|
| 67 |
+
recent_history[date] = {}
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
# 3. 聚类
|
| 71 |
+
feats = prepare_features(candidates)
|
| 72 |
+
labeled, centroids = cluster_candidates(candidates, feats)
|
| 73 |
+
n_clusters = len(centroids)
|
| 74 |
+
n_noise = (labeled["cluster_id"] == -1).sum()
|
| 75 |
+
print(f" clusters={n_clusters}, noise={n_noise}")
|
| 76 |
+
|
| 77 |
+
# 4. 跨日匹配
|
| 78 |
+
prev_dates = sorted(
|
| 79 |
+
[d for d in recent_history.keys() if d < date]
|
| 80 |
+
)[-2:]
|
| 81 |
+
prev_c_for_match = {}
|
| 82 |
+
for pd_ in prev_dates:
|
| 83 |
+
if recent_history.get(pd_):
|
| 84 |
+
prev_c_for_match[pd_] = recent_history[pd_]
|
| 85 |
+
|
| 86 |
+
matches = match_multi_window(date, centroids, prev_c_for_match)
|
| 87 |
+
print(f" matches={len(matches)}")
|
| 88 |
+
for m in matches:
|
| 89 |
+
print(f" {m[0]} c{m[1]} → {m[2]} cost={m[3]:.3f}")
|
| 90 |
+
|
| 91 |
+
# 5. 实体追踪
|
| 92 |
+
cid_to_eid = tracker.process_day(date, centroids, matches)
|
| 93 |
+
print(f" entity mapping: {cid_to_eid}")
|
| 94 |
+
|
| 95 |
+
# 6. 仓位推断
|
| 96 |
+
signal = tracker.compute_position_signal(date)
|
| 97 |
+
print(f" signal: score={signal['score']:.4f}, bid_entities={signal['bid_entities']}, ask_entities={signal['ask_entities']}")
|
| 98 |
+
|
| 99 |
+
recent_history[date] = centroids
|
| 100 |
+
|
| 101 |
+
# ---- 导出 ----
|
| 102 |
+
print("\n===== 导出 =====")
|
| 103 |
+
|
| 104 |
+
entity_df = tracker.get_entity_timeline()
|
| 105 |
+
print(f"实体总数: {len(entity_df)}")
|
| 106 |
+
print(entity_df.to_string())
|
| 107 |
+
|
| 108 |
+
entity_path = os.path.join(OUTPUT_DIR, "entity_timeline.parquet")
|
| 109 |
+
entity_df.to_parquet(entity_path)
|
| 110 |
+
print(f"实体表 → {entity_path}")
|
| 111 |
+
|
| 112 |
+
signals_df = tracker.get_daily_signals()
|
| 113 |
+
signals_path = os.path.join(OUTPUT_DIR, "position_signal_daily.parquet")
|
| 114 |
+
signals_df.to_parquet(signals_path)
|
| 115 |
+
print(f"信号表 → {signals_path}")
|
| 116 |
+
print(signals_df[["date", "score", "score_z", "n_active_entities"]].to_string())
|
| 117 |
+
|
| 118 |
+
# 被动单样本(第一天)
|
| 119 |
+
passive_path = os.path.join(OUTPUT_DIR, "sample_passive_orders.parquet")
|
| 120 |
+
passive.to_parquet(passive_path)
|
| 121 |
+
print(f"被动单样本 → {passive_path}")
|
| 122 |
+
|
| 123 |
+
# 聚类样本
|
| 124 |
+
cluster_path = os.path.join(OUTPUT_DIR, "sample_clusters.parquet")
|
| 125 |
+
labeled.to_parquet(cluster_path)
|
| 126 |
+
print(f"聚类样本 → {cluster_path}")
|
| 127 |
+
|
| 128 |
+
print("\n===== 本地验证完成 =====")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
main()
|
scripts/validate_with_moneyflow.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
校验:将推断的主力仓位信号与 Tushare moneyflow_dc 的主力净流入做相关性检查。
|
| 4 |
+
|
| 5 |
+
这不是拟合目标——只是 sanity check,确认推断方向不与外部数据严重矛盾。
|
| 6 |
+
|
| 7 |
+
用法:
|
| 8 |
+
python scripts/validate_with_moneyflow.py --signal outputs/signals/position_signal_daily.parquet
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
from scipy.stats import pearsonr, spearmanr
|
| 21 |
+
|
| 22 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
| 23 |
+
|
| 24 |
+
from src.data.loader import load_tushare_table
|
| 25 |
+
from huggingface_hub import snapshot_download
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
parser = argparse.ArgumentParser()
|
| 30 |
+
parser.add_argument("--signal", required=True, help="position_signal_daily.parquet 路径")
|
| 31 |
+
parser.add_argument("--output-dir", default="./outputs/reports")
|
| 32 |
+
args = parser.parse_args()
|
| 33 |
+
|
| 34 |
+
# 加载信号
|
| 35 |
+
signal = pd.read_parquet(args.signal)
|
| 36 |
+
signal["date"] = signal["date"].astype(int)
|
| 37 |
+
|
| 38 |
+
# 下载并加载 moneyflow_dc
|
| 39 |
+
tushare_root = snapshot_download(
|
| 40 |
+
"kangkangchen/a-share-tushare-context-600809",
|
| 41 |
+
repo_type="dataset",
|
| 42 |
+
allow_patterns=["data/moneyflow_dc_daily/**/*.parquet"],
|
| 43 |
+
)
|
| 44 |
+
mf = load_tushare_table(tushare_root, "moneyflow_dc_daily")
|
| 45 |
+
if mf.empty:
|
| 46 |
+
print("ERROR: moneyflow_dc_daily is empty")
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
mf["trade_date"] = mf["trade_date"].astype(int)
|
| 50 |
+
|
| 51 |
+
# Merge
|
| 52 |
+
merged = signal.merge(mf, left_on="date", right_on="trade_date", how="inner")
|
| 53 |
+
print(f"Merged days: {len(merged)} / {len(signal)} signal days")
|
| 54 |
+
|
| 55 |
+
if len(merged) < 10:
|
| 56 |
+
print("Too few overlapping days for correlation")
|
| 57 |
+
return
|
| 58 |
+
|
| 59 |
+
# 相关性检查
|
| 60 |
+
# moneyflow_dc 的主力净流入字段通常叫 buy_elg_amount - sell_elg_amount 或 net_mf_amount
|
| 61 |
+
net_col = None
|
| 62 |
+
for col in ["net_mf_amount", "buy_elg_amount", "net_mainforce_amount"]:
|
| 63 |
+
if col in merged.columns:
|
| 64 |
+
net_col = col
|
| 65 |
+
break
|
| 66 |
+
# fallback: compute from buy/sell
|
| 67 |
+
if net_col is None and "buy_lg_amount" in merged.columns:
|
| 68 |
+
merged["_net_mf"] = merged["buy_lg_amount"] - merged["sell_lg_amount"]
|
| 69 |
+
net_col = "_net_mf"
|
| 70 |
+
|
| 71 |
+
if net_col is None:
|
| 72 |
+
print(f"Available moneyflow columns: {list(merged.columns)}")
|
| 73 |
+
print("Cannot find net flow column, printing sample:")
|
| 74 |
+
print(merged.head())
|
| 75 |
+
return
|
| 76 |
+
|
| 77 |
+
# Normalize
|
| 78 |
+
merged["mf_norm"] = merged[net_col] / merged[net_col].abs().mean()
|
| 79 |
+
|
| 80 |
+
for score_col in ["score_z", "score"]:
|
| 81 |
+
if score_col not in merged.columns:
|
| 82 |
+
continue
|
| 83 |
+
clean = merged.dropna(subset=[score_col, net_col])
|
| 84 |
+
r_pearson, p_pearson = pearsonr(clean[score_col], clean[net_col])
|
| 85 |
+
r_spearman, p_spearman = spearmanr(clean[score_col], clean[net_col])
|
| 86 |
+
print(f"\n{score_col} vs {net_col}:")
|
| 87 |
+
print(f" Pearson: r={r_pearson:.4f}, p={p_pearson:.4f}")
|
| 88 |
+
print(f" Spearman: r={r_spearman:.4f}, p={p_spearman:.4f}")
|
| 89 |
+
print(
|
| 90 |
+
f" Interpretation: {'同向 ✓' if r_pearson > 0 else '反向 ✗' if r_pearson < -0.1 else '弱相关'}"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# 保存合并结果
|
| 94 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 95 |
+
out_path = os.path.join(args.output_dir, "signal_vs_moneyflow.parquet")
|
| 96 |
+
merged.to_parquet(out_path)
|
| 97 |
+
print(f"\nMerged data saved to {out_path}")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
main()
|