claude-trading-skills 回放提示词契约解析:required-only 模式下的 Stockbee 20% 研究流水线

原创2026-11-15 09:42:191,352 阅读
文章标签:金融科技AI 技能人工智能数据分析

claude-trading-skills 回放提示词契约解析:required-only 模式下的 Stockbee 20% 研究流水线

examples/workflows/stockbee-20pct-study-daily/sample-run/prompt.md 只有五行,却是整个可执行回放(executable replay)体系中最靠近"使用者"的一层接口:它规定了 Agent 在 required-only 变体下必须做什么、必须禁止什么、以及必须跳过什么。本文以这份提示词为骨架,逐条拆解它在仓库中对应的校验代码、执行器实现、产物规范化规则与可验证输出,说明一条看起来只是"自然语言指令"的提示词,是如何被 replay.yaml 这样的机器可读契约强制约束住的。读完后你可以独立运行该回放、读懂生成的 manifest 与产物,并判断哪些结论是证据支持的、哪些仍然只是观察。

提示词原文与它在回放体系中的位置

被分析的文档全文如下(prompt.md):

# Prompt: required-only stockbee-20pct-study-daily replay

Replay this workflow with the bundled fictional input data. This is not investment advice and must not submit orders or call live APIs.

Skip every optional step.

它包含三条明确的约束:

条款 原文要点 强制落点
输入约束 bundled fictional input data replay.yaml 的 inputs 段,全部指向 replay-inputs/ 下的离线夹具
安全约束 not investment advice、must not submit orders or call live APIs network_policy: offline-input-required、环境变量清洗、无 API key / universe 参数
范围约束 Skip every optional step variants.required-only.enabled_steps: [1,2,3,4],第 5 步不执行

值得先说明的一点是:这份 prompt.md 并不是手写的说明文档,而是由回放框架生成的。生成逻辑位于 execution.py 的 _prompt_text():

def _prompt_text(workflow: Mapping[str, Any], variant: str) -> str:
    if variant == "required-only":
        optional_text = "Skip every optional step."
    elif workflow["id"] == "stockbee-20pct-study-daily":
        optional_text = (
            "Run the optional human-approved lessons step after reviewing the 20% mover "
            "cohort evidence."
        )

也就是说,required-only 分支是通用模板,而 full-path 分支对本工作流有专门措辞(对应 sample-run-full-path/prompt.md)。生成的提示词随后被写入产物目录,并在 manifest.yaml 中以 prompt: prompt.md 字段回指。

这种设计的意义在于:提示词不是独立于测试的自由文本,而是"变体语义的可读投影"。契约测试 test_workflow_examples_issue208.py 会检查样例目录里的提示词是否包含 fictional 与 not investment advice 这两个关键语义:

prompt_text = " ".join(prompt.read_text(encoding="utf-8").lower().split())
assert "fictional" in prompt_text
assert "not investment advice" in prompt_text

换句话说,任何人修改提示词却删掉了虚构数据声明或免责声明,CI 就会失败。这是"文档即契约"的具体实现。

第一条约束:bundled fictional input data 如何被锁死

提示词要求"用打包的虚构输入数据回放",这条约束在执行层是通过"输入声明 + 必需输入表"双向锁定的。

inputs 段声明的三份夹具

replay.yaml 只声明三个输入:

inputs:
  prices: replay-inputs/prices.json
  news: replay-inputs/news.json
  accepted_lessons: replay-inputs/accepted_lessons.yaml

三份夹具内容都对得上提示词中的"fictional":

  • prices.json 只有一个虚构代码 FICT20,提供 10 根日线,2026-01-06 那天从 10.4 跳空到 12.2 开盘、13.0 收盘;
  • news.json 只有一条虚构新闻 Fictional company reports earnings and raises revenue outlook;
  • accepted_lessons.yaml 是人审通过的虚构教训夹具,供 full-path 变体使用。

校验器强制"执行器需要什么输入就必须先声明"

manifest.py 维护了一张 executor_required_inputs 映射,把每个执行器与它必需的离线输入绑定。与本工作流相关的四条是:

"twenty_pct_scan": {"prices"},
"twenty_pct_enrich": {"news"},
"twenty_pct_update_outcomes": {"prices"},
"manual_twenty_pct_lessons": {"accepted_lessons"},

