Quant Buffet API
实验室运行 API
浏览器 IDE、HTTP 路由与 Python 运行器之间的 JSON 契约。
每个策略页上的 IDE 都会调用一个 Next.js 路由,后者启动 backtest/sandbox_runner.py,并通过 stdin / stdout 交换一个 JSON 对象。了解该契约有助于调试,也便于直接脚本化调用运行器。
HTTP 端点
| 路由 | 用途 | 访问权限 |
|---|---|---|
POST /api/strategy-lab/backtest | 运行已发布策略的编辑后代码 | 需登录,并受该策略付费墙约束 |
POST /api/strategy-lab/fix-code | 请求 AI 调试器给出修复 | 同上 |
POST /api/draft-preview/backtest | 运行内部草稿实验室的代码 | 管理员 / 草稿权限 |
bash
POST /api/strategy-lab/backtest
Content-Type: application/json
{
"slug": "dual-momentum-global-equity",
"locale": "en",
"code": "ASSETS = ['SPY', 'BIL']\n...",
"start": "2000-01-01"
}每次成功运行都会计入你的账户用量,并显示在 账户 → 回测使用记录 中,其中包含模拟成交笔数。
bash
POST /api/strategy-lab/fix-code
Content-Type: application/json
{
"slug": "dual-momentum-global-equity",
"locale": "en",
"code": "<your edited source>",
"error": {
"type": "NameError",
"message": "name 'ASSETS' is not defined",
"line": 12
}
}运行器请求(stdin)
json
{
"code": "ASSETS = ['SPY', 'BIL']\n\ndef make_on_day(prices):\n ...",
"start": "2000-01-01",
"max_points": 90
}| 字段 | 类型 | 默认值 | 含义 |
|---|---|---|---|
code | str | "" | 完整 Python 源码,校验前会先净化。 |
start | str | "2000-01-01" | 传递给 load_daily_prices。 |
max_points | int | 90 | equity 与 benchmark 的图表分辨率。 |
成功响应
json
{
"ok": true,
"assets": ["SPY", "BIL"],
"start": "2000-10-16",
"end": "2026-09-05",
"trades": 148,
"trades_sample": [
{
"date": "2000-10-16",
"symbol": "SPY",
"side": "buy",
"shares": 712.345678,
"price": 140.281234,
"value": 99950.0,
"commission": 49.975
}
],
"trades_sample_note": "Showing first 10 and last 20 of 148 fills",
"metrics": { "cagr": 0.0784, "sharpe": 0.71, "max_drawdown": -0.1932 },
"displayMetrics": {
"annualisedReturn": "7.84%",
"volatility": "10.42%",
"sharpeRatio": "0.71",
"sortinoRatio": "1.03",
"maxDrawdown": "-19.32%",
"beta": "0.48",
"alpha": "1.90%",
"winRate": "54.10%"
},
"equity": [{ "date": "2000-10-16", "equity": 100000.0 }],
"benchmark": [{ "date": "2000-10-16", "equity": 100000.0 }]
}| 字段 | 说明 |
|---|---|
assets | 经白名单校验与去重后的标的列表。 |
start、end | 净值曲线实际的首末日期。 |
trades | 整次运行的成交总笔数。 |
trades_sample | 不超过 36 笔时返回全部,否则返回前 10 笔与后 20 笔。 |
trades_sample_note | 说明字符串;样本完整时为 null。 |
metrics | compute_metrics 的原始字典。 |
displayMetrics | 供界面卡片使用的预格式化字符串。 |
equity、benchmark | 供图表使用的降采样 {date, equity} 数组。 |
错误响应
json
{
"ok": false,
"error": {
"type": "SyntaxError",
"message": "Syntax error at line 14: invalid syntax",
"line": 14,
"column": 22,
"traceback": "Traceback (most recent call last): ..."
}
}| 字段 | 备注 |
|---|---|
type | Python 异常类名,或 ContractError / BadPayload。 |
message | 可读文本,在 IDE 中原样展示。 |
line | 你的源码行号,由 <strategy> 栈帧解析得出,可能为 null。 |
column | 仅 SyntaxError 会提供。 |
traceback | 格式化 traceback 的最后 2,500 个字符。 |
行号的获取方式是倒序遍历 traceback,取文件名为 <strategy> 的最后一个栈帧。这意味着报告的行号是你代码内部最深处的位置,而不是 pandas 内部 —— 而它几乎总是你真正需要修改的那一行。
在本地驱动运行器
bash
# 在仓库根目录执行
python -c "import json,sys; print(json.dumps({'code': open('my_strategy.py').read(), 'start': '2005-01-01'}))" \
| python -m backtest.sandbox_runner