Trader Memory Core 论点生命周期全解:状态机、部分平仓 P&L 与回溯日期实践

原创2026-11-15 12:26:351,858 阅读
文章标签:金融科技AI 技能人工智能数据分析

Trader Memory Core 论点生命周期全解:状态机、部分平仓 P&L 与回溯日期实践

本文以 claude-trading-skills 仓库中 trader-memory-core 技能的论点生命周期规范为主线,系统讲解投资论点从 IDEA 到 CLOSED/INVALIDATED 的六态状态机、合法与非法迁移、部分平仓的累计盈亏算法,以及用 --event-date 为已有券商持仓补齐时间线的实操方法。读完后你将能够不写一行 Python,仅靠 CLI 就把一笔交易从"筛选候选"完整走完到"平仓复盘",并知道每一步在源码里被哪条不变量卡住。

为什么需要一套显式的论点状态机

交易的真正成本往往不在开仓,而在"想法与持仓脱节":筛出来的候选没人跟踪,开了仓的忘了原定止损,减了仓的算不清到底赚了多少。trader-memory-core 的解法是把每个投资想法落成一个可校验的 YAML 文件(thesis object),由 thesis_store.py 统一承担状态推进与金额记账,任何一个非法动作都会在写盘前被拒绝。

生命周期规范本身定义在 thesis_lifecycle.md,它是行为契约;代码实现分散在 thesis_store_parts/ 目录的六个源码片段中(validation.py、persistence.py、lifecycle.py、positions_equity.py、positions_futures.py、queries.py),由 thesis_store.py 的 _exec_parts() 按序执行进同一命名空间。理解这一"契约 + 实现"的对应关系,是读懂所有报错信息的前提。

六个状态与它们的触发条件

Status 语义 典型触发
IDEA 已筛选出的候选,尚未确认为可入场 从 screener 输出 ingest
ENTRY_READY 已验证,入场条件已定义,等价格 人工复核 / 深度分析
ACTIVE 已建仓(actual_price 与 actual_date 已填);shares_remaining == shares 确认成交执行
PARTIALLY_CLOSED 已减仓;0 < shares_remaining < shares trim() 卖出部分股数
CLOSED 完全退出,结果已记录;shares_remaining == 0 确认退出执行
INVALIDATED 论点在建仓前或持仓中被否证 触发 kill criteria

状态的取值范围在源码中由 _STATUS_ORDER 常量固定声明:

_STATUS_ORDER = [
    "IDEA",
    "ENTRY_READY",
    "ACTIVE",
    "PARTIALLY_CLOSED",
    "CLOSED",
    "INVALIDATED",
]
_TERMINAL_STATUSES = {"CLOSED", "INVALIDATED"}  # PARTIALLY_CLOSED is non-terminal

见 thesis_store.py。两点值得注意:其一,列表顺序即"前进方向",反向迁移的判定直接用的是索引比较;其二,PARTIALLY_CLOSED 不是终态,这是它能继续减仓、也能被 close() 收尾的根本原因。

同样的枚举在 thesis.schema.json 中以 JSON Schema enum 形式重复了一次,schema 层与业务层形成双重约束。

合法迁移图与三条硬规则

规范给出的迁移路径是:

IDEA ─► ENTRY_READY ─► ACTIVE ─► PARTIALLY_CLOSED ─► CLOSED
  │          │            │            │ ▲   │
  │          │            │            │ └───┘ (further trims)
  └──────────┴────────────┴────────────┴───────────► INVALIDATED

ACTIVE → PARTIALLY_CLOSED → … → CLOSED 只能由 trim() 驱动;一次把剩余全部卖出的 trim() 直接落到 CLOSED。close() 同时接受 ACTIVE 与 PARTIALLY_CLOSED。

只能前进,不能倒退

反向迁移是被显式拒绝的,抛出 ValueError:

  • ACTIVE → IDEA — blocked
  • CLOSED → ACTIVE — blocked
  • INVALIDATED → * — blocked(终态)

transition() 的实现把这条规则拆成了四道闸门,见 lifecycle.py(实际路径为 thesis_store_parts/lifecycle.py):