随后 validate_spec() 逐个步骤比对:如果某个执行器需要的输入没有在 inputs 中出现,就抛出 requires offline inputs 错误。这条机制把提示词的"用打包数据"从口号变成了不可绕过的前置条件——你无法在没有 news.json 的情况下跑 enrich。

同时,输入路径必须是通过 _safe_relative() 解析出的、位于 spec 目录内的相对路径,禁止绝对路径与 .. 逃逸(见 normalize.py)。这阻断了"把提示词改写成指向本机真实行情文件"的可能性。

输入的全部形态

prices.json 的加载器支持多种形状。源码 run_20pct_study.py 中的 load_prices_json() 接受:

  1. {"prices": {"AAPL": [bars]}}
  2. {"data": {...}} 或 {"ohlcv": {...}}
  3. 顶层直接是 symbol -> rows 的映射
  4. 行列表(每行带 symbol/ticker 字段),由 rows_to_prices_by_symbol() 分组

夹具采用的是第 1 种。了解这一点对替换为自有数据很重要:--prices-json 并不要求某种私有格式,常见的 OHLCV 导出都能直接被吸收;缺失或非正的 OHLC 会被 normalize_price_bars() 静默丢弃。

第二条约束:不构成投资建议、不下单、不调用实时 API

这一条是提示词里最"像免责声明"的一句,但它在仓库中有三层可验证的工程实现。

第一层:network_policy 的显式记录

执行报告会把策略写成 offline-input-required(execution.py),并原样落到 manifest 的 network_policy 字段。样例 README 对这一点的措辞很克制:README.md 明确说明

Every native command receives bundled --prices-json or --news-json input; none receives a live-universe or API-key flag. Sensitive environment variables are removed before subprocess execution. This is an offline-input policy, not an operating-system network sandbox.

最后一句是重要的证据边界:这是输入策略,不是操作系统级网络沙箱。回放不会拦住你自己写的脚本发请求,它只保证回放自身不给出联网参数、并清掉凭据环境变量。

第二层:执行器根本不传联网参数

看真实调用点 steps_twenty_pct.py,扫描步骤的命令行是硬编码的:

_run_cli(
    [
        sys.executable,
        str(_twenty_pct_script(repo_root)),
        "scan",
        "--prices-json",
        str(inputs["prices"]),
        "--as-of",
        spec["fixed_timestamp"][:10],
        "--lookback-days", "5",
        "--min-price", "1",
        "--min-dollar-volume", "0",
        "--include-down-movers",
        "--state-file", str(state),
        "--output-dir", str(reports),
    ],
    repo_root,
)

没有 --fmp-universe,没有 --symbols,没有 --api-key。而 CLI 侧 run_20pct_study.py 的 load_prices_for_args() 只有在 --prices-json 缺失时才会转向 FMP 分支,否则直接读取本地文件:

def load_prices_for_args(args, days=320):
    if getattr(args, "prices_json", None):
        return load_prices_json(args.prices_json), {
            "source": "prices_json",
            "path": args.prices_json,
        }
    if getattr(args, "fmp_universe", False) or getattr(args, "symbols", None):
        prices, stats = fetch_prices_from_fmp(args, days=days)
        ...
    raise ValueError("Provide --prices-json, --symbols, or --fmp-universe.")

此外 FMPClient 只在需要时才按路径加载同目录的 fmp_client.py(_load_shared_fmp(),见 run_20pct_study.py),因此即使机器上没装 requests,离线路径也能正常跑——MissingDependencyError 只在构造客户端时抛出。

第三层:子进程环境变量清洗

_run_cli() 在启动原生 CLI 之前会调用 _scrubbed_environment(),移除任何名称包含 SENSITIVE_ENV_MARKERS 的变量:

SENSITIVE_ENV_MARKERS = ("API_KEY", "TOKEN", "SECRET", "PASSWORD", "PROXY")

并且 env_overrides 参数本身也拒绝注入敏感键(common.py)。这意味着即使开发者本机设置了 FMP_API_KEY,回放子进程也拿不到它——"不调用实时 API"因此不仅靠参数缺失,还靠凭据缺失形成双重保险。

关于"不下单"

研究脚本本身没有任何下单代码路径。其文档字符串直接写明:

