writing-skills
OBobra/superpowers298k2,631 new stars in the last 7 days
AI-IDE 写策略与执行 — 用 AI 生成 Qlib 量化策略代码、Docker 容器执行策略/回测、自然语言条件选股、策略落库。在 QuantBot / Claude Code 中让 AI 写策略、生成 Qlib 策略、执行策略回测、云端保存策略时使用。触发词:AI写策略、写策略、生成策略、策略代码、AI-IDE、运行策略、执行策略、帮我写个策略、云端策略
⚙️ 本技能遵循公共运行环境契约(最高优先级,先于本文其余内容执行): 详见 _shared/env-contract.md,执行前先读它。
AI-IDE 用 AI 生成 Qlib 量化策略代码,并在 Docker 容器中隔离执行(策略运行 / 回测)。核心入口是 /api/v1/ai-ide/execute/*。
BASE=http://127.0.0.1:8000
TOKEN=$(curl -s -X POST $BASE/api/v1/auth/login -H "Content-Type: application/json" \
-d '{"username":"admin","password":"admin123","tenant_id":"default"}' \
| python3 -c "import sys,json; print(json.load(sys.stdin).get('access_token',''))")
AUTH="Authorization: Bearer $TOKEN"
CT="Content-Type: application/json"
AI-IDE / QuantAgent / QuantBot 的 LLM 通道统一走「个人中心 → AI 服务」配置(持久化在 user_profiles):
# 读取当前配置(api_key 已脱敏)
curl -s -H "$AUTH" "$BASE/api/v1/ai-ide/config/llm"
# 保存配置(自定义网关/模型:可带自定义请求头)
curl -s -X POST -H "$AUTH" -H "$CT" "$BASE/api/v1/ai-ide/config/llm" -d '{
"provider": "custom",
"model": "your-model",
"base_url": "https://your-gateway.example.com",
"qwen_api_key": "sk-...",
"extra_headers": "{\"x-opencode-session\": \"<session-id>\"}"
}'
# 测试连通(字段同上)
curl -s -X POST -H "$AUTH" -H "$CT" "$BASE/api/v1/ai-ide/config/llm/test" -d '{ ... }'
extra_headers:自定义请求头(JSON 字符串),存 user_profiles.llm_extra_headers,会注入到全部 LLM 调用
(AI-IDE/QuantAgent、QuantBot、策略 Lab、ai_strategy 等)。None=不改动,空串=清除,有值=覆盖。base_url:只填到域名即可,客户端会自动补 /v1/chat/completions(例:https://api.deepseek.com → https://api.deepseek.com/v1/chat/completions)。extra_headers(litellm 不读该变量),需要本地反向代理或单独 patch。AI-IDE 通过 Docker 容器执行策略代码。策略分三种模式自动识别:
if __name__ == '__main__' 或顶层可执行代码)STRATEGY_CONFIG / get_strategy_config())→ 回测中心兼容模式# 从存储加载策略文件执行(云端策略)
curl -s -X POST -H "$AUTH" -H "$CT" "$BASE/api/v1/ai-ide/execute/start" \
-d '{
"file_id": "strategy_id_xxx",
"model_id": "mdl_cn_ensemble_xxx", # 可选:指定回测模型(默认模型)
"strategy_id": "strategy_xxx",
"run_id": "run_xxx",
"qlib_provider_uri": "db/qlib_data", # 多市场 Qlib 数据路径
"qlib_region": "cn", # cn / us / hk / crypto / futures
"benchmark": "SH000300"
}'
# 直接传代码执行(未保存代码)
curl -s -X POST -H "$AUTH" -H "$CT" "$BASE/api/v1/ai-ide/execute/run-tmp" \
-d '{
"content": "print(1+1)",
"filename": "tmp_strategy.py",
"model_id": "mdl_cn_ensemble_xxx"
}'
# 返回: {job_id, status: "started", runner_image}
# SSE 流式日志([SYSTEM]/[RESULT]/[ERROR]/[PROCESS_FINISHED])
curl -s -N -H "$AUTH" "$BASE/api/v1/ai-ide/execute/logs/{job_id}"
日志关键标记:
[SYSTEM] 使用回测中心同一回测引擎执行 — 模块型策略进入回测[RESULT] annual_return: ... / sharpe_ratio: ... — 回测结果[ERROR] ... — 执行错误[PROCESS_FINISHED] — 执行结束curl -s -X POST -H "$AUTH" "$BASE/api/v1/ai-ide/execute/stop/{job_id}"
curl -s -X POST -H "$AUTH" -H "$CT" "$BASE/api/v1/ai-ide/execute/check-syntax" \
-d '{"code": "class Strategy: ..."}'
AI-IDE 回测使用默认模型(GET /api/v1/models/default,缺失时先经管理后台/训练链路配置),回测前自动检查模型 pred 就绪:
pred.pkl / pred.parquet;缺失时提示"请先对该模型执行推理生成预测"ensemble_config.json):自动用子模型 pred 融合生成 pred.pkl(截面排名百分位加权)模块型策略(回测中心兼容模式)需定义:
STRATEGY_CONFIG:dict,含 class + kwargs(signal/topk/n_drop/rebalance_days 等)get_strategy_config():返回上述 dictPOOL_FILE 顶部变量指定股票池文件策略类参考(以代码为准:extended_strategies.py + recording_strategy.py;module_path 必须显写,
仅下表前 7 个类缺省时可由 builder 自动补全 strategy_builder.py:16-24):
| 类 | 模块路径 | 用途 |
|---|---|---|
RedisRecordingStrategy | ...qlib_app.utils.recording_strategy | 模型 TopK + f_ 基本面硬过滤(默认首选) |
RedisTopkStrategy | ...qlib_app.utils.extended_strategies | Top-K 选股(等权,最常用) |
RedisWeightStrategy | ...qlib_app.utils.recording_strategy | 分数加权(max_weight/min_score) |
RedisLongShortTopkStrategy | ...qlib_app.utils.extended_strategies | 多空 Top-K(用户明确要求多空时用) |
RedisStopLossStrategy | ...qlib_app.utils.extended_strategies | 止损止盈 |
RedisCrashBuyDipStrategy | ...qlib_app.utils.extended_strategies | 急跌抄底 |
SimpleWeightStrategy | ...qlib_app.utils.recording_strategy | 简单权重(基类) |
RedisMomentumStrategy | ...qlib_app.utils.extended_strategies | 动量(momentum_period 累计收益 + 模型分融合) |
RedisRiskGuardTopkStrategy | ...qlib_app.utils.extended_strategies | 大盘风控 Top-K(f_* 过滤 + 动态降仓) |
RedisAdvancedAlphaStrategy | ...qlib_app.utils.extended_strategies | 高级截面 Alpha(分数权重 + TopK-Dropout) |
RedisSectorRotationStrategy | ...qlib_app.utils.extended_strategies | 行业轮动 |
禁止引用
RedisVolatilityWeightedStrategy/RedisFullAlphaStrategy:代码中不存在, 生成会导致 ImportError。最小可用结构见后端模板backend/services/engine/routers/ai_ide/skill_templates/qlib_model_strategy_config.md:16-35(get_strategy_config()+signal: "<PRED>"+topk/n_drop/rebalance_days/only_tradable必备, 因子过滤必须用f_前缀参数)。
universe、buy/sell、ctx.history/feature):前缀式 SH600036/stock-terminal / D.features:后缀式 600036.SH
(跨格式查 parquet 会静默查空;Qlib 内部大小写由回测层自动兼容,生成代码时不用手写小写)SH600036;Redis 快照键为小写 market:snapshot:sh600036)StockCodeUtil.to_suffix/to_prefix
(backend/shared/stock_utils.py)显式转换,禁止手写切片。# 保存策略(字段以 StrategyCreateRequest 为准:name 必填,调参放 parameters,勿用 params/strategy_type/market)
curl -s -X POST -H "$AUTH" -H "$CT" "$BASE/api/v1/strategies" \
-d '{
"name": "AI生成-低估值策略",
"description": "PE<15 且 ROE>10",
"code": "STRATEGY_CONFIG = {...}",
"parameters": {"topk": 50, "n_drop": 5, "rebalance_days": 3},
"tags": ["AI生成"]
}'
# 策略列表 / 模板
curl -s -H "$AUTH" "$BASE/api/v1/strategies"
curl -s -H "$AUTH" "$BASE/api/v1/strategies/templates"
当用户要求"写个策略 / 运行策略"时:
STRATEGY_CONFIG(模块型)或可执行脚本/strategies POST 保存到云端/ai-ide/execute/start(带 model_id + qlib_provider_uri)/ai-ide/execute/logs/{job_id} SSE 流式,等 [PROCESS_FINISHED]| 现象 | 处理 |
|---|---|
| 模块型策略无法执行 | 确保有 STRATEGY_CONFIG 或 get_strategy_config() |
| 回测 universe 无数据/查空 | 先查股票代码格式:Lab SDK 用前缀 SH600036,Qlib/QuantDB 用后缀 600036.SH(见 §4) |
| 回测报"模型无可用预测文件" | 单模型先推理;融合模型会自动生成 pred |
| 回测慢 | 纯 TopK 策略自动向量化;复杂策略耗时正常 |
| 容器执行失败 | 查 /execute/logs/{job_id} 的错误详情 |
| 想换市场回测 | 传 qlib_provider_uri + qlib_region(多市场 Qlib 数据) |
OBobra/superpowers298k2,631 new stars in the last 7 days
OBobra/superpowers298k2,631 new stars in the last 7 days
MAmattpocock/skills288k10,178 new stars in the last 7 days
MAmattpocock/skills288k10,178 new stars in the last 7 days
MAmattpocock/skills288k10,178 new stars in the last 7 days
MAmattpocock/skills288k10,178 new stars in the last 7 days