thesis = _load_thesis(state_dir, thesis_id)
current = thesis["status"]

if current in _TERMINAL_STATUSES:
    raise ValueError(f"Cannot transition from terminal status {current}")

if new_status == "ACTIVE":
    raise ValueError(
        "Use open_position() to transition to ACTIVE — "
        "it requires actual_price and actual_date."
    )

if new_status == "PARTIALLY_CLOSED":
    raise ValueError(
        "Use trim() to reach PARTIALLY_CLOSED — it requires shares_sold, price, and date."
    )

if new_status in _TERMINAL_STATUSES:
    raise ValueError(
        f"Cannot transition to terminal status {new_status} via transition(). "
        "Use close() for CLOSED or terminate() for INVALIDATED."
    )

# Forward-only check (only IDEA → ENTRY_READY remains)
current_idx = _STATUS_ORDER.index(current)
if new_idx <= current_idx:
    raise ValueError(f"Cannot transition backward from {current} to {new_status}")

注意错误信息本身就是文档:它不只说"不行",还告诉你"该用哪个函数"。测试 test_thesis_store.py 中的 test_transition_backward_raises 与 test_transition_to_active_raises 正是对这两条错误文案的断言。

任意非终态都可以被否证

INVALIDATED 是唯一一个可以从任何非终态进入的状态:

  • IDEA → INVALIDATED(复核前候选失效)
  • ENTRY_READY → INVALIDATED(入场前 kill criteria 触发)
  • ACTIVE → INVALIDATED(持仓中 kill criteria 触发)

这在业务上很关键:否证一个想法不应该要求先建仓。因此 terminate(terminal_status="INVALIDATED") 的价格与日期参数都是可选的。

状态相关的操作矩阵

操作 要求状态 效果
register() — 以 IDEA 创建论点(通过 fingerprint 幂等)
transition() 任意非终态(仅允许 IDEA → ENTRY_READY) 推进状态并追加 status_history
open_position() ENTRY_READY 写入建仓数据与 shares_remaining,转为 ACTIVE(通往 ACTIVE 的唯一路径)
attach_position() IDEA / ENTRY_READY / ACTIVE 挂载仓位规模数据(设置 shares 且 shares_remaining == shares);在 PARTIALLY_CLOSED / CLOSED / INVALIDATED 上被拒(会破坏减仓台账)
trim() ACTIVE / PARTIALLY_CLOSED 卖出部分;追加台账条目、递减 shares_remaining;→ PARTIALLY_CLOSED(若剩余归零则 → CLOSED)
link_report() 任意 追加关联报告引用
close() ACTIVE / PARTIALLY_CLOSED 置为 CLOSED,计算累计 outcome.pnl_* 与 holding_days
terminate() 任意非终态 委托 close() 转 CLOSED,或携可选退出数据转 INVALIDATED
mark_reviewed() 任意非终态 按 review_date 更新复核日期与状态
rebuild_index() — 从 YAML 重建 _index.json
validate_state() — 检查文件 ⇔ 索引一致性 + schema 校验

attach_position() 的状态白名单来自 _ATTACH_ALLOWED:

# ACTIVE is safe to re-attach for equity: attach_position() only ever
# rewrites shares/shares_remaining/position_value/risk_dollars, none of
# which encode a directional sign.
_ATTACH_ALLOWED = {"IDEA", "ENTRY_READY", "ACTIVE"}

见 thesis_store.py。源码注释解释了为何 PARTIALLY_CLOSED 必须被排除:重挂载会把 shares_remaining 重置回 shares,直接违反"部分平仓"的不变量,并抹掉减仓台账的对应关系。错误信息也写明了这一点:

if thesis["status"] not in _ATTACH_ALLOWED:
    raise ValueError(
        f"attach_position() not allowed for status {thesis['status']}; "
        f"only {sorted(_ATTACH_ALLOWED)} (would corrupt shares_remaining)"
    )