The script is intentionally research-oriented: it creates study records, updates forward outcomes, and summarizes cohorts. It never places orders or outputs broker instructions.

(run_20pct_study.py)

产物中也不存在任何 broker 指令字段,所有动作止步于"研究记录 + 结果标签"。

第三条约束:Skip every optional step 的机械含义

这句最短的指令,恰好是 required-only 变体存在的全部理由。它的机械含义在 replay.yaml 中一目了然:

variants:
  required-only:
    enabled_steps:
      - 1
      - 2
      - 3
      - 4
    golden_dir: sample-run
  full-path:
    enabled_steps:
      - 1
      - 2
      - 3
      - 4
      - 5
    golden_dir: sample-run-full-path

谁定义了"optional"

"可选"不是回放自己发明的,而是从规范工作流 workflows/stockbee-20pct-study-daily.yaml 继承的。第 5 步带有显式的 optional: true:

- step: 5
  name: Log accepted lessons
  skill: trader-memory-core
  optional: true
  consumes:
    - twenty_pct_cohort_summary
    - edge_hints_yaml
  produces:
    - accepted_lessons_log
  decision_gate: true

而 validate_spec() 会强制校验变体与工作流的对应关系(manifest.py):

expected_required = [
    number for number, step in workflow_steps.items() if not bool(step.get("optional"))
]
expected_full = sorted(workflow_steps)
if variants["required-only"]["enabled_steps"] != expected_required:
    raise ReplayError(
        "required-only enabled_steps must contain exactly the non-optional workflow steps"
    )
if variants["full-path"]["enabled_steps"] != expected_full:
    raise ReplayError("full-path enabled_steps must contain every workflow step")

这条校验有两个作用:一是防止有人在 required-only 里偷偷加上可选步骤(违背提示词);二是防止有人漏掉必需步骤(让"必跑"名不副实)。契约测试 test_workflow_replay_twenty_pct.py 进一步断言执行器类型划分:

assert summary["native_steps"] == [1, 2, 3, 4]
assert summary["manual_contract_steps"] == [5]

跳过的痕迹:optional_steps_skipped

"跳过"不是沉默地不执行,而是必须留下记录。manifest 生成逻辑在 execution.py 中写入:

skipped = [
    {
        "step": int(step["step"]),
        "skill": step["skill"],
        "reason": "required-only executable replay",
    }
    for step in workflow["steps"]
    if step.get("optional") and variant == "required-only"
]

对应产物见 manifest.yaml:

optional_steps_skipped:
- step: 5
  skill: trader-memory-core
  reason: required-only executable replay

并且该变体目录中确实不存在 05_accepted_lessons_log.yaml(与 full-path 目录的差异正是这一个文件加 manifest/prompt 的差异)。测试用一行断言固化它:assert not (output / "05_accepted_lessons_log.yaml").exists()。

被保留的四个步骤:一次完整的 20% 事件研究链路

required-only 覆盖的四个步骤全部是 stockbee-20pct-study 技能的原生 CLI,各自有独立产物。

步骤 执行器 模式 gate_policy 规范产物 状态产物
1 twenty_pct_scan native_cli continue 01_twenty_pct_mover_events.json 01_twenty_pct_events.jsonl
2 twenty_pct_enrich native_cli continue 02_classified_event_study.json 02_twenty_pct_events.jsonl
3 twenty_pct_update_outcomes native_cli continue 03_matured_event_outcomes.json 03_twenty_pct_events.jsonl
4 twenty_pct_summarize native_cli record_only 04_twenty_pct_cohort_summary.json、04_edge_hints.yaml —

gate_policy 不是自由填写项。manifest.py 规定:非决策门步骤只能是 continue;决策门步骤可在 record_only/continue/halt 中选择。第 4 步在工作流里带 decision_gate: true("哪些形态样本足够、结果稳定、执行可行,值得从观察升级为研究?"),回放选择 record_only——记录结论但不中断流水线。这正好呼应了提示词的精神:回放负责产证据,不负责做决定。

步骤 1:扫描与宽松阈值

回放传入的阈值比 CLI 默认值宽得多:

