Files
sfgrid/models/reference_backtest_logic
2026-06-24 16:13:44 +08:00
..
2026-06-24 12:19:08 +08:00
2026-06-24 16:13:44 +08:00

v6.7r3 代码使用说明

code/ 目录包含 v6.7r3 策略的自包含实现,可在不依赖项目其他模块的情况下独立运行。

文件清单

文件 大小 作用
strategy.py ~22 KB 完整策略实现(模型加载/特征/网格/沉寂/周度淘汰)

文件结构

strategy.py
├── 配置常量 (网格/价格/沉寂/周度)
├── 1. 持仓 + 网格交易
│   ├── Position dataclass
│   ├── compute_initial_position() 初始建仓
│   ├── compute_single_position()  单格建仓
│   └── simulate_grid_day()         单日网格 (LIFO)
├── 2. 5 特征沉寂检测
│   └── is_slumbering()  5 特征 ≥ 3 触发
├── 3. 模型加载 + 三件套预测
│   ├── ModelBundle class
│   │   ├── load 3 .pkl
│   │   └── predict(X56) → {rank_score, top_prob, stack_prob}
├── 4. 特征计算
│   ├── compute_52_base_features()  52 维 v3.4 基础
│   └── compute_4_v67_new_features()  4 维 v6.7 新增
├── 5. 评分池
│   └── score_pool()  单日全市场评分
├── 6. 主回测入口(精简版)
│   └── quick_backtest()  生产级完整版见 tools/backtest_v67r2.py
└── 7. 入口示例
    └── __main__  加载模型 + 加载行情 + 跑回测

快速开始

# 1. 安装依赖
pip install pandas numpy lightgbm scipy

# 2. 准备数据
#   方式 A: 用项目内的 dump_market_data_to_parquet.py 拉 Postgres
python tools/dump_market_data_to_parquet.py
#   方式 B: 直接用现有 parquet (release/v6.7r3 之前已生成 5025 个)

# 3. 运行
cd release/v6.7r3/code
python strategy.py

核心 API 速查

1. 加载模型

from strategy import ModelBundle

models = ModelBundle("../models")
# 等价: models = ModelBundle("release/v6.7r3/models")
print(models.rank_feats[:5])  # ['rolling_grid_ratio_20d', ...]

2. 三件套预测

import numpy as np
import pandas as pd

# 加载单只股 120 日窗口
df_window = pd.read_parquet("data/market_data/share/000001.parquet")
df_window["date"] = pd.to_datetime(df_window["date"])
df_window = df_window.tail(120).reset_index(drop=True)

# 算 56 维特征 (这里用简化版, 生产建议用项目 core.features)
from strategy import compute_52_base_features, compute_4_v67_new_features
fd = compute_52_base_features(df_window)
fd = compute_4_v67_new_features(df_window, fd)
X56 = np.array([fd.get(k, 0.0) for k in models.rank_feats], dtype=np.float64).reshape(1, -1)

# 三件套预测
pred = models.predict(X56)
print(f"rank_score: {pred['rank_score'][0]:.3f}")
print(f"top_prob:   {pred['top_prob'][0]:.3f}")
print(f"stack_prob: {pred['stack_prob'][0]:.3f}")  # 月末选股用

3. 沉寂检测

from strategy import is_slumbering

df = pd.read_parquet("data/market_data/share/000001.parquet")
df["date"] = pd.to_datetime(df["date"])
slumbering = is_slumbering(df, min_triggers=3)
# True = 5 特征中至少 3 个触发 → 资金离场

4. 网格交易(单日)

from strategy import Position, simulate_grid_day

pos = Position(code="000001", base=10, queue=[10.0, 9.5], entry_date="2023-05-01")
new_base, new_queue, trades = simulate_grid_day(
    pos.base, pos.queue,
    open_p=9.4, high_p=10.6, low_p=9.3, close_p=10.5,
)
# 触发 buy at 9.0 (low 9.3 <= 9.0? no, 9.3 > 9.0 不触发)
# 触发 sell at 10.0 (high 10.6 >= 10.0, 卖出 1 格)
# 最终: base=11, queue=[9.5] (1 格清仓)

5. 评分池(每日全市场)

from strategy import score_pool, ModelBundle
import pandas as pd

# 假设 kline_cache 是 dict[code, DataFrame]
models = ModelBundle("../models")
pool = score_pool(pd.Timestamp("2024-03-15"), kline_cache, models, models.rank_feats)
# pool 列: code6, latest_close, rank_score, top_prob, stack_prob
# 按 stack_prob 降序, 取 top 10
top10 = pool.head(10)

关键参数(可调)

参数 默认 说明 调优方向
WEEKLY_ELIM_N 2 周度淘汰: 连续 N 周不在 top 50 1 太频, 3+ 太慢
SLUMBER_TRIGGERS 3 沉寂检测: >= 3/5 特征触发 2 太宽, 4 太严
SLUMBER_DAYS 10 连续触发多少天清仓 5 太短, 20 太长
TOP_N 10 最大持仓数 5-15 视资金量
SHARES_PER_GRID 200 单格股数 (2 手) 100 (1 手) 也可
REFILL_PRICE 9.0-9.8 补仓价格区间 紧贴 9-10 网格上限

依赖项目其他模块?

为保持 code/ 目录自包含:

  • 不依赖 core/features.py (内置 compute_52_base_features 简化版)
  • 不依赖 training/dataset_builder.py (内置 compute_4_v67_new_features)
  • 需要数据: parquet 行情文件

生产部署建议:用 core/features.calculate_features 替换 compute_52_base_features, 它有完整版 v3.4 52 维特征实现,精度更高。

完整版 vs 精简版

维度 code/strategy.py (精简) tools/backtest_v67r2.py (生产)
特征计算 简化版 (10 维示例) 完整版 (52 维 v3.4 + 4 维 v6.7)
数据加载 dict of DataFrame parquet 目录 + score cache
日志 详细进度打印
输出 dict 指标 CSV/JSON/PNG 完整产物
速度 慢 (无缓存) 快 (有 score cache)
用途 教学/集成 完整回测

生产环境:用 tools/backtest_v67r2.py 跑回测,确保完整功能。 集成到实盘系统:用 code/strategy.py 中的 ModelBundlequick_backtest 作为模板。