四条实操建议(对应规范中的 Important 列表)

  • transition() 只允许 IDEA → ENTRY_READY;ACTIVE 和 PARTIALLY_CLOSED 一律被挡(分别改用 open_position() / trim()),所有终态同理。
  • 要到达 ACTIVE,必须用 open_position(),且它要求 actual_price 与 actual_date。
  • 要到达 PARTIALLY_CLOSED,必须用 trim(),且它要求 shares_sold、price、date。
  • 要到达 CLOSED,有三种方式:close()(从 ACTIVE 或 PARTIALLY_CLOSED)、卖掉全部剩余的 trim()、或 terminate(terminal_status="CLOSED")。
  • 要到达 INVALIDATED,用 terminate(terminal_status="INVALIDATED");提供 price+date 时计算累计盈亏,否则走"无盈亏"的旧路径。

部分平仓与累计盈亏的正确算法

这是整份规范里最容易被算错的部分,三个字段的语义必须分清楚:

  • position.shares 是原始建仓数量,不可变;
  • position.shares_remaining 是当前仍持有的数量;
  • 每次 trim() 与最后一次收尾都会向 status_history 追加一条台账记录,携带 shares_sold / price / proceeds / realized_pnl。

累计结果是:

outcome.pnl_dollars = Σ realized_pnl
outcome.pnl_pct     = pnl_dollars / (entry_price × original_shares) × 100

若从未减仓,该式与旧的单腿结果完全一致——这是向后兼容的设计。历史遗留的 ACTIVE/CLOSED 论点若缺少 shares_remaining,校验仍能通过,运行时按"全部持有"处理;但 PARTIALLY_CLOSED 永远要求同时存在 position.shares 与 position.shares_remaining。

源码如何保证"不重复记账"

trim() 自己追加台账条目,_finalize_outcome() 是最终一条腿的唯一所有者。二者的分工由一个布尔参数控制,见 positions_equity.py 的文档字符串:

"""Roll up the cumulative realized outcome for a position-backed thesis.

Single owner of the final-leg status_history ledger append. Callers:
  - close() / terminate(): append_entry=True (this appends the one final
    ledger entry for the still-open remainder).
  - trim() full close-out: append_entry=False (trim already appended the
    final ledger entry; here we only sum + finalize).
"""

trim() 中的关键计算与"归零吸附":

try:
    realized = round((price - entry_price) * shares_sold, 2)
    proceeds = round(price * shares_sold, 2)
    # Round to kill float-subtraction noise (7.86 - 4.00 == 3.86000…3),
    # then epsilon-snap a ~0 remainder to an exact 0.0 (→ full close-out).
    new_remaining = round(remaining - shares_sold, 8)
    ...
if abs(new_remaining) < 1e-9:
    new_remaining = 0.0

见 positions_equity.py。这两行 round 是为了对付浮点数:7.86 - 4.00 在二进制浮点里并不等于 3.86,如果不做 epsilon 吸附,最后一笔"卖光剩余"的 trim() 会留下 1e-16 股,于是状态永远停在 PARTIALLY_CLOSED 而无法自动收尾。测试 test_trim_fractional_precision_to_zero 用 7.86 的碎股场景专门验证了这一点。

一个可验证的多段减仓算例(来自 test_multi_trim_then_close_cumulative):建仓价 100、10 股;trim 4@120(+80)、trim 3@130(+90)、close 3@90(−30),最终 pnl_dollars == 140.0、pnl_pct == 14.0,且 status_history 中 CLOSED 条目恰好一条。

状态不变量在保存时强制校验

_validate_thesis() 按状态逐条检查,任何一条不满足都会在写盘前抛错,见 validation.py:

  • ACTIVE:必须有 entry.actual_price 与 entry.actual_date;若 shares_remaining 存在则必须等于 shares(对旧数据宽容,缺失时不报错)。
  • PARTIALLY_CLOSED:必须有 entry 数据、必须有 position,且 0 < shares_remaining < shares;这条没有历史宽容,因为它是 PR-80B 之后才出现的状态。
  • CLOSED:必须有 exit.actual_price、exit.actual_date,exit_reason 必须属于 {stop_hit, target_hit, time_stop, invalidated, manual},退出日期不得早于建仓日期,且 shares_remaining == 0。
  • INVALIDATED:若存在 exit_reason 则必须恰为 invalidated(用户填写的具体原因写进 status_history.reason,而不是枚举字段)。