参数 CLI 默认值 回放取值 原因
--lookback-days 5 5 与 5 日复盘窗口一致
--min-abs-return-pct 20.0 未覆盖(默认 20.0) 保留 20% 阈值语义
--min-price 5.0 1 夹具收盘价 13.0,压低门槛便于小样本通过
--min-dollar-volume 20,000,000 0 虚构标的成交额不足真实流动性门槛
--include-down-movers 关闭 开启 同时研究 +20% 与 -20%
--as-of 最新可用 bar fixed_timestamp[:10] = 2026-01-06 时间锚定,保证可复现

注意 --as-of 取自 fixed_timestamp,这是整个回放确定性的根:同一夹具在任何机器、任何日期运行,都落在 2026-01-06。min_dollar_volume: 0.0 也会如实写进元数据(见 01_twenty_pct_mover_events.json),让读者一眼看出"这次扫描没有做流动性过滤"。

扫描出的记录里值得关注的字段:

"price_snapshot": {"close": 13.0, "previous_close": 10.4, "lookback_close": 10.0,
                   "return_pct": 30.0, "day_return_pct": 25.0,
                   "gap_pct": 17.3077, "close_location_pct": 71.43},
"liquidity": {"volume_ratio_20d": 2.727, "dollar_volume": 78000000.0},
"technical_context": {"pattern_label": "BASE_BREAKOUT", "close_quality": "MID_CLOSE",
                      "extension_risk": "LOW", "base_depth_pct": 8.4112},
"scores": {"continuation_quality_score": 66, "reversal_risk_score": 33,
           "study_priority_score": 81, "data_quality_score": 85}

这些标签来自 run_20pct_study.py 的 classify_chart_pattern():near_52w_high = distance >= -5.0、close_location >= 70、volume_ratio_20 >= 1.5 同时满足才判 BASE_BREAKOUT。本例距 52 周高点 -2.9851%、收盘位于日内 71.43%、量比 2.727,条件全部命中。

data_quality_score = 85 是因为有一条 flag:SHORT_HISTORY_LT_260_BARS(历史只有 10 根 bar,不足 260)。计分规则见 run_20pct_study.py 与 score_event() 中的 data_quality_score = max(0, 100 - len(flags) * 15)。

步骤 2:新闻富化改变的不只是标签

enrich 会按 event_date 向前 3 天内匹配同代码新闻(pick_news_for_event(),max_lag_days=3),然后用关键词表分类催化剂。run_20pct_study.py 的 classify_catalyst_from_text() 对命中的关键词计数:confidence = min(0.95, 0.45 + 0.15 * matches)。夹具标题同时命中 earnings 与 revenue,两个关键词 → 0.45 + 0.30 = 0.75,与产物中的 confidence: 0.75 完全一致。

富化会触发重新计分(run_20pct_study.py),因为催化剂权重在 score_event() 的表中差异巨大:

催化剂标签 分数权重
EARNINGS_REVALUATION / GUIDANCE_RAISE 24
M&A 22
CONTRACT_ORDER 18
FDA_CLINICAL / THEME_SYMPATHY 14
ANALYST_UPGRADE 12
NO_CLEAR_NEWS 3
LOW_FLOAT_SPECULATION / CAPITAL_STRUCTURE 0

于是同一事件在两次产物中的评分发生跳变:

字段 步骤 1(NO_CLEAR_NEWS) 步骤 3(EARNINGS_REVALUATION)
continuation_quality_score 66 87
reversal_risk_score 33 8
study_priority_score 81 93
质量标签 B_MOMENTUM_EVENT A_REVALUATION_OR_HIGH_QUALITY_EVENT

reversal_risk_score 从 33 掉到 8,是因为 NO_CLEAR_NEWS 本身贡献 +25(if catalyst_label in {"NO_CLEAR_NEWS", ...}: reversal_risk_score += 25)。这段对比很能说明回放的价值:它把"有没有催化剂"从一句定性判断,变成了可复算的分差。

连带变化的还有 handoffs 交接旗标(handoff_flags(),run_20pct_study.py):

"pead_screener": catalyst_label in {"EARNINGS_REVALUATION", "GUIDANCE_RAISE"},
"edge_candidate_agent": scores.get("study_priority_score", 0) >= 85,
"theme_detector": catalyst_label == "THEME_SYMPATHY" or scores.get("study_priority_score", 0) >= 80,

