Quant Buffet API

沙箱规则

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

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

允许的 import 根模块

类别根模块
Quant Buffetbacktest(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。