对应的负向测试 test_partially_closed_requires_shares_remaining 与正向测试 test_closed_shares_remaining_zero_passes_schema 分别守住了这两侧边界。

CLI 全流程:不写 Python 也能走完生命周期

每一个生命周期操作都是 thesis_store.py 的子命令:transition、open-position、attach-position、close、terminate,与 list / get / review-due / rebuild-index / doctor / mark-reviewed 并列。推荐通过 stdlib-only 启动器调用,它会自动经 uv run --project <repo> 路由,从而在任意 cwd(cron、profile 运行)下都能拿到仓库固定版本的 jsonschema:

# 仓库内
python3 skills/trader-memory-core/scripts/trader_memory_cli.py store --state-dir state/theses list

# 仓库外
export CLAUDE_TRADING_SKILLS_REPO=/path/to/claude-trading-skills
python3 "$CLAUDE_TRADING_SKILLS_REPO/skills/trader-memory-core/scripts/trader_memory_cli.py" \
  store --state-dir /path/to/state/theses list

子命令路由为 store → thesis_store.py、ingest → thesis_ingest.py、review → thesis_review.py,后续参数原样透传,因此既有 flag 无需改动。

完整示例:从入库到平仓

SD=state/theses
CLI=skills/trader-memory-core/scripts/trader_memory_cli.py

# 1) IDEA:从 screener 输出注册
python3 $CLI ingest --source kanchi-dividend-sop \
  --input reports/kanchi_entry_signals_2026-03-14.json --state-dir $SD

# 2) IDEA → ENTRY_READY(唯一允许的 transition)
python3 $CLI store --state-dir $SD transition th_aapl_div_20260314_a3f1 ENTRY_READY \
  --reason "validated"

# 3) ENTRY_READY → ACTIVE(唯一路径),并记录碎股数量
python3 $CLI store --state-dir $SD open-position th_aapl_div_20260314_a3f1 \
  --actual-price 142.10 --actual-date 2026-05-02 --shares 7.86

# 4) 部分平仓 → PARTIALLY_CLOSED
python3 $CLI store --state-dir $SD trim th_aapl_div_20260314_a3f1 \
  --shares-sold 4 --price 120.00 --date 2026-05-10

# 5) 收尾 → CLOSED,累计盈亏
python3 $CLI store --state-dir $SD close th_aapl_div_20260314_a3f1 \
  --exit-reason target_hit --actual-price 165.00 --actual-date 2026-06-01

若论点在入场前就被否证,用 terminate 而不需要任何价格:

python3 $CLI store --state-dir $SD terminate th_aapl_div_20260314_a3f1 \
  --terminal-status INVALIDATED --exit-reason "thesis broke"

回溯已有持仓:--event-date 的正确用法

transition、open-position、close、terminate 都接受 --event-date(写入该次迁移的 status_history.at)。open-position 另有 --actual-date(→ entry.actual_date);close/terminate 的 --actual-date 指向 exit.actual_date。纯 YYYY-MM-DD 会被扩展为 UTC 午夜,完整 ISO 时间戳则原样透传——这由 _coerce_dt() 完成:

def _coerce_dt(value: str | None) -> str | None:
    if value is None:
        return None
    if "T" in value:
        return value
    return f"{value}T00:00:00+00:00"

见 persistence.py。注释里点明了原因:status_history.at 与 entry.actual_date 在 schema 中是 date-time,_check_datetime 要求必须有 T 分隔符与时区偏移。

transition --event-date 的存在理由很具体:一笔已经成交的券商持仓通过 manual adapter 录入时,manual adapter 会把 IDEA 的时间戳回溯到 entry_date;此时必须让 transition --event-date <entry_date> 与 open-position --event-date <entry_date> 保持同一天。若省略 transition --event-date,ENTRY_READY 会盖上"当前时间",而回溯的 open-position --event-date 把 ACTIVE 放到过去,于是 ACTIVE 早于 ENTRY_READY,保存时直接踩中 status_history 单调性检查而失败。