步骤 1 时 pead_screener: false、edge_candidate_agent: false;富化后两者双双变 true(priority 93 ≥ 85)。这说明下游技能的"该不该被唤起"也是被数据驱动的,而不是提示词里拍板的。

步骤 3:五日前瞻结果的成熟

回放只要求 5 日地平线(--horizons 5),而不是 CLI 默认的 1,3,5,10,20。原因是夹具只有 10 根 bar:update_forward_outcomes() 需要 idx + horizon < len(bars),超出则写入 status: "PENDING" 并记 insufficient_future_bars。截取 5 日既能演示"成熟",又不会制造一堆 PENDING 噪声。

产物中的成熟结果(03_matured_event_outcomes.json):

"5d": {
  "status": "MATURED", "horizon_days": 5,
  "entry_close": 13.0, "close": 15.2, "close_date": "2026-01-11",
  "close_return_pct": 16.9231,
  "mfe_pct": 19.2308, "mae_pct": -1.5385,
  "directional_close_return_pct": 16.9231,
  "directional_mfe_pct": 19.2308, "directional_mae_pct": -1.5385,
  "outcome_tag": "STRONG_CONTINUATION"
}

mfe_pct = 19.2308 对应未来 5 日最高 15.5((15.5/13.0-1)*100),mae_pct = -1.5385 对应最低 12.8。方向化处理对做多与做空是镜像的:direction == "DOWN" 时 directional_close = -close_return,MFE/MAE 也用 entry_close - low / entry_close - high 换算(update_forward_outcomes())。这一点很重要——如果不做方向化,"跌 20% 后继续跌 10%"会被记成负收益,与"研究下跌延续性"的意图相反。

STRONG_CONTINUATION 的判定门槛见 classify_outcome():directional_close >= 8 or directional_mfe >= 12。本例 16.92 / 19.23 双双越线。

步骤 4:分组、样本数与候选规则

汇总步骤传入显式分组维度与最小样本:

"summarize",
"--state-file", str(state),
"--group-by", "direction,catalyst.label,technical_context.pattern_label,technical_context.close_quality",
"--min-sample", "1",
"--horizon", "5",
"--output-dir", str(reports),

--min-sample 1 是回放相对默认值(10)最重要的松动。summarize_cohorts() 只有在 len(items) >= min_sample 时才尝试生成规则候选,因此真实研究里默认要求 10 个样本,而夹具只有 1 个——如果照搬默认值,产物会是空的,回放就"用空流水线通过了",这正是样例 README 所强调要避免的情况:

The fixture deliberately produces one mover, one matched news catalyst, one matured outcome, and one research candidate so an empty pipeline cannot pass.

(README.md)

候选规则的判定逻辑在 candidate_rule_from_cohort()(run_20pct_study.py):

if win_rate >= 0.58 and median_return >= 2.0:
    status = "candidate_for_review"
    thesis = "Continuation-favorable cohort; promote only after representative chart review and out-of-sample validation."
elif win_rate <= 0.42 and median_return <= -2.0:
    status = "avoid_or_fade_study"
    thesis = "Weak continuation cohort; useful as avoid filter or fade hypothesis, not an automatic short signal."
else:
    return None

本例 win_rate 1.0、中位方向收益 16.9231,落入第一支,产物 status 为 candidate_for_review,并附带三条固定的 required_review(图表复核、年度/制度稳定性、执行现实性)。如果记录带 CURRENT_UNIVERSE_BACKFILL_SURVIVORSHIP_BIAS,还会追加第四条关于生存者偏差的复核要求。

edge hints 与 cohort summary 之间的一致性是被强制断言的(steps_twenty_pct.py):

if hints.get("edge_hints") != summary.get("rule_candidates"):
    raise ReplayError("edge_hints handoff does not match cohort summary rule_candidates")

这条断言堵住了"下游拿到一份与上游证据不一致的提示清单"这类隐蔽漂移。

产物规范化:为什么回放能稳定复现

四个步骤都产出"canonical JSON + state JSONL"这对文件。规范化的关键在于 normalize.py 的 _canonicalize():它把 TIMESTAMP_FIELDS 中的时间字段统一替换为 fixed_timestamp:

TIMESTAMP_FIELDS = frozenset(
    {"generated_at", "created_at", "updated_at", "last_outcome_update_at", "recorded_at"}
)

