Quant Buffet API

沙箱规则

允许的 import、你实际拿到的 builtins、被禁的调用与硬性运行上限。

实验室运行会在 `backtest/sandbox_runner.py` 中执行你的代码:源码先用 `ast` 解析,由 lab_sanitize 剥离引导片段,然后在受限命名空间中 exec。理解这些限制,就能解释绝大多数令人困惑的失败。

允许的 import 根模块

类别根模块
Quant Buffetbacktest(data、engine、metrics、templates、universes、lab_sanitize)
数值计算numpynppandaspd
标准库mathjsontypingcollectionsdataclassesfunctoolsitertoolsdatetimerestatisticsdecimal
语言特性__future__

校验针对根模块,因此 from backtest.templates import make_sma_trendimport collections.abc 都能通过。其他任何模块都会在校验阶段失败并报 *Import blocked: …*。

被禁止的内容

  • 白名单之外的标准库模块:ossyspathlibsubprocesssocketpicklerandomtime 等。
  • 所有第三方包:requestssklearnscipymatplotlibyfinancestatsmodels 等。
  • 直接调用 evalexeccompileopen__import__inputbreakpoint —— 由 AST 遍历直接拒绝。
  • async / await / async for / async with —— *Async code is not supported in the sandbox.*
  • 源码超过 80 KB —— *Code too long (max 80KB).*

你可以使用的 builtins

分组可用
数值absminmaxsumroundfloatintbool
序列lenrangeenumeratezipmapfiltersorted
容器listdictsettuplestr
自省isinstanceissubclasshasattrtypeprint
异常ExceptionValueErrorTypeErrorKeyErrorRuntimeErrorStopIteration

你拿不到的 builtins

缺失改用
any(...)all(...)series.any()series.all(),或 sum(1 for … ) > 0
reversed(...)sorted(x, reverse=True)x[::-1]
getattrsetattrvarsglobalslocals重构代码 —— 这里不需要属性反射
nextiterfrozensetdivmodpow推导式、set//%**
IndexErrorAttributeErrorZeroDivisionError捕获 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 sysfrom pathlib …ROOT = …,以及任何涉及 sys.path 的行;
  • 文件开头的模块 docstring 与 from __future__ 行;
  • 生成器元数据赋值,如 SLUGLOCALETITLETEMPLATEFIDELITYDATA_SOURCE