这条单调性检查在 _validate_thesis() 末尾:

history = thesis.get("status_history", [])
for i in range(1, len(history)):
    prev_at = history[i - 1].get("at", "")
    curr_at = history[i].get("at", "")
    if prev_at and curr_at and _parse_dt(curr_at) < _parse_dt(prev_at):
        raise ValueError(...)
if history and history[-1]["status"] != thesis["status"]:
    raise ValueError(...)

见 validation.py。注意它还额外要求"历史最后一条的状态必须等于当前 status",这条断言能挡住手改 YAML 导致的状态漂移。

完整的三步回溯序列:

# 1) ingest → IDEA(时间戳落在 entry_date)
python3 $CLI ingest --source manual --input amd.json --state-dir $SD
# 2) IDEA → ENTRY_READY(回溯)
python3 $CLI store --state-dir $SD transition <id> ENTRY_READY \
  --reason "existing IBI Smart position" --event-date 2026-05-02
# 3) ENTRY_READY → ACTIVE(碎股,回溯)
python3 $CLI store --state-dir $SD open-position <id> \
  --actual-price 142.10 --actual-date 2026-05-02 --shares 7.86 --event-date 2026-05-02

端到端测试 test_manual_backdated_lifecycle_monotonic_e2e 断言最终三条历史的时间戳全是 2026-05-02T00:00:00+00:00。与之配套的负向控制组 test_backdate_monotonicity_negative_control 则证明了省略 --event-date 时会以 is before 报错——这正是该 flag 存在的证据。

监控循环:复核日期如何滚动

规范的监控循环是四步:

  1. register() 时:next_review_date = created_at + review_interval_days
  2. 复核时:更新 last_review_date,推进 next_review_date
  3. list_review_due(as_of) 返回 next_review_date <= as_of 的论点
  4. 复核状态沿 OK → WARN → REVIEW 的升级阶梯变化

register() 在源码中还有一个容易忽略的细节:复核基准用的是 _source_date(报告自身的 as_of)而非墙钟时间,这样批量回放历史报告时日期才是正确的:

# Set next_review_date based on source date (not wall-clock)
interval = thesis["monitoring"].get("review_interval_days", 30)
base_dt = datetime.fromisoformat(source_base)
next_review = (base_dt + timedelta(days=interval)).strftime("%Y-%m-%d")
thesis["monitoring"]["next_review_date"] = next_review

见 lifecycle.py。review_interval_days 默认 30,schema 限定最小为 1。

mark_reviewed() 同时承担"推进日期"与"记录告警"两件事,并对终态论点直接拒绝:

valid_outcomes = {"OK", "WARN", "REVIEW"}
if outcome not in valid_outcomes:
    raise ValueError(f"outcome must be one of {valid_outcomes}, got {outcome}")

thesis = _load_thesis(state_dir, thesis_id)

if thesis["status"] in _TERMINAL_STATUSES:
    raise ValueError(f"Cannot review terminal thesis ({thesis['status']})")

interval = thesis["monitoring"].get("review_interval_days", 30)
review_dt = datetime.fromisoformat(f"{review_date}T00:00:00+00:00")
next_review = (review_dt + timedelta(days=interval)).strftime("%Y-%m-%d")

见 lifecycle.py。注意 notes 会被格式化成 [{review_date}] {outcome}: {notes} 追加进 monitoring.alerts,形成可追溯的复核流水。

查询侧 list_review_due() 会主动跳过终态,并把无法解析的 next_review_date 降级为 warning 而不是崩溃:

for tid, entry in index.get("theses", {}).items():
    if entry.get("status") in _TERMINAL_STATUSES:
        continue
    nrd = entry.get("next_review_date")
    if nrd:
        try:
            if date.fromisoformat(nrd) <= as_of_date:
                results.append({"thesis_id": tid, **entry})
        except ValueError:
            logger.warning("Skipping unparsable next_review_date for %s: %s", tid, nrd)

见 queries.py。

CLI 对应命令:

python3 $CLI store --state-dir $SD review-due --as-of 2026-04-15
python3 $CLI store --state-dir $SD mark-reviewed <id> \
  --review-date 2026-04-15 --outcome WARN --notes "yield compression continued"

只做多股票与"初始风险位"校验

规范最后一块内容约束的是资产类别边界,很容易被忽略但踩坑代价很高。

股票口径只支持多头。 不要把抛物线做空方案灌进来,也不要用 manual 记录做空股票——没有对应 adapter。显式的 SHORT 方向会在原始注册、manual 摄入、股票开仓、shares 报告挂载四个入口被拒绝。通用 register() 不导入任何原始仓位:期货的 LONG/SHORT 请走已验证的期货挂载或 open-position --contracts。

初始价格对必须合法。 当 entry 与 stop 同时给出时,两者都必须是有限的数值(非 bool)。若二者均为正,而初始止损高于入场价,则在 manual 摄入、shares 报告挂载、股票激活(以实际成交价判定)三处都会被拒绝。缺失的可选价格对、以及既有的有限非正价格行为保持兼容。

这条规则不适用于已持仓多头的移动止损。 一个浮盈的多头完全可以把止损抬到原始入场价之上——把初始建仓规则套用到 ACTIVE/PARTIALLY_CLOSED 上会误伤正常的风险管理。源码通过函数命名与文档字符串把语义钉死:

def _validate_equity_initial_stop(entry: Any, stop: Any) -> None:
    """Check a supplied initial pair, not an ACTIVE long's trailing stop."""
    if entry is None or stop is None:
        return
    valid_entry = _valid_finite_number(entry)
    valid_stop = _valid_finite_number(stop)
    if valid_entry is None or valid_stop is None:
        raise ValueError(
            "Equity accounting is long-only; initial entry/stop must be finite numbers"
        )
    # Preserve #257's finite nonpositive-price compatibility. A positive
    # initial stop above a positive fill describes unsupported short geometry.
    if valid_entry > 0 and valid_stop > valid_entry:
        raise ValueError("Equity accounting is long-only; an initial stop cannot exceed entry")

见 validation.py。对应的测试 test_active_long_profit_stop_and_partial_exit_remain_valid 在 test_equity_long_only.py 中确认了浮盈多头抬高止损 + 部分止盈依旧合法。

规范还给出了一个实操建议:回溯时若需要保护利润的止损,应先用初始止损把多头开出来,等激活之后再更新当前止损。这正好绕开了"初始对"校验,同时保留了时间线单调性。

历史做空记录的降级处理。 显式的历史空头(出现 SHORT 词或裸 SELL,如 SELL_SHORT、Short position、SELL;Sell to close 这类标签仍视为多头)会在任何新记账或 MAE/MFE 计算前被拒绝。CLOSED/INVALIDATED 的历史空头可以生成"仅历史"复盘:P&L、MAE/MFE、仓位估值与风险一律显示为不可用(—),并附明确的不支持说明。该报告不抓取价格,也不改动论点/索引状态、已存 outcome 与溯源;旧值不会被校验或更正。ACTIVE/PARTIALLY_CLOSED 的记录仍不能生成复盘,但可以 mark_reviewed 或以无退出价 INVALIDATED 收尾——这类记账动作保留全部既有金额字段与溯源。汇总统计与月度报告会跳过显式空头并在 JSON 中给出计数(非零时为 excluded_unsupported_equity_shorts)。

分类逻辑集中在 _is_short_label(),它用正则抽取大写词再做集合判断:

_SHORT_WORDS = frozenset({"SHORT", "SHORTED", "SHORTING", "SELLSHORT"})

def _is_short_label(value: str) -> bool:
    words = re.findall(r"[A-Z]+", value.upper())
    return words == ["SELL"] or not _SHORT_WORDS.isdisjoint(words)