同时把临时路径替换成语义占位符。扫描步骤声明的替换表是:

replacements = {
    str(inputs["prices"]): "$INPUT/prices.json",
    str(state): "$STATE/events.jsonl",
    str(reports): "$WORK/reports",
}

于是产物里出现的是 "path": "$INPUT/prices.json"(可在 01_twenty_pct_mover_events.json 中看到),而不是某些机器相关的 /tmp/... 绝对路径。替换按路径长度降序执行,先替换更长的具体文件路径再替换父目录,避免目录前缀误伤同名兄弟目录——这个细节写在 _canonicalize() 的注释里。

state JSONL 的规范化还承担"步骤间状态交棒"的职责。每个后续步骤都会把上一步产物的 state 文件预处理到工作目录(_stage_state_handoff()),再交给原生 CLI。这样原生 CLI 看到的永远是干净、时间戳已锚定的事件流。

最终产物的完整性由 _validate_artifact_files() 与 _validate_artifact_provenance() 校验,并且发布是事务性的:任何一步失败,目标输出目录中已有的内容保持不变。测试 test_invalid_offline_input_fails_without_partial_publication 用 sentinel 文件验证了这一点(test_workflow_replay_twenty_pct.py):

sentinel.write_bytes(b"unchanged\n")
with pytest.raises(ReplayError) as exc_info:
    execute_replay(ROOT, SPEC, "required-only", output, input_overrides=...)
assert sentinel.read_bytes() == b"unchanged\n"
assert {path.name for path in output.iterdir()} == {"existing.txt"}

与 full-path 的唯一差别:一条被 SHA-256 钉住的经验

full-path 变体只多做一件事:执行第 5 步 manual_twenty_pct_lessons,把一个人审通过的经验记录落盘。它的提示词差别也只有一句(full-path prompt.md):

Run the optional human-approved lessons step after reviewing the 20% mover cohort evidence.

但这一步的校验密度远超其他步骤(steps_twenty_pct.py):

  1. 输入必须满足 twenty-pct-lessons.schema.json 的 input 定义;
  2. 必须 human_approved: true;
  3. source_artifacts 必须恰好是 ["twenty_pct_cohort_summary", "edge_hints_yaml"];
  4. 必须同时收到这两个上游产物;
  5. 必须重新计算两份产物的 SHA-256,并与输入声明的 source_sha256 完全一致;
  6. 输出再按 output 定义校验一次。

产物中的 provenance 极其克制地记录了自己没做什么(05_accepted_lessons_log.yaml):

provenance:
  execution_mode: manual_contract
  native_trader_memory_validated: false
  source_sha256:
    twenty_pct_cohort_summary: 17a60a0e...
    edge_hints_yaml: 32c77310...
  note: Human-approved fixture staged by replay harness; no trader-memory-core append API was executed.

这段 provenance 是整篇文档最重要的"证据边界"示例:它明确写了 native_trader_memory_validated: false,即并没有真的调用 trader-memory-core 的追加接口。README 也给出了这条经验为什么只能是 journal_only 的理由——一个虚构观察不足以支撑交易规则变更:

The full-path lesson remains journal_only because one fictional observation cannot justify a trading-rule change.

(README.md)

对应的领悟记录内容是:

lessons:
- lesson_id: fictional-earnings-continuation-observation
  decision: journal_only
  observation: Keep this single fictional continuation example as a research observation only.
  changes_trading_rules: false

若把 decision 改成 rejected 却保留 changes_trading_rules: true,输出 schema 校验会直接失败(见 test_non_operating_lesson_cannot_claim_rule_changes_on_output)。这类"语义自相矛盾必须报错"的约束,比任何文档提醒都更可靠。

如何实际运行这个回放

从仓库根目录运行 required-only 变体(命令来自 README.md):

python3 scripts/workflow_replay.py run \
  --spec examples/workflows/stockbee-20pct-study-daily/replay.yaml \
  --variant required-only \
  --output-dir /tmp/stockbee-20pct-required

命令会打印完整执行报告(每步的 executor_mode、gate_policy、consumed、produced),并在输出目录写下 manifest.yaml、prompt.md 与四个步骤的产物。

与之配套的两个命令:

