回测运行详情

📎 引用文件

本文引用的文件 - agent/src/api/runs_routes.py - agent/src/api/models.py - agent/src/api/helpers.py - agent/src/api/security.py - agent/api_server.py - frontend/src/pages/RunDetail.tsx - frontend/src/lib/api.ts

目录

  1. 简介
  2. 项目结构
  3. 核心组件
  4. 架构总览
  5. 详细组件分析
  6. 依赖关系分析
  7. 性能考虑
  8. 故障排查指南
  9. 结论
  10. 附录

简介

本文件为 Vibe-Trading 的“回测运行详情”API 提供完整技术文档,聚焦 GET /runs/{run_id} 端点。内容涵盖: - 路径参数 run_id 的安全校验规则 - 可选查询参数 chart_symbol、chart_payload 的作用与约束 - RunResponse 数据模型的复杂结构与字段含义 - 图表数据的按需加载机制与 CSV 读取限制 - 内存使用控制策略 - 请求与响应示例(含不同 chart_payload 模式差异)

该端点用于根据 run_id 获取一次历史回测运行的详细信息,包括状态、指标、产物清单、图表数据、风险评估等。

项目结构

GET /runs/{run_id} 由 API 服务器挂载 runs 路由模块实现,核心流程如下: - FastAPI 应用启动时注册 runs 路由 - 路由层对 run_id 进行安全校验并定位运行目录 - 构建响应对象,按需加载 JSON/CSV 产物与图表数据 - 通过 Pydantic 模型序列化返回

graph TB Client["客户端"] --> API["FastAPI 应用<br/>api_server.py"] API --> Routes["Runs 路由<br/>runs_routes.py"] Routes --> Helpers["路径与安全校验<br/>helpers.py / security.py"] Routes --> Builder["响应构建器<br/>_build_response_from_run_dir()"] Builder --> FS["文件系统<br/>state.json, artifacts/*, *.json"] Builder --> UI["UI 服务<br/>build_run_analysis()"] Routes --> Models["Pydantic 模型<br/>models.py"] Models --> Client

图示来源 - agent/api_server.py:163-189 - agent/src/api/runs_routes.py:226-343 - agent/src/api/helpers.py:263-270 - agent/src/api/security.py:571-588

章节来源 - agent/api_server.py:163-189 - agent/src/api/runs_routes.py:226-343

核心组件

章节来源 - agent/src/api/runs_routes.py:23-216 - agent/src/api/models.py:10-97 - agent/src/api/helpers.py:263-270 - agent/src/api/security.py:571-588 - frontend/src/pages/RunDetail.tsx:150-170

架构总览

下图展示从请求到响应的关键交互:

sequenceDiagram participant C as "客户端" participant A as "FastAPI 应用" participant R as "runs_routes.get_run_result" participant S as "安全校验(require_auth)" participant H as "路径校验(_validate_path_param)" participant B as "响应构建(_build_response_from_run_dir)" participant U as "UI 服务(build_run_analysis)" participant M as "Pydantic 模型序列化" C->>A : GET /runs/{run_id}?chart_symbol=&chart_payload= A->>S : 验证认证(Header/Bearer/本地回环) S-->>A : 通过/拒绝 A->>R : 进入路由处理 R->>H : 校验 run_id 格式 H-->>R : 通过/拒绝 R->>B : 构建响应(读取 state.json/artifacts/*.csv/*.json) alt 需要图表元数据 R->>U : build_run_analysis(include_analysis=true) U-->>R : price_series/indicator_series/trade_markers/chart_symbols end R->>M : 序列化为 RunResponse M-->>C : JSON 响应

图示来源 - agent/src/api/runs_routes.py:302-343 - agent/src/api/security.py:571-588 - agent/src/api/helpers.py:263-270

详细组件分析

端点定义与参数

章节来源 - agent/src/api/runs_routes.py:302-319 - agent/src/api/helpers.py:263-270 - agent/src/api/security.py:571-588

响应构建逻辑

_build_response_from_run_dir 负责从运行目录拼装响应: - 基础信息 - status:来自 state.json 的状态映射(success/failed/cancelled/unknown) - run_id:目录名 - elapsed_seconds:当前固定为 0.0(占位) - reason:失败原因(如有) - 策略与规划 - strategy_spec:design_spec.json - planner_output:planner_output.json - RAG 选择 - rag_selection:selected_api、selected_name、selected_score - 回测指标 - metrics:解析 artifacts/metrics.csv 首行,构造 BacktestMetrics(允许额外字段) - 产物清单 - artifacts:artifacts 目录下所有文件的元信息(name/path/type/size/exists) - 原始 CSV - artifacts_equity_csv、artifacts_metrics_csv、artifacts_trades_csv:分别读取 equity/metrics/trades 全量 CSV - 其他 - run_card、risk_xray、rebalance_notes、llm_usage、validation:从对应 JSON 文件加载 - 图表预览 - equity_curve:equity.csv 前 1000 行的精简列(time/equity/drawdown) - trade_log:trades.csv 前 500 行 - 图表数据(按需) - include_analysis=true 时调用 build_run_analysis,产出 price_series、indicator_series、trade_markers、run_logs,并在需要时收集 chart_symbols

章节来源 - agent/src/api/runs_routes.py:52-216

数据模型 RunResponse

RunResponse 是本次 API 的核心响应模型,包含以下分组字段: - 基础信息 - status、run_id、elapsed_seconds、reason、run_directory - 策略与规划 - strategy_spec、planner_output - RAG 选择 - rag_selection:selected_api、selected_name、selected_score - 回测指标 - metrics:final_value、total_return、annual_return、max_drawdown、sharpe、win_rate、trade_count,以及允许的其他数值字段 - 产物清单 - artifacts:name、path、type、size、exists - 图表与日志 - equity_curve、trade_log、price_series、indicator_series、trade_markers、run_logs - 其他 - run_card、risk_xray、rebalance_notes、llm_usage、validation、run_stage、run_context

classDiagram class RunResponse { +string status +string run_id +float elapsed_seconds +string reason +string run_directory +dict planner_output +dict strategy_spec +RAGSelection rag_selection +BacktestMetrics metrics +Artifact[] artifacts +dict run_card +dict llm_usage +dict[] equity_curve +dict[] trade_log +dict[] artifacts_equity_csv +dict[] artifacts_metrics_csv +dict[] artifacts_trades_csv +dict validation +dict risk_xray +dict rebalance_notes +string run_stage +dict run_context +dict price_series +dict indicator_series +dict[] trade_markers +dict[] run_logs } class Artifact { +string name +string path +string type +int size +bool exists } class BacktestMetrics { +float final_value +float total_return +float annual_return +float max_drawdown +float sharpe +float win_rate +int trade_count } class RAGSelection { +string selected_api +string selected_name +float selected_score } RunResponse --> Artifact : "包含" RunResponse --> BacktestMetrics : "包含" RunResponse --> RAGSelection : "包含"

图示来源 - agent/src/api/models.py:10-97

章节来源 - agent/src/api/models.py:10-97

图表数据按需加载与差异

flowchart TD Start(["请求进入"]) --> CheckParams{"是否传入 chart_symbol 或 chart_payload?"} CheckParams --> |否| BaseOnly["仅返回基础信息与通用预览<br/>equity_curve, trade_log"] CheckParams --> |是| BuildAnalysis["调用 build_run_analysis<br/>include_analysis=true"] BuildAnalysis --> Mode{"chart_payload == 'summary' ?"} Mode --> |是| Summary["省略图表行与交易标记<br/>返回 chart_symbols"] Mode --> |否| Full["返回完整图表数据<br/>price_series, indicator_series, trade_markers"] BaseOnly --> End(["响应"]) Summary --> End Full --> End

图示来源 - agent/src/api/runs_routes.py:302-343 - agent/src/api/runs_routes.py:198-216

章节来源 - agent/src/api/runs_routes.py:302-343

前端集成与调用策略

章节来源 - frontend/src/pages/RunDetail.tsx:150-170 - frontend/src/pages/RunDetail.tsx:205-235 - frontend/src/lib/api.ts:594-617

依赖关系分析

graph LR RunsRoutes["runs_routes.py"] --> Security["security.py<br/>require_auth"] RunsRoutes --> Helpers["helpers.py<br/>_validate_path_param"] RunsRoutes --> UI["ui_services.build_run_analysis"] RunsRoutes --> Models["models.py<br/>RunResponse/BacktestMetrics/RAGSelection/Artifact"] RunsRoutes --> FS["文件系统<br/>state.json, artifacts/*"]

图示来源 - agent/src/api/runs_routes.py:226-343 - agent/src/api/security.py:571-588 - agent/src/api/helpers.py:263-270 - agent/src/api/models.py:10-97

章节来源 - agent/src/api/runs_routes.py:226-343

性能考虑

章节来源 - agent/src/api/runs_routes.py:142-196 - agent/src/api/runs_routes.py:198-216 - frontend/src/pages/RunDetail.tsx:150-170

故障排查指南

章节来源 - agent/src/api/runs_routes.py:316-325 - agent/src/api/runs_routes.py:317-319 - agent/src/api/helpers.py:263-270 - agent/src/api/security.py:571-588

结论

GET /runs/{run_id} 提供了完整的回测运行详情能力,并通过可选参数实现图表数据的按需加载与体积控制。配合严格的路径参数校验与认证机制,既保证了安全性,又兼顾了性能与用户体验。建议在生产环境中: - 始终启用认证(Bearer Token) - 合理设置 chart_payload=summary 作为默认,按需切换到 full - 关注 CSV 文件大小,必要时在数据源侧做采样或分页

附录

请求示例

响应示例(摘要)

章节来源 - agent/src/api/models.py:56-97 - agent/src/api/runs_routes.py:72-216 - agent/src/api/runs_routes.py:327-343