见 validation.py。words == ["SELL"] 要求"裸 SELL"是整条标签,因此 Sell to close 里虽然含 SELL 但 words 是 ["SELL","TO","CLOSE"],不会被误判为做空意图。规范末尾那句"模糊的历史记录无法仅凭 trailing stop 归类"正是这个设计的自白:不要试图从止损位置反推方向,把空头日志留在系统之外。

运维与自检:doctor、rebuild-index 与原子写

状态目录不是黑盒。三个命令覆盖日常维护:

# 一致性诊断:文件 ⇔ 索引 + schema + 字段比对
python3 $CLI store --state-dir $SD doctor

# 从 th_*.yaml 重建索引
python3 $CLI store --state-dir $SD rebuild-index

validate_state() 返回结构化的四类问题——missing_in_index、orphaned_in_index、field_mismatches、schema_errors——见 queries.py。rebuild_index() 则对每个 YAML 先校验再收录,非法文件跳过并记 warning,因此它同时是一次全量体检:

for yaml_path in sorted(state_dir.glob("th_*.yaml")):
    try:
        thesis = yaml.safe_load(yaml_path.read_text())
        if thesis and "thesis_id" in thesis:
            _validate_thesis(thesis)
            _update_index_entry(index, thesis)
    except Exception as e:
        logger.warning("Skipping invalid file %s: %s", yaml_path.name, e)
        continue

所有落盘都走 tempfile + os.replace,这是"要么旧内容、要么新内容"的保证,也是为什么 _save_thesis() 必须在写之前完成校验:

def _save_thesis(state_dir: Path, thesis: dict, *, allow_legacy_short: bool = False) -> None:
    """Validate and save a thesis YAML file atomically."""
    _validate_thesis(thesis, allow_legacy_short=allow_legacy_short)
    path = state_dir / f"{thesis['thesis_id']}.yaml"
    _atomic_write_yaml(path, thesis)

见 persistence.py。校验抛错时磁盘文件字节不变,这条契约让所有业务函数可以放心地"先改内存、最后统一保存"。

排错速查:错误信息对应的不变量

报错片段 含义 修正方式
Cannot transition backward from ACTIVE to IDEA 反向迁移 无需回退;新建论点或改用正确的前进操作
Use open_position() to transition to ACTIVE 用 transition() 直奔 ACTIVE 改用 open-position 并提供 --actual-price/--actual-date
Use trim() to reach PARTIALLY_CLOSED 试图直接跳入部分平仓 改用 trim --shares-sold --price --date
Cannot transition from terminal status CLOSED 对终态再操作 终态不可复活,重新建论点
attach_position() not allowed for status PARTIALLY_CLOSED 在减仓后台重挂规模 只在 IDEA/ENTRY_READY/ACTIVE 挂载
shares_sold (...) must be > 0 and <= shares_remaining 减仓数量越界 检查 shares_remaining 后再卖
trim requires a recorded position 没有股数就减仓 先 open-position --shares
status_history[1].at (...) is before ... 回溯造成时间倒流 给 transition 也补 --event-date
Equity accounting is long-only; an initial stop cannot exceed entry 初始止损高于入场 先按初始止损开仓,激活后再上调止损
Cannot review terminal thesis 对已结束论点做复核 复核仅适用于非终态

小结

thesis_lifecycle.md 定义的不是一份流程图,而是一组能在源码里逐条找到对应实现的强制约束:_STATUS_ORDER 固定前进方向,_ATTACH_ALLOWED 保护减仓台账,_finalize_outcome() 独占最终腿记账,_validate_thesis() 在每次写盘前复核状态不变量与时间单调性。把这些约束与 CLI 的 --event-date/--actual-date 配合使用,你就能让一笔真实券商持仓的完整历史——哪怕是回溯录入的碎股仓位——在 status_history 里保持严格时序,并让 outcome.pnl_pct 始终以原始建仓名义金额为分母,从而在跨多笔减仓的复杂退出中依然得到可比较的收益率。

若想继续深入,可对照阅读 field_mapping.md(各 screener 输出到规范字段的映射)、thesis.schema.json(全部字段与枚举约束)、以及 SKILL.md 中的期货分支说明(quantity/multiplier/direction 与按 position.asset_type 自动分派的四个操作)。

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