# 在临时目录重跑全部覆盖样例,与提交的 golden 目录逐字节比对
python3 scripts/workflow_replay.py check

# 用当前源码重新生成 golden 目录(仅在契约有意变更时使用)
python3 scripts/workflow_replay.py generate

check 子命令由 cli.py 定义,实际逻辑在 check_goldens():它先校验覆盖清单,再对每个 workflow 的每个变体执行 execute_replay(),最后用 compare_trees() 与 golden_dir 比较。有差异就返回非零退出码并列出漂移项,可直接作为 CI 门禁。

覆盖清单 replay-coverage.yaml 登记了本工作流的两个变体:

  stockbee-20pct-study-daily:
    spec: stockbee-20pct-study-daily/replay.yaml
    variants:
      - required-only
      - full-path

而 constants.py 把"延迟覆盖集合"冻结为空集,注释说明了意图:

# Coverage 14/14 leaves no workflow deferred. This frozen baseline prevents a
# newly introduced workflow from being waved through as another deferral.
FROZEN_DEFERRED_WORKFLOWS = frozenset()

也就是说,新增工作流不能靠"标记为暂缓"躲过回放契约。

自己托管一份离线输入的注意事项

如果你想用自有 OHLCV 替换夹具,需要满足以下条件(结论均来自源码,非推测):

  1. prices.json 每个标的的 bar 日期必须唯一且递增,重复日期会被 normalize_price_bars() 去重;
  2. OHLC 必须全部为正且 high >= low,否则该 bar 被丢弃;
  3. 扫描前至少要 lookback_days + 1 根 bar,否则计入 insufficient_lookback 跳过;
  4. 要覆盖 10/20 日地平线,需要事件日之后至少对应根数的未来 bar,否则得到 PENDING;
  5. 历史长度不足 260 根会自动打 SHORT_HISTORY_LT_260_BARS,并把 data_quality_score 扣 15 分;
  6. 用 backfill 补历史时必须带 --prices-json(源码明确拒绝无控制联网扫描),且默认打上 CURRENT_UNIVERSE_BACKFILL_SURVIVORSHIP_BIAS,只有传入 --survivorship-complete 才会取消该标记。

边界与正确使用姿势

最后需要把"这份提示词能保证什么、不能保证什么"讲清楚,因为回放文档最容易产生的误读就是把"离线"当成"安全沙箱"、把"候选规则"当成"交易信号"。

它能保证的:

  • 每个原生命令只收到离线输入参数,不会拿到 live universe 或 API key 开关;
  • 子进程环境变量中敏感键被移除;
  • required-only 变体确实只跑 1–4 步,且跳过痕迹写入 manifest;
  • 产物时间戳与路径被锚定,重跑结果一致;
  • 产物之间的证据链一致(edge hints 与 rule candidates、lessons 与上游 SHA-256);
  • 失败时不会发布半成品。

它不能保证的(源码与文档明确声明的限制):

  • 不是操作系统网络沙箱,无法阻止第三方代码自行联网;
  • 单样本产生的 candidate_for_review 只是研究提示,min_sample: 1 是为小夹具让步,不是研究标准;
  • 当前标的集合的历史回补默认带生存者偏差标记;
  • full-path 的第 5 步是 manual_contract,native_trader_memory_validated 为 false,并未真正写入 trader-memory-core;
  • 回放不验证真实 FMP 响应、字段漂移与限流行为。

工作流自身的 when_not_to_run 也把话说得很直:不要把它当买卖信号工作流或自动执行系统,不要从小样本、仅含当前标的集合的分析、或缺少生存者偏差与数据质量说明的事件中提拔新规则(workflows/stockbee-20pct-study-daily.yaml)。而 manual_review 清单则给出了把观察升级为规则的检查顺序:先看代表性成功与失败图表,严格区分观察、研究假设与可执行交易计划,再交给 monthly-performance-review 汇总,而不是临时改规则。

把这几条与那份五行提示词放在一起看,就能理解整个设计的取舍:提示词只写三句话,因为所有可执行的细节都已经下沉到 YAML 契约、执行器实现与产物校验里;而提示词之所以仍然是必要的,是因为它提供了唯一一处人类和 Agent 都能一眼读懂的行为承诺——用虚构数据、不联网、不下单、只跑必跑步骤。

登录后查看全文
claude-trading-skills