Quant Buffet API
沙箱规则
允许的 import、你实际拿到的 builtins、被禁的调用与硬性运行上限。
实验室运行会在 `backtest/sandbox_runner.py` 中执行你的代码:源码先用 `ast` 解析,由 lab_sanitize 剥离引导片段,然后在受限命名空间中 exec。理解这些限制,就能解释绝大多数令人困惑的失败。
允许的 import 根模块
| 类别 | 根模块 |
|---|---|
| Quant Buffet | backtest(data、engine、metrics、templates、universes、lab_sanitize) |
| 数值计算 | numpy、np、pandas、pd |
| 标准库 | math、json、typing、collections、dataclasses、functools、itertools、datetime、re、statistics、decimal |
| 语言特性 | __future__ |
校验针对根模块,因此 from backtest.templates import make_sma_trend 与 import collections.abc 都能通过。其他任何模块都会在校验阶段失败并报 *Import blocked: …*。
被禁止的内容
- 白名单之外的标准库模块:
os、sys、pathlib、subprocess、socket、pickle、random、time等。 - 所有第三方包:
requests、sklearn、scipy、matplotlib、yfinance、statsmodels等。 - 直接调用
eval、exec、compile、open、__import__、input、breakpoint—— 由 AST 遍历直接拒绝。 async/await/async for/async with—— *Async code is not supported in the sandbox.*- 源码超过 80 KB —— *Code too long (max 80KB).*
你可以使用的 builtins
| 分组 | 可用 |
|---|---|
| 数值 | abs、min、max、sum、round、float、int、bool |
| 序列 | len、range、enumerate、zip、map、filter、sorted |
| 容器 | list、dict、set、tuple、str |
| 自省 | isinstance、issubclass、hasattr、type、print |
| 异常 | Exception、ValueError、TypeError、KeyError、RuntimeError、StopIteration |
你拿不到的 builtins
| 缺失 | 改用 |
|---|---|
any(...)、all(...) | series.any()、series.all(),或 sum(1 for … ) > 0 |
reversed(...) | sorted(x, reverse=True) 或 x[::-1] |
getattr、setattr、vars、globals、locals | 重构代码 —— 这里不需要属性反射 |
next、iter、frozenset、divmod、pow | 推导式、set、// 与 %、** |
IndexError、AttributeError、ZeroDivisionError | 捕获 Exception,或改为提前判断条件 |
运行上限
| 上限 | 取值 | 超限时的错误 |
|---|---|---|
| 源码体积 | 80 KB | *Code too long (max 80KB).* |
ASSETS 标的数 | 15 | *Too many symbols (max 15).* |
| 最少价格行数 | 加载后 30 行 | *Not enough price history for the selected assets/start date.* |
| 最少净值点数 | 运行后 20 个 | *Equity curve too short — strategy may never trade.* |
| 净值图点数 | 90(降采样) | 无 —— 指标仍由完整曲线计算 |
| 默认起始日 | 2000-01-01 | 无 |
源码净化
backtest/lab_sanitize.py 在校验之前运行,会移除目录生成文件所携带的脚手架,使同一文件既能作为 CLI 脚本运行,也能作为实验室输入。它会剥离:
- 从
def main(开始的所有内容,包括__main__守卫; import sys、from pathlib …、ROOT = …,以及任何涉及sys.path的行;- 文件开头的模块 docstring 与
from __future__行; - 生成器元数据赋值,如
SLUG、LOCALE、TITLE、TEMPLATE、FIDELITY、DATA_SOURCE。