quant-buddy-skill

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

观照量化投研

Guanzhao Quantitative Research & Investment

⚠️ 必读:本文件较长,必须完整读取,不要设置 limit 参数截断。前 50 行不包含操作规范。
⚠️ Must Read: This document is long and must be read in full. Do not use the limit parameter to truncate it. The first 50 lines do not contain operation specifications.

硬规则(8 条,违反必失败)

Hard Rules (8 Rules, Violation Results in Failure)

  1. 开工第一步:先查 API Key,再做任何其他事。收到新问题后的第一个动作必须是读
    config.json
    (或等效检查 api_key 字段):
    • api_key
      为空字符串 → 立即停止,直接输出「前置条件」章节的新用户引导消息禁止 newSession、禁止读 workflow / quick-lookup / 任何业务文档、禁止调用
      scripts/call.py
      或任何平台工具。等用户贴入
      sk-
      开头的 Key 后再执行「配置向导」。
    • api_key
      非空 → 继续第 1 条。
    • 唯一例外:用户本轮消息本身就是
      sk-
      开头的 Key(进入配置向导)或与查数无关的闲聊/元问题(如"你会做什么")。
    • 为什么:查数类工作流最终都会调
      scripts/call.py
      ,api_key 为空时必然失败。提前在入口拦截可以避免多次失败调用,给新用户直接、清晰的第一印象。
  2. 每个新问题/新对话必须新建 session:收到用户的新问题后,在调用任何平台工具之前,必须先新建 session(优先直接调用原生
    newSession
    工具;仅当当前环境没有原生
    newSession
    时,才使用
    GZQ_PARAMS='{"user_query":"<用户的问题>"}' python scripts/call.py newSession
    )。newSession 是本地 UUID 生成,不可省略;
    user_query
    仅用于本地 session 初始化标注,方便后续 trace 分析。
    • 为什么:session 文件会自动注入到所有工具调用中。不新建 session = 复用上一轮对话的 task_id = 变量名冲突风险 + session 污染。
    • 多会话隔离(必须):当本对话有可能与其他对话/进程并行使用本 skill(多个 Claude 窗口、共享开发机、并行 trace)时,在 chat 的第一条 bash 命令里先执行:
      bash
      export QBS_SESSION_KEY=$(python -c "import uuid;print(uuid.uuid4().hex[:12])")
      之后所有
      python scripts/call.py
      都必须在这同一个 terminal 会话里跑
      (环境变量只在该会话内可见)。如此每个对话独占
      output/.session.<key>.json
      文件,互不覆盖。未设置时退化到默认
      .session.json
      ,仅适合单会话场景。
    • 唯一例外:同一对话中的追问/续问(如"再画个图""换个时间段"),可复用当前 session(
      QBS_SESSION_KEY
      也保持不变)。
  3. 原生工具优先,脚本包装仅限无原生等价能力时:平台已提供的原生工具(
    fast_query
    confirmMultipleAssets
    confirmDataMulti
    runMultiFormulaBatch
    readData
    renderKLine
    renderChart
    等)必须优先直接调用;禁止用
    run_skill_script
    、shell 命令、
    GZQ_PARAMS=... python scripts/call.py ...
    等方式包装这些原生工具;
    scripts/call.py
    仅用于:①
    newSession
    等管理动作;② workflow 明确要求的本地脚本步骤;③ 平台不存在等价原生工具时的兜底。
    • ⛔ 典型违规反例(直接失败)
      confirmMultipleAssets
      intentions
      本身就是数组,设计意图是「一次传多个资产名同时确认」;任何在 for 循环 / while 循环里对它重复调用的写法都是违规,无论是通过原生工具还是
      scripts/call.py
      包装。需批量确认资产时,应单次调用并传完整数组;若数组过大,则按批传入(每批一次调用),而不是每个资产调用一次。
  • 确认资产也必须先查本地库:用户明确说「确认资产 / 批量确认 / confirm / 找代码 / 找ticker」时,仍然先走本地资产路由:
    presets/assets.yaml
    (可读完)→
    grep presets/assets_db/{类型}.yaml
    (禁止整文件读取)→ 仍未命中再调用
    confirmMultipleAssets
    。不得因为用户使用了「确认」二字就直接调用工具。
  • 英文代码无市场后缀时必须 grep 确认格式:用户直接输入英文股票代码(如
    GOOGL
    AAPL
    BIDU
    )但未携带市场后缀(
    .O
    .N
    .A
    )时,不得凭 user memory / 猜测 / 拼接后缀直接查数,必须先
    grep presets/assets_db/stock_us.yaml
    找到正确 ticker 后再调用工具。
  • ⛔ 严禁用 inline 解释器 heredoc /
    -c
    包装
    scripts/call.py
    :以下写法全部违规,无论参数有多复杂、批次有多少、依赖关系有多绕:
    • python - <<'PY' ... subprocess.run(['python','scripts/call.py','<工具名>',...]) ... PY
    • python -c "import subprocess; subprocess.run(['python','scripts/call.py',...])"
    • node -e "...child_process.execSync('python scripts/call.py ...')..."
    • 任何在 inline 脚本里
      for/while
      循环驱动多批
      runMultiFormulaBatch
      的写法
    • 理由:这种「自写 driver 脚本」会绕过本 skill 的 session 注入、配额校验、错误协议;trace 中表现为 task_id 漂移、stdout 阻塞、
      /tmp/gzq_out.txt
      在 Windows 上不存在等连锁失败。call.py 的兜底地位只允许一层调用(shell → call.py),不允许在它外面再套 python/node 解释器。
  • 多批
    runMultiFormulaBatch
    的合规模板
    :当公式数超过单批硬上限(20 条)需切批时,切批与编排必须由 LLM 自己在工具调用之间完成,禁止写脚本自动化。每批一次独立调用;任何参数预处理(读 md、regex、依赖分析、生成
    force_reusable_array
    )都在 LLM 推理中完成,必要的中间产物用
    create_file
    落盘到
    output/tmp_batches/batch_K.json
    ,然后逐批用:
    bash
    GZQ_PARAMS="$(cat output/tmp_batches/batch_K.json)" python scripts/call.py runMultiFormulaBatch
    每批一条独立 shell 命令,前一批返回后再发起下一批;禁止写一个 python 脚本一次跑完所有批。这是 hard rule,违反必失败。
  1. 先读 workflow 再操作:按下方「场景路由」表加载对应 workflow,不要自行猜测参数格式。
  2. 配置/认证错误立即停止,不得在普通查数流程中转为认证收集
    • 工具返回 API Key 缺失错误(含
      api_key 为空
      消息 /
      code: 1
      ):立即停止查数,输出新用户引导消息(格式见「前置条件」章节模板),禁止继续执行查数;等待用户粘贴 Key 后再执行配置向导。
    • 其他工具报错(网络、服务端错误等):直接报告"内部工具异常",不做认证相关引导。
  3. 最终答案首句必须是数据结论:回答用户时,第一句话必须直接给出数据结论(如资产名+数值、表格、或"符合条件的共N只"),绝对禁止以"已成功获取""数据已获取""根据返回结果""让我来"等过程性陈述开头。违反此规则 = 必须删除过程话术后重新输出。
  4. 用户条件冻结,不得改写:执行前必须逐字核对用户原始条件,以下改写行为均属违规(一旦发现必须回退并重新确认):
    • 百分比↔小数互转(如"股息率>3%"禁止改写为
      >0.03
    • 相对时间改为年份区间(如"过去10年"禁止改写为"2015-2025")
    • 资产宇宙替换(如"普通股票"禁止改写为"万得全A成分股"或"非ST股")
    • 事件口径扩大(如"年报/半年报"禁止扩大为全部业绩披露类型)
    • 卡片附加条件继承:命中知识卡片后,若卡片含用户未明确提出的"首次/非ST/封板/流动性门槛"等附加条件,必须先删除再执行,禁止默默继承进最终答案
  5. 任务含糊时先反问,禁止猜测开干:若用户的指令有 2 种以上合理解读(如"批量确认X"不清楚是确认指数本身还是全部成分股、"分析一下Y"不清楚要哪个维度),第一步必须向用户提问澄清,不得凭推测选择一种解读自行执行。反问应简洁列出各种可能(例:"您的意思是 ① … 还是 ② …?"),等用户确认后再继续。唯一例外:用户语义明确无歧义(如"给我贵州茅台今日收盘价"),无需反问。
  6. 检测到版本不匹配时必须按规定流程自愈,禁止以任何方式伪造版本号:版本不匹配信号有两类,必须分别处理。
    【P0 红线 — 任何情况下都不允许】
    • ❌ 禁止用
      replace_string_in_file
      /
      multi_replace_string_in_file
      /
      create_file
      覆盖 / 终端
      sed
      echo >
      等任何手段,修改本地
      SKILL.md
      config.json
      scripts/*.py
      CHANGELOG.md
      中任何
      version: x.y.z
      /
      metadata.version
      /
      _read_skill_version()
      相关字段,企图让本地版本号"对上"服务端。
    • ❌ 禁止把
      .session.json
      skill_version_at_creation
      改成新值绕过本地校验。
    • ⚠️ 这种"改字符串骗过校验"是欺骗式自愈:本地工具签名/参数格式仍是旧版,下次调用必然继续失败或行为错乱,且会污染用户工作目录。一旦你正在考虑做这类编辑,立即停手并改走下面的 (A) / (B) 流程。
    (A) 类:本地 session 与本地 SKILL.md 版本不匹配(信号:工具输出含
    "error": "SKILL_VERSION_MISMATCH"
    ,由本地
    scripts/call.py
    校验抛出,原因是当前 session 创建时记录的版本 ≠ 当前本地 SKILL.md 版本,通常是用户中途升级了 skill):
    1. 立即停止当前任务,不得再调用任何平台工具;
    2. 调用
      newSession
      (新建 session,获取新 task_id,并写入新版本号);
    3. 强制重读
      SKILL.md
      (本文件)+ 当前场景对应的 workflow 文档 + 涉及的
      tools/*.md
    4. 新读取的工具签名和参数格式重新执行用户原始任务;
    5. 禁止询问用户"是否继续"或解释版本升级过程——直接静默完成自愈并返回结果。
    (B) 类:服务端要求版本高于本地 skill 版本(信号:任何工具返回的 message / intro / error 中出现"skill 版本过低"、"请执行以下命令更新"、"npx skills update"、"skill_server_version"、
    code: -1
    且文案提示更新等;或者
    newSession
    返回的
    skill_version
    与服务端最新版本不一致而服务端要求强制升级):
    1. 立即停止当前任务,不得继续调用任何平台工具(再调也只会重复报错);
    2. 直接输出给用户一段明确的更新提示,并通过
      run_in_terminal
      执行(用户已授权 skill 内置脚本路径下的更新命令):
      bash
      # 默认走更新(适用于已安装过的老用户,不挑当年装在 .claude / .cursor / 全局还是项目)
      npx skills update pseudo-longinus/quant-buddy-skills -y
      若上一步退出码非 0、或输出含
      not installed
      /
      skill not found
      之类(说明用户从未安装过),回落到首装命令:
      bash
      npx skills add pseudo-longinus/quant-buddy-skills -g -a '*' -y
      Windows 上若任一命令报 symlink /
      EPERM
      / 权限错,末尾追加
      --copy
      重试一次:
      bash
      npx skills add pseudo-longinus/quant-buddy-skills -g -a '*' --copy -y
      用户拿不准当前装在哪,可让其自检:
      npx skills list -g --json
      。 (如服务端
      intro
      字段给出的命令与此不同,以服务端返回的命令为准,不要自作主张换包名/换源/换标志位。)
    3. 等待命令执行完毕(成功标志:退出码 0 且输出含
      installed
      /
      updated to x.y.z
      );若仍失败(
      command not found
      /
      EACCES
      / 网络/registry 不通等),把原始错误整段交给用户,让用户线下处理,不要自己尝试改文件凑数、不要换源、不要换包名;
    4. 命令成功后,强制重读
      SKILL.md
      (确认
      version
      已是新版)+ 当前场景的 workflow + 相关
      tools/*.md
    5. 调用
      newSession
      重建 session(让
      skill_version_at_creation
      更新为新版);
    6. 以新版工具签名重新执行用户原始任务。
    判别提示:分不清是 (A) 还是 (B) 时,先按 (A) 跑一遍 newSession + 重读;如果重试仍立刻报版本错或服务端继续提示要更新,就转 (B) 跑
    npx skills update
    (必要时回落
    add
    )。永远不要反过来"先改本地版本号试试看"。
  1. First Step Before Starting: Check API Key First, Then Do Anything Else. The first action after receiving a new question must be to read
    config.json
    (or equivalently check the api_key field):
    • If
      api_key
      is an empty string → Stop immediately, directly output the new user guide message in the "Prerequisites" section, prohibit newSession, prohibit reading workflow / quick-lookup / any business documents, prohibit calling
      scripts/call.py
      or any platform tools. Wait for the user to paste a Key starting with
      sk-
      before executing the "Configuration Wizard".
    • If
      api_key
      is non-empty → Proceed to Rule 1.
    • Only Exception: The user's current message is a Key starting with
      sk-
      (enter configuration wizard) or chat/meta questions unrelated to data querying (e.g., "What can you do?").
    • Why: Data query workflows will eventually call
      scripts/call.py
      , which will definitely fail if api_key is empty. Intercepting at the entrance in advance avoids multiple failed calls and gives new users a direct, clear first impression.
  2. Create a New Session for Each New Question/New Conversation: After receiving a user's new question, before calling any platform tools, you must create a new session (prefer to directly call the native
    newSession
    tool; only use
    GZQ_PARAMS='{"user_query":"<user's question>"}' python scripts/call.py newSession
    if the native
    newSession
    is not available in the current environment). newSession generates a local UUID and cannot be omitted;
    user_query
    is only used for local session initialization annotation to facilitate subsequent trace analysis.
    • Why: Session files are automatically injected into all tool calls. Not creating a new session = reusing the task_id from the previous conversation = risk of variable name conflicts + session pollution.
    • Multi-Session Isolation (Mandatory): When this conversation may use this skill in parallel with other conversations/processes (multiple Claude windows, shared development machines, parallel traces), in the first bash command of the chat, execute first:
      bash
      export QBS_SESSION_KEY=$(python -c "import uuid;print(uuid.uuid4().hex[:12])")
      After that, all
      python scripts/call.py
      must be run in the same terminal session
      (environment variables are only visible within this session). This way, each conversation exclusively uses the
      output/.session.<key>.json
      file without overwriting each other. If not set, it degrades to the default
      .session.json
      , which is only suitable for single-session scenarios.
    • Only Exception: Follow-up questions in the same conversation (e.g., "Draw another chart" "Change the time period") can reuse the current session (keep
      QBS_SESSION_KEY
      unchanged).
  3. Prioritize Native Tools; Script Wrapping Only When No Native Equivalent Exists: Must prioritize direct calls to native tools provided by the platform (such as
    fast_query
    ,
    confirmMultipleAssets
    ,
    confirmDataMulti
    ,
    runMultiFormulaBatch
    ,
    readData
    ,
    renderKLine
    ,
    renderChart
    , etc.); prohibit wrapping these native tools using
    run_skill_script
    , shell commands,
    GZQ_PARAMS=... python scripts/call.py ...
    , etc.;
    scripts/call.py
    is only used for: ① Management actions like
    newSession
    ; ② Local script steps explicitly required by workflows; ③ Fallback when no equivalent native tool exists on the platform.
    • ⛔ Typical Violation Examples (Direct Failure): The
      intentions
      of
      confirmMultipleAssets
      is an array by design, intended to "confirm multiple asset names at once"; any repeated calls to it in for/while loops are violations, whether through native tools or
      scripts/call.py
      wrapping. When confirming assets in batches, call it once and pass the complete array; if the array is too large, pass it in batches (one call per batch) instead of calling once per asset.
  • Must Check Local Library First for Asset Confirmation: When the user explicitly says "confirm assets / batch confirmation / confirm / find code / find ticker", still follow the local asset routing:
    presets/assets.yaml
    (can be read in full) →
    grep presets/assets_db/{type}.yaml
    (prohibit reading the entire file) → call
    confirmMultipleAssets
    only if no match is found. Do not directly call the tool just because the user used the word "confirm".
  • Must Grep to Confirm Format for English Codes Without Market Suffix: When the user directly enters an English stock code (e.g.,
    GOOGL
    ,
    AAPL
    ,
    BIDU
    ) without a market suffix (
    .O
    ,
    .N
    ,
    .A
    ), do not query data directly based on user memory / guesses / suffix concatenation, must first
    grep presets/assets_db/stock_us.yaml
    to find the correct ticker before calling the tool.
  • ⛔ Strictly Prohibit Wrapping
    scripts/call.py
    with Inline Interpreter Heredoc /
    -c
    : The following writing methods are all violations, regardless of how complex the parameters are, how many batches there are, or how complicated the dependency relationships are:
    • python - <<'PY' ... subprocess.run(['python','scripts/call.py','<tool name>',...]) ... PY
    • python -c "import subprocess; subprocess.run(['python','scripts/call.py',...])"
    • node -e "...child_process.execSync('python scripts/call.py ...')..."
    • Any writing method that drives multiple batches of
      runMultiFormulaBatch
      with
      for/while
      loops in inline scripts
    • Reason: Such "self-written driver scripts" will bypass session injection, quota verification, and error protocols of this skill; traces will show task_id drift, stdout blocking,
      /tmp/gzq_out.txt
      not existing on Windows, and other chain failures. The fallback status of call.py only allows one layer of calls (shell → call.py), and does not allow wrapping it with python/node interpreters outside.
  • Compliant Template for Multiple Batches of
    runMultiFormulaBatch
    : When the number of formulas exceeds the single-batch hard limit (20 entries) and needs to be split into batches, batch splitting and orchestration must be done by the LLM itself between tool calls, and script automation is prohibited. Each batch is an independent call; any parameter preprocessing (reading md, regex, dependency analysis, generating
    force_reusable_array
    ) is done in LLM reasoning, and necessary intermediate products are saved to
    output/tmp_batches/batch_K.json
    using
    create_file
    , then call batch by batch with:
    bash
    GZQ_PARAMS="$(cat output/tmp_batches/batch_K.json)" python scripts/call.py runMultiFormulaBatch
    One independent shell command per batch, initiate the next batch only after the previous batch returns; prohibit writing a python script to run all batches at once. This is a hard rule, violation results in failure.
  1. Read Workflow Before Operation: Load the corresponding workflow according to the "Scenario Routing" table below, do not guess parameter formats on your own.
  2. Stop Immediately on Configuration/Authentication Errors; Do Not Switch to Authentication Collection in Normal Data Query Processes:
    • Tool Returns API Key Missing Error (including
      api_key is empty
      message /
      code: 1
      ): Stop data query immediately, output the new user guide message (see template in "Prerequisites" section), prohibit continuing data query; wait for the user to paste the Key before executing the configuration wizard.
    • Other Tool Errors (network, server errors, etc.): Directly report "Internal tool exception", do not provide authentication-related guidance.
  3. First Sentence of Final Answer Must Be Data Conclusion: When answering the user, the first sentence must directly give the data conclusion (e.g., asset name + value, table, or "N items meet the criteria"), absolutely prohibit starting with process statements like "Successfully obtained" "Data obtained" "According to the returned results" "Let me do this". Violating this rule = must delete process statements and re-output.
  4. Freeze User Conditions; Do Not Rewrite: Must check the user's original conditions word by word before execution, the following rewriting behaviors are all violations (must roll back and re-confirm once found):
    • Percentage ↔ Decimal Conversion (e.g., "dividend rate >3%" is prohibited from being rewritten as
      >0.03
      )
    • Relative Time Changed to Year Range (e.g., "past 10 years" is prohibited from being rewritten as "2015-2025")
    • Asset Universe Replacement (e.g., "ordinary stocks" is prohibited from being rewritten as "Wind All A Components" or "non-ST stocks")
    • Event Scope Expansion (e.g., "annual report/semi-annual report" is prohibited from being expanded to all performance disclosure types)
    • Card Additional Condition Inheritance: After hitting a knowledge card, if the card contains additional conditions not explicitly proposed by the user, such as "first-time/non-ST/limit-up/liquidity threshold", must delete them first before execution, prohibit silently inheriting them into the final answer
  5. Ask for Clarification First When Task Is Ambiguous; Prohibit Guessing and Starting: If the user's instruction has 2 or more reasonable interpretations (e.g., "batch confirm X" is unclear whether to confirm the index itself or all its components, "analyze Y" is unclear which dimension to use), the first step must be to ask the user for clarification, do not choose one interpretation based on speculation and execute it on your own. The clarification should briefly list the possible interpretations (example: "Do you mean ① … or ② …?"), wait for the user's confirmation before proceeding. Only Exception: The user's semantics are clear and unambiguous (e.g., "Give me today's closing price of Kweichow Moutai"), no need to ask for clarification.
  6. Must Follow the Specified Process to Self-Heal When Version Mismatch Is Detected; Prohibit Forging Version Numbers in Any Way: There are two types of version mismatch signals, which must be handled separately.
    【P0 Red Line — Not Allowed Under Any Circumstances】
    • ❌ Prohibit using
      replace_string_in_file
      /
      multi_replace_string_in_file
      /
      create_file
      to overwrite / terminal
      sed
      ,
      echo >
      or any other means to modify any
      version: x.y.z
      /
      metadata.version
      /
      _read_skill_version()
      related fields in local
      SKILL.md
      ,
      config.json
      ,
      scripts/*.py
      ,
      CHANGELOG.md
      , attempting to make the local version number "match" the server.
    • ❌ Prohibit changing the
      skill_version_at_creation
      of
      .session.json
      to a new value to bypass local verification.
    • ⚠️ Such "changing strings to cheat verification" is deceptive self-healing: the local tool signature/parameter format is still the old version, the next call will definitely fail or behave abnormally, and will pollute the user's working directory. Once you are considering doing such edits, stop immediately and switch to the (A) / (B) process below.
    Type (A): Local Session Version Mismatches Local SKILL.md Version (Signal: Tool output contains
    "error": "SKILL_VERSION_MISMATCH"
    , thrown by local
    scripts/call.py
    verification, reason is that the version recorded when the current session was created ≠ the current local SKILL.md version, usually because the user upgraded the skill midway):
    1. Stop immediately the current task, do not call any platform tools anymore;
    2. Call
      newSession
      (create a new session, get a new task_id, and write the new version number);
    3. Forcefully re-read
      SKILL.md
      (this file) + the workflow document corresponding to the current scenario + the involved
      tools/*.md
      ;
    4. Re-execute the user's original task with the newly read tool signature and parameter format;
    5. Prohibit asking the user "whether to continue" or explaining the version upgrade process — complete self-healing silently and return the result directly.
    Type (B): Server Requires Higher Version Than Local Skill Version (Signal: Any tool's returned message / intro / error contains "skill version is too low", "please execute the following command to update", "npx skills update", "skill_server_version",
    code: -1
    with prompt to update, etc.; or the
    skill_version
    returned by
    newSession
    is inconsistent with the latest server version and the server requires forced upgrade):
    1. Stop immediately the current task, do not continue calling any platform tools (calling again will only repeat the error);
    2. Directly output a clear update prompt to the user, and execute it via
      run_in_terminal
      (the user has authorized the update command in the skill's built-in script path):
      bash
      # Default to update (suitable for old users who have installed it, regardless of whether it was installed in .claude / .cursor / global or project)
      npx skills update pseudo-longinus/quant-buddy-skills -y
      If the exit code of the previous step is non-0, or the output contains
      not installed
      /
      skill not found
      (indicating the user has never installed it), fall back to the initial installation command:
      bash
      npx skills add pseudo-longinus/quant-buddy-skills -g -a '*' -y
      If either command reports symlink /
      EPERM
      / permission errors on Windows, append
      --copy
      at the end and retry once:
      bash
      npx skills add pseudo-longinus/quant-buddy-skills -g -a '*' --copy -y
      If the user is unsure where it is currently installed, let them self-check:
      npx skills list -g --json
      . (If the command given in the server's
      intro
      field is different from this, follow the command returned by the server, do not change the package name/source/flags on your own.)
    3. Wait for the command to execute successfully (success sign: exit code 0 and output contains
      installed
      /
      updated to x.y.z
      ); if it still fails (
      command not found
      /
      EACCES
      / network/registry unreachable, etc.), give the original error to the user in full, let the user handle it offline, do not try to modify files to make it work, do not change sources, do not change package names;
    4. After the command succeeds, forcefully re-read
      SKILL.md
      (confirm
      version
      is the new version) + the workflow of the current scenario + related
      tools/*.md
      ;
    5. Call
      newSession
      to rebuild the session (update
      skill_version_at_creation
      to the new version);
    6. Re-execute the user's original task with the new tool signature.
    Discrimination Tip: If you can't tell whether it's (A) or (B), run (A) first newSession + re-read; if the retry still reports version error immediately or the server continues to prompt for update, switch to (B) and run
    npx skills update
    (fall back to
    add
    if necessary). Never reverse it by "changing the local version number first to try".

最小充分原则(任何动作前自检)

Principle of Minimal Sufficiency (Self-Check Before Any Action)

默认走最窄路径;只在收到"明确不够用"的证据后,才扩大范围。
每次准备读文件、调工具、扩大读取范围前,回答三个问题
  1. 这一步要解决的具体问题是什么? — 必须能用一句话写成"为了 X,所以做 Y",其中 X 是已经发生的需求,不能是"可能会需要 X"、"以防万一"、"先准备着"。
  2. 有没有更窄的选项能完成同样的 X? — 更下游的输出 / 更精简的文件 / 更少的字段 / 不调用这个工具直接构造。
  3. 当前选择如果失败,下一步是什么? — 如果答不上来,说明还没想清楚就在动手。
任一回答含糊 → 不做这一步。
扩大范围的唯一合法触发:上一步工具明确返回了"缺数据 / 字段不存在 / 失败",且失败原因可以追溯。不允许用"为了更全面"、"为了更准确"、"为了避免遗漏"作为理由。
这条原则覆盖:要不要多读一个文档;readData 读哪个变量;要不要为某个字段调 confirmDataMulti;公式自己写还是查现成数据集;以及所有未来出现的同类决策。
工具层面落地:调用
confirmDataMulti
/
readData
/
runMultiFormulaBatch
或加载额外文档前,必须先勾选
recipes/tool-call-checklist.md
对应小节(每节 5–10 行)。顶层原则管"要不要做",清单管"具体怎么做"。
Default to the narrowest path; only expand the scope when receiving clear evidence that "it is not enough".
Before preparing to read a file, call a tool, or expand the reading scope, answer three questions:
  1. What is the specific problem to be solved in this step? — Must be able to be written in one sentence as "Do Y to solve X", where X is a already existing requirement, not "may need X", "just in case", "prepare first".
  2. Is there a narrower option to achieve the same X? — More downstream output / more streamlined file / fewer fields / construct directly without calling this tool.
  3. What is the next step if the current choice fails? — If you can't answer, it means you haven't thought it through before acting.
If any answer is ambiguous → Do not take this step.
Only Valid Trigger for Expanding Scope: The previous tool clearly returned "missing data / field does not exist / failure", and the failure reason can be traced back. Do not use "for comprehensiveness", "for accuracy", "to avoid omissions" as reasons.
This principle covers: whether to read one more document; which variable to read with readData; whether to call confirmDataMulti for a certain field; whether to write formulas yourself or check existing datasets; and all similar decisions that may arise in the future.
Implementation at Tool Level: Before calling
confirmDataMulti
/
readData
/
runMultiFormulaBatch
or loading additional documents, must check the corresponding section in
recipes/tool-call-checklist.md
(5–10 lines per section). The top-level principle governs "whether to do it", and the checklist governs "how to do it specifically".

Skill 包根目录

Skill Package Root Directory

本 SKILL.md 所在目录即为 skill 根目录(
SKILL_ROOT
,下文所有相对路径均以此为基准。 所有终端命令必须先
cd
到此目录再执行。
SKILL_ROOT/
├── config.json              ← API Key 配置(按需读取;非每题必读)
├── SKILL.md                 ← 本文件(入口 + 路由)
├── workflows/               ← 业务流程编排(路由目标)
│   ├── fast-snapshot.md         Fast Path:最新时点行情/估值(≤3资产,标量)
│   ├── fast-window.md           Fast Path:最近N日序列/窗口统计
│   ├── fast-report-period.md    Fast Path:最近报告期财务(≤3资产)
│   ├── quick-lookup.md          快速查数路由器 + 共享基础规则
│   ├── quick-snapshot.md        最新时点行情/估值快照(字段齐即停)
│   ├── quick-window.md          最近N日短窗序列/窗口统计
│   ├── quick-report-period.md   最近报告期财务指标
│   ├── period-return-compare.md 固定区间累计涨跌幅对比
│   ├── global-rules-lite.md     精简全局规则(quick-window/period-return-compare 专用)
│   ├── quant-standard.md        选股/回测/因子/图表标准流程
│   ├── event-study.md           事件研究(给定或可识别事件后的窗口表现)
│   ├── regime-segmentation.md   阈值区间/连续阶段识别与区间统计
│   └── render-kline.md          K线图渲染与交付
├── recipes/                 ← 公式模板 & 工具用法(被 workflow 引用)
│   ├── ma-crossover-backtest.md     均线金叉策略
│   ├── value-pe-strategy.md         PE估值选股
│   ├── upload-custom-data.md        上传自有数据
│   ├── render-chart.md              渲染图表
│   ├── download-data.md             下载数据
│   └── industry-aggregation.md      行业聚合排名
├── references/              ← 参考文档
│   ├── environment.md           环境依赖
│   ├── troubleshooting.md       故障排查
│   └── ru-billing.md            RU 计费
├── tools/                   ← API 工具的完整参数文档
│   ├── run_multi_formula.md
│   ├── read_data.md
│   └── ...(正常链路无需提前阅读,遇到参数问题时查)
├── presets/                 ← 已验证的常用数据(按需加载)
│   ├── cases_index.yaml         106 张案例卡片目录(量化标准场景必读,快速查数无需)
│   ├── assets.yaml              常用资产(99 行精选,可一次读完)
│   ├── assets_db/               全量资产字典(按类型分文件,⚠️ 仅 grep 检索,禁止 read_file 整文件;不含指数成分股映射)
│   │   ├── stock_a.yaml             A 股 5505 条(SH/SZ)
│   │   ├── stock_hk.yaml            港股 2862 条(HK 前缀,仅行情)
│   │   ├── stock_us.yaml            美股 1044 条(.N/.O/.A,仅行情)
│   │   ├── index.yaml               指数 503 条
│   │   └── future.yaml              期货 257 条
│   ├── functions.yaml           常用函数
│   ├── data_catalog.yaml        常用数据集
│   ├── sectors.yaml             行业板块
│   └── themes.yaml              题材板块
├── scripts/                 ← 执行脚本
│   ├── call.py                  工具统一入口(所有命令通过它调用)
│   ├── executor.py              call.py 的底层(禁止直接调用)
│   ├── quant_api.py             Python SDK(供其他脚本 import)
│   ├── auth/                    认证脚本
│   └── eval/                    评测脚本
└── output/                  ← 输出目录(自动创建)
    ├── .session.<key>.json      当前 session task_id(按 QBS_SESSION_KEY 派生,多会话隔离)
    ├── ic_data/                 IC 扫描结果
    └── *.png / *.csv            图表和数据文件

全局 429 处理(所有路径均适用)
error.code处理
RATE_LIMIT_EXCEEDED
/
CONCURRENT_LIMIT
retryAfter
秒后静默重试,不向用户暴露
WINDOW_QUOTA_EXCEEDED
立即停止,读
references/troubleshooting.md
配额限流段,输出提示
DAILY_QUOTA_EXCEEDED
/
DAILY_SCAN_EXCEEDED
立即停止,输出:
⚠️ 今日额度已满,次日 00:00 重置。
SERVICE_OVERLOADED
(503)
retryAfter
秒后静默重试 1 次,仍失败则告知"系统繁忙,请稍后重试"

The directory where this SKILL.md is located is the skill root directory (
SKILL_ROOT
)
, all relative paths below are based on this. All terminal commands must first
cd
to this directory before execution.
SKILL_ROOT/
├── config.json              ← API Key configuration (read on demand; not required to read for every question)
├── SKILL.md                 ← This file (entry + routing)
├── workflows/               ← Business process orchestration (routing target)
│   ├── fast-snapshot.md         Fast Path: Latest market/valuation (≤3 assets, scalar)
│   ├── fast-window.md           Fast Path: Latest N-day sequence/window statistics
│   ├── fast-report-period.md    Fast Path: Latest reporting period financials (≤3 assets)
│   ├── quick-lookup.md          Quick data query router + shared basic rules
│   ├── quick-snapshot.md        Latest market/valuation snapshot (stop when fields are complete)
│   ├── quick-window.md          Latest N-day short-window sequence/window statistics
│   ├── quick-report-period.md   Latest reporting period financial indicators
│   ├── period-return-compare.md Fixed interval cumulative price change comparison
│   ├── global-rules-lite.md     Simplified global rules (exclusive to quick-window/period-return-compare)
│   ├── quant-standard.md        Standard process for stock selection/backtesting/factors/charts
│   ├── event-study.md           Event study (window performance after given or identifiable events)
│   ├── regime-segmentation.md   Threshold interval/continuous phase identification and interval statistics
│   └── render-kline.md          K-line chart rendering and delivery
├── recipes/                 ← Formula templates & tool usage (referenced by workflows)
│   ├── ma-crossover-backtest.md     Moving average crossover strategy
│   ├── value-pe-strategy.md         PE valuation stock selection
│   ├── upload-custom-data.md        Upload custom data
│   ├── render-chart.md              Render charts
│   ├── download-data.md             Download data
│   └── industry-aggregation.md      Industry aggregation ranking
├── references/              ← Reference documents
│   ├── environment.md           Environment dependencies
│   ├── troubleshooting.md       Troubleshooting
│   └── ru-billing.md            RU billing
├── tools/                   ← Complete parameter documentation for API tools
│   ├── run_multi_formula.md
│   ├── read_data.md
│   └── ... (no need to read in advance for normal links, check when parameter issues occur)
├── presets/                 ← Verified commonly used data (loaded on demand)
│   ├── cases_index.yaml         106 case card directory (required for quantitative standard scenarios, not needed for quick data query)
│   ├── assets.yaml              Commonly used assets (99 lines of selected assets, can be read in full at once)
│   ├── assets_db/               Full asset dictionary (divided by type, ⚠️ only grep for retrieval, prohibit reading the entire file; does not include index component mapping)
│   │   ├── stock_a.yaml             5505 A-shares (SH/SZ)
│   │   ├── stock_hk.yaml            2862 H-shares (HK prefix, market data only)
│   │   ├── stock_us.yaml            1044 U.S. stocks (.N/.O/.A, market data only)
│   │   ├── index.yaml               503 indices
│   │   └── future.yaml              257 futures
│   ├── functions.yaml           Commonly used functions
│   ├── data_catalog.yaml        Commonly used datasets
│   ├── sectors.yaml             Industry sectors
│   └── themes.yaml              Thematic sectors
├── scripts/                 ← Execution scripts
│   ├── call.py                  Unified tool entry (all commands are called through it)
│   ├── executor.py              Underlying of call.py (prohibit direct call)
│   ├── quant_api.py             Python SDK (imported by other scripts)
│   ├── auth/                    Authentication scripts
│   └── eval/                    Evaluation scripts
└── output/                  ← Output directory (automatically created)
    ├── .session.<key>.json      Current session task_id (derived from QBS_SESSION_KEY, multi-session isolation)
    ├── ic_data/                 IC scan results
    └── *.png / *.csv            Chart and data files

Global 429 Handling (Applicable to All Paths):
error.codeHandling
RATE_LIMIT_EXCEEDED
/
CONCURRENT_LIMIT
Retry silently after reading
retryAfter
seconds, do not expose to users
WINDOW_QUOTA_EXCEEDED
Stop immediately, read the quota limiting section in
references/troubleshooting.md
, output prompt
DAILY_QUOTA_EXCEEDED
/
DAILY_SCAN_EXCEEDED
Stop immediately, output:
⚠️ Daily quota has been used up, reset at 00:00 next day.
SERVICE_OVERLOADED
(503)
Retry silently once after
retryAfter
seconds, if still failed, inform "System is busy, please try again later"

⛔ 执行顺序(路由前必读,所有场景必须遵守)

⛔ Execution Order (Must Read Before Routing, All Scenarios Must Comply)

无论匹配到哪个 leaf workflow,执行顺序固定为:
① read_skill_file(global-rules 版本,见下表)  →  ② read_skill_file(leaf workflow)  →  ③ 执行
步骤 ① 全局规则文件选择(按目标 leaf workflow 确定)
目标 leaf workflow步骤 ① 读取的文件
fast-snapshot.md
无(Fast Path,跳过步骤 ①,直接执行)
fast-window.md
无(Fast Path,跳过步骤 ①,直接执行)
fast-report-period.md
无(Fast Path,跳过步骤 ①,直接执行)
quick-window.md
workflows/global-rules-lite.md
period-return-compare.md
workflows/global-rules-lite.md
其他所有 workflow
workflows/global-rules.md
  • 步骤 ① 是硬前置条件。确定目标 leaf 后,先按上表选择并读取对应 global-rules 版本,再读 leaf workflow,最后执行。
  • Fast Path(fast-*.md)直接从步骤 ② 开始,无需步骤 ①。

Regardless of which leaf workflow is matched, the execution order is fixed as:
① read_skill_file(global-rules version, see table below)  →  ② read_skill_file(leaf workflow)  →  ③ Execute
Step ① Global Rules File Selection (Determined by Target Leaf Workflow):
Target Leaf WorkflowFile Read in Step ①
fast-snapshot.md
None (Fast Path, skip Step ①, execute directly)
fast-window.md
None (Fast Path, skip Step ①, execute directly)
fast-report-period.md
None (Fast Path, skip Step ①, execute directly)
quick-window.md
workflows/global-rules-lite.md
period-return-compare.md
workflows/global-rules-lite.md
All other workflows
workflows/global-rules.md
  • Step ① is a hard prerequisite. After determining the target leaf, select and read the corresponding global-rules version according to the table above, then read the leaf workflow, and finally execute.
  • Fast Path (fast-*.md) starts directly from Step ②, no need for Step ①.

场景路由

Scenario Routing

先识别用户意图,确定目标 leaf workflow;然后按上方执行顺序加载
场景触发词目标 leaf workflow
最新时点行情 / 估值(快照)最新价、今日收盘、最新涨跌幅、当前换手率、最新PE/PB/市值…Fast Path →
fast-snapshot.md
/ 完整链路 →
global-rules.md
quick-snapshot.md
最近N日序列 / 窗口统计最近5日、最近20日、近N个交易日、窗口最高/最低/振幅…(仅单资产、最近N日)Fast Path →
fast-window.md
/ 完整链路 →
global-rules-lite.md
quick-window.md
最近报告期财务营收、净利润、归母净利润、ROE、总资产、总负债、资产负债率…Fast Path →
fast-report-period.md
/ 完整链路 →
global-rules.md
quick-report-period.md
K线图(可视化)K线图、画图、展示走势…
global-rules.md
render-kline.md
固定区间累计涨跌幅从A到B、某年某月至某年某月、区间收益、累计涨跌幅、区间表现、多资产区间对比
global-rules-lite.md
period-return-compare.md
量化选股 / 回测 / 因子 / 图表 / 上传下载选股、回测、均线、PE选股、因子、净值、上传CSV、下载数据、画图…
global-rules.md
quant-standard.md
直接运行用户给定的公式链文件「运行/跑一遍/执行这个文件里的全部公式」「公式链文件」「formula chain」「按这个 md/json 跑」
global-rules.md
run-formula-chain.md
事件研究复盘、历次、涨价、降息、加息、事件窗口、随后表现、超预期、不及预期、政策后表现…(给定事件或需先识别事件日)
global-rules.md
event-study.md
阈值区间统计 / 连续阶段历次、每次、平均、回撤超过、从高点下跌超过、熊市区间、连续阶段、regime
global-rules.md
regime-segmentation.md
上传、下载、画图不是独立场景——它们是 workflow 内的子步骤,workflow 文档会在需要时指引你读对应的
recipes/
First identify the user's intention, determine the target leaf workflow; then load according to the execution order above:
ScenarioTrigger WordsTarget Leaf Workflow
Latest market / valuation (snapshot)Latest price, today's close, latest price change, current turnover rate, latest PE/PB/market capitalization…Fast Path →
fast-snapshot.md
/ Complete link →
global-rules.md
quick-snapshot.md
Latest N-day sequence / window statisticsLatest 5 days, latest 20 days, latest N trading days, window high/low/amplitude… (single asset only, latest N days)Fast Path →
fast-window.md
/ Complete link →
global-rules-lite.md
quick-window.md
Latest reporting period financialsOperating income, net profit, attributable net profit, ROE, total assets, total liabilities, asset-liability ratio…Fast Path →
fast-report-period.md
/ Complete link →
global-rules.md
quick-report-period.md
K-line chart (visualization)K-line chart, draw chart, show trend…
global-rules.md
render-kline.md
Fixed interval cumulative price changeFrom A to B, from year month to year month, interval return, cumulative price change, interval performance, multi-asset interval comparison
global-rules-lite.md
period-return-compare.md
Quantitative stock selection / backtesting / factors / charts / upload/downloadStock selection, backtesting, moving average, PE stock selection, factors, net value, upload CSV, download data, draw chart…
global-rules.md
quant-standard.md
Directly run the formula chain file given by the user"Run/execute all formulas in this file" "formula chain file" "formula chain" "Run according to this md/json"
global-rules.md
run-formula-chain.md
Event studyReview, historical, price increase, interest rate cut, interest rate hike, event window, subsequent performance, better than expected, worse than expected, performance after policy… (given event or need to identify event date first)
global-rules.md
event-study.md
Threshold interval statistics / continuous phaseHistorical, each time, average, drawdown exceeds, falls more than from high, bear market interval, continuous phase, regime
global-rules.md
regime-segmentation.md
Upload, download, and charting are not independent scenarios — they are sub-steps within workflows, and workflow documents will guide you to read the corresponding
recipes/
when needed.

路由硬排除(优先于触发词匹配)

Routing Hard Exclusions (Prioritize Over Trigger Word Matching)

以下规则在触发词匹配之前检查,命中即强制改道,不得被触发词覆盖:
用户意图特征禁止进入强制导向判断依据
盘中/实时/当前/现在/今天/今日/当日 + 查询日内行情(涨幅排名、涨停、日内跌幅等)
quick-snapshot
quick-window
quant-standard.md
(优先匹配分钟频卡片)
需要分钟频卡片的专用公式;
use_minute_data: true
已是全局默认
盘中/实时/当前/今天/今日/当日 + 全市场/板块 + TopN/排名/阈值名单/选股/筛选/信号
quick-snapshot
quick-window
quant-standard.md
→ 优先命中"实时横截面 TopN 排名"或"盘中阈值筛选_名单查询"微流程
这类高频短题有专用封闭微流程
给出明确起止日期,只问区间累计涨跌幅/收益
event-study
quick-window
quant-standard
period-return-compare.md
本质是固定区间收益比较,不是因果窗口分析,也不是复杂量化流程
行业/板块聚合排名(如"申万行业涨幅前5")
quick-window
quick-snapshot
quant-standard.md
需要横截面聚合,不是单资产序列
阈值触发型离散事件识别(如"跌幅超过X%的次数",问每次后表现)
event-study.md
(阈值触发模式)
需先识别阈值事件日,再做窗口分析
由阈值条件定义连续区间(如"历次熊市""回撤超30%的阶段")
event-study
regime-segmentation.md
研究的是连续阶段而非离散事件后的窗口
"创近N日新高/新低"(不含"首次"修饰词)不得加"昨日未满足"条件当前状态判断(state check),公式只比较当前值与昨日的N日极值只有用户明确出现"首次突破/首次跌破""新晋""今日第一次"时,才允许追加首次触发条件;详见
quant-standard.md
判断口诀:
  • 有明确起止日 + 只问区间数值
    period-return-compare
    (固定区间收益比较)
  • 有事件 + 问"随后N天/月表现"
    event-study
    (因果窗口)
  • 有阈值条件 + 问"每次发生后表现"
    event-study
    (阈值触发模式)
  • 有阈值条件 + 问"连续阶段/区间内表现"
    regime-segmentation
    (连续阶段统计)
若用户请求满足以下任一模式,应优先判定为【快速查数任务】,按以下路由直接跳转,不得先进入其他 workflow:
Fast Path 条件(同时满足以下 3 点才可走 Fast Path;否则走完整链路):
  • 资产数 ≤ 3
  • 所有目标字段属于 fast_query whitelist(价格/估值/财务/衍生字段,详见
    tools/fast_query.md
    ),不涉及自定义公式/选股/排名
  • 非全市场横截面查询(不是"全市场排名/前N只"等场景)
快速查数路由(按优先级依次判断,首个匹配即停):
  1. 时间锚点是"最近 N 日窗口/序列" → Fast Path 条件满足时读
    workflows/fast-window.md
    ,不满足则
    workflows/global-rules-lite.md
    workflows/quick-window.md
  2. 时间锚点是"最近报告期"且字段属于财务类 → Fast Path 条件满足时读
    workflows/fast-report-period.md
    ,不满足则
    workflows/global-rules.md
    workflows/quick-report-period.md
  3. 用户明确要"画图 / K线 / 带成交量走势" → 直接加载
    workflows/render-kline.md
  4. 其余(明确是最近完成交易日的行情/估值/多资产对比,且不含 今天/今日/当日/当前/现在/实时/盘中/排名/筛选 语义)→ Fast Path 条件满足时读
    workflows/fast-snapshot.md
    ,不满足则
    workflows/global-rules.md
    workflows/quick-snapshot.md
上述路由不需要先读
workflows/quick-lookup.md
The following rules are checked before trigger word matching; if hit, forced redirection is required, and cannot be overwritten by trigger words:
User Intention FeatureProhibit EnteringForce Redirect ToJudgment Basis
Intraday/real-time/current/now/today/today's + query intraday market (price change ranking, limit-up, intraday price change, etc.)
quick-snapshot
quick-window
quant-standard.md
(prioritize matching minute-frequency cards)
Requires dedicated formulas for minute-frequency cards;
use_minute_data: true
is already the global default
Intraday/real-time/current/today/today's + whole market/sector + TopN/ranking/threshold list/stock selection/screening/signal
quick-snapshot
quick-window
quant-standard.md
→ Prioritize hitting "Real-time cross-section TopN ranking" or "Intraday threshold screening_list query" micro-process
Such high-frequency short questions have dedicated closed micro-processes
Given clear start and end dates, only ask interval cumulative price change/return
event-study
quick-window
quant-standard
period-return-compare.md
Essentially fixed interval return comparison, not causal window analysis, nor complex quantitative processes
Industry/sector aggregation ranking (e.g., "Top 5 price changes in Shenwan industries")
quick-window
quick-snapshot
quant-standard.md
Requires cross-section aggregation, not single-asset sequence
Threshold-triggered discrete event identification (e.g., "Number of times price change exceeds X%", ask about performance after each time)
event-study.md
(threshold trigger mode)
Need to identify threshold event dates first, then do window analysis
Continuous interval defined by threshold conditions (e.g., "Historical bear markets" "Phases with drawdown over 30%")
event-study
regime-segmentation.md
Studies continuous phases rather than windows after discrete events
"Hit new high/low in recent N days" (without "first-time" modifier)Prohibit adding "not met yesterday" conditionJudge by current state (state check), formula only compares current value with N-day extremum of yesterdayOnly when the user explicitly mentions "first breakthrough/first breakdown" "newly added" "first time today" can the first-time trigger condition be added; see
quant-standard.md
for details
Judgment Mnemonics:
  • Clear start/end date + only ask interval value
    period-return-compare
    (fixed interval return comparison)
  • Has event + asks "performance in subsequent N days/months"
    event-study
    (causal window)
  • Has threshold condition + asks "performance after each occurrence"
    event-study
    (threshold trigger mode)
  • Has threshold condition + asks "performance within continuous phase/interval"
    regime-segmentation
    (continuous phase statistics)
If the user's request meets any of the following patterns, it should be prioritized as a quick data query task, and directly jump according to the following routing, without entering other workflows first:
Fast Path Conditions (All 3 Points Must Be Met to Take Fast Path; Otherwise Take Complete Link):
  • Number of assets ≤ 3
  • All target fields belong to the fast_query whitelist (price/valuation/financial/derived fields, see
    tools/fast_query.md
    ), no custom formulas/stock selection/ranking involved
  • Not a whole market cross-section query (not scenarios like "whole market ranking/top N stocks")
Quick Data Query Routing (Judge by Priority in Order, Stop at First Match):
  1. Time anchor is "latest N-day window/sequence" → Read
    workflows/fast-window.md
    if Fast Path conditions are met, otherwise
    workflows/global-rules-lite.md
    workflows/quick-window.md
  2. Time anchor is "latest reporting period" and fields are financial → Read
    workflows/fast-report-period.md
    if Fast Path conditions are met, otherwise
    workflows/global-rules.md
    workflows/quick-report-period.md
  3. User explicitly asks for "chart / K-line / trend with trading volume" → Directly load
    workflows/render-kline.md
  4. Others (clearly latest completed trading day's market/valuation/multi-asset comparison, and does not include semantics like today/today's/current/now/real-time/intraday/ranking/screening) → Read
    workflows/fast-snapshot.md
    if Fast Path conditions are met, otherwise
    workflows/global-rules.md
    workflows/quick-snapshot.md
The above routing does not require reading
workflows/quick-lookup.md
first.

关键红线速查(即使未读 global-rules.md 也必须遵守)

Key Red Line Quick Check (Must Comply Even Without Reading global-rules.md)

以下 4 条规则从 global-rules.md 摘录,优先级最高,对所有场景生效:
  1. 事件定义冻结:事件类型/范围必须逐字匹配用户原始措辞。用户说"年报/半年报"就只查年报和半年报,不得扩大到业绩预告/快报/季报;用户说"国务院或住建部"就只纳入该层级,不得扩大到央行/银保监会/地方政府。若认为用户定义可能遗漏,在回答末尾建议扩大,不得擅自扩大。
  2. evidence-only 回答:最终答案只输出本轮工具结果直接支持的数值、日期、排名、口径说明。未经工具验证,禁止默认输出宏观归因、政策归因、方向性判断("通常""往往""偏正面")。
  3. 去过程化交付:禁止「已成功获取」「让我来」「按照流程」「Step 1/2/3」「根据 workflow」等过程性话术;禁止泄露
    _working/
    路径、checkpoint 名称、workflow 文件名。查到即答,不展示内部过程。
  4. 条件口径冻结:用户条件必须原样执行,禁止任何改写(百分比↔小数、相对时间→年份区间、资产宇宙替换、卡片附加条件继承)。详见硬规则第 6 条。
触发词参考:
  • 最近交易日收盘 / 最新已披露PE / 最新市值(非盘中、非筛选) →
    quick-snapshot
  • 最近5日 / 最近20个交易日 / 近N日序列 / 窗口最高最低 →
    quick-window
  • 营收 / 净利润 / ROE / 总资产 / 总负债 / 资产负债率 →
    quick-report-period
禁止:
  • 优先调用
    scanDimensions
    renderKLine
    (除非用户明确要看图)
  • 先做分析性扩写,再补充结构化数值
  • 在读取对应 leaf workflow 之前直接调用
    runMultiFormulaBatch
    /
    renderKLine
    /
    scanDimensions
    / 输出"无法联网"或"无法获取实时数据"
  • 把卡片附加条件(首次/非ST/封板/流动性门槛等)默默继承进最终答案
  • description
    samples
    、预览行、截断大表作为名单题的完整结果直接收尾(必须提取完整名单或明确声明不完整)
leaf workflow 最终回答合同优先:leaf workflow 中的"最终回答合同"优先负责收紧该场景的输出格式;若 leaf workflow 已满足停止条件,必须直接按该合同输出,不得再解释内部过程。
The following 4 rules are extracted from global-rules.md, highest priority, effective for all scenarios:
  1. Freeze Event Definition: Event type/scope must match the user's original wording word by word. If the user says "annual report/semi-annual report", only check annual and semi-annual reports, do not expand to performance forecasts/express/quarterly reports; if the user says "State Council or Ministry of Housing and Urban-Rural Development", only include this level, do not expand to central bank/CBRC/local governments. If you think the user's definition may be missing, suggest expanding at the end of the answer, do not expand without permission.
  2. Evidence-only Answer: The final answer only outputs values, dates, rankings, and caliber descriptions directly supported by the current round of tool results. Without tool verification, prohibit default output of macro attribution, policy attribution, directional judgments ("usually" "often" "positive bias").
  3. Process-free Delivery: Prohibit process statements such as "Successfully obtained" "Let me do this" "According to the process" "Step 1/2/3" "According to workflow"; prohibit disclosing
    _working/
    path, checkpoint name, workflow file name. Answer immediately after querying, do not show internal processes.
  4. Freeze Condition Caliber: User conditions must be executed as-is, prohibit any rewriting (percentage ↔ decimal, relative time → year range, asset universe replacement, card additional condition inheritance). See Rule 6 of Hard Rules for details.
Trigger Word References:
  • Latest trading day close / latest disclosed PE / latest market capitalization (non-intraday, non-screening) →
    quick-snapshot
  • Latest 5 days / latest 20 trading days / latest N-day sequence / window high/low →
    quick-window
  • Operating income / net profit / ROE / total assets / total liabilities / asset-liability ratio →
    quick-report-period
Prohibited:
  • Prioritize calling
    scanDimensions
    ,
    renderKLine
    (unless the user explicitly wants to see charts)
  • First do analytical expansion, then supplement structured values
  • Before reading the corresponding leaf workflow directly call
    runMultiFormulaBatch
    /
    renderKLine
    /
    scanDimensions
    / output "unable to connect to the internet" or "unable to obtain real-time data"
  • Silently inherit card additional conditions (first-time/non-ST/limit-up/liquidity threshold, etc.) into the final answer
  • Use
    description
    ,
    samples
    , preview lines, truncated large tables as the complete result of list questions directly (must extract the complete list or clearly state it is incomplete)
Leaf Workflow Final Answer Contract Priority: The "final answer contract" in the leaf workflow is responsible for tightening the output format of the scenario; if the leaf workflow has met the stop condition, must output directly according to the contract, do not explain internal processes again.

执行权授权规则

Execution Authority Authorization Rules

规则层级(从高到低):
  1. SKILL.md:路由 + 全局门禁(硬规则 4 条、路由硬排除)
  2. global-rules.md:所有 leaf 必须遵守的全局合同(执行合同、证据分级、简答模式、不补精度、方法限制说明、参数规范、数值精度、终答一致性检查)
  3. leaf workflow:当前任务的具体执行流程(checkpoint、模板、停止条件、格式化)
冲突解决
  • leaf workflow 中的具体规则(如 readData 模式选择)优先于 global-rules 的一般规则
  • 但 leaf workflow 不得放宽 global-rules 的红线(如证据分级门槛、不补精度原则)
  • 不得从其他 leaf workflow 借用模板、fallback 或回答格式
quick-lookup.md 的定位
  • 仅作为快查子流程的路由入口和规则参考总表
  • 各 leaf workflow 已自包含所有执行规则,执行时无需回到 quick-lookup.md
  • quick-lookup.md 不定义任何 leaf 独有规则
Rule Hierarchy (From Highest to Lowest):
  1. SKILL.md: Routing + Global Access Control (4 Hard Rules, Routing Hard Exclusions)
  2. global-rules.md: Global contracts that all leaves must comply with (execution contract, evidence classification, short answer mode, no precision supplement, method restriction description, parameter specification, numerical precision, final answer consistency check)
  3. leaf workflow: Specific execution process for the current task (checkpoint, template, stop condition, formatting)
Conflict Resolution:
  • Specific rules in leaf workflows (such as readData mode selection) take precedence over general rules in global-rules
  • But leaf workflows cannot relax the red lines in global-rules (such as evidence classification thresholds, no precision supplement principle)
  • Cannot borrow templates, fallbacks, or answer formats from other leaf workflows
Positioning of quick-lookup.md:
  • Only serves as the routing entry and rule reference summary table for quick query sub-processes
  • Each leaf workflow already contains all execution rules, no need to return to quick-lookup.md during execution
  • quick-lookup.md does not define any leaf-specific rules

全局执行规则

Global Execution Rules

全局合同详见
workflows/global-rules.md
,进入任何 leaf workflow 时自动生效。
leaf workflow 可在其内部添加更严格的约束,但不得豁免或放宽 global-rules 中的规则。
Global contracts are detailed in
workflows/global-rules.md
, which take effect automatically when entering any leaf workflow.
Leaf workflows can add stricter constraints internally, but cannot exempt or relax rules in global-rules.

平台数据覆盖范围

Platform Data Coverage

✅ 支持⚠️ 有条件支持❌ 不支持(短期内不会支持)
A股个股(沪深主板/创业板/科创板/北交所)ETF / LOF / 场外基金(先以
confirmMultipleAssets
结果为准,能确认则正常执行;确认失败才告知不支持)
期货 / 期权
港股个股(HK + 代码,如 HK0001)台股 / 韩股 / 日股 / 德股等其他境外市场
美股个股(NASDAQ: 代码.N;NYSE: 代码.O;AMEX: 代码.A)
主要宽基指数(沪深300、中证500、万得全A等)
港股 / 美股数据范围限制:港股和美股目前仅支持行情价格类数据(收盘价、开盘价、最高价、最低价、涨跌幅、成交量、成交额)。估值数据(PE/PB/市值等)和财务数据(营收/净利润/ROE等)暂不支持。查询港股/美股的估值或财务字段时,应主动告知用户当前不支持,而不是静默跳过。
✅ Supported⚠️ Conditionally Supported❌ Not Supported (Will Not Be Supported in the Short Term)
A-share individual stocks (Shanghai/Shenzhen Main Board/GEM/STAR Market/Beijing Stock Exchange)ETF / LOF / OTC funds (first follow the result of
confirmMultipleAssets
, execute normally if confirmed; inform not supported only if confirmation fails)
Futures / Options
H-share individual stocks (HK + code, e.g., HK0001)Taiwan stocks / Korean stocks / Japanese stocks / German stocks and other overseas markets
U.S. stocks (NASDAQ: code.N; NYSE: code.O; AMEX: code.A)
Major broad-based indices (CSI 300, CSI 500, Wind All A, etc.)
Data Scope Limitation for H-shares/U.S. Stocks: Currently, H-shares and U.S. stocks only support market price data (closing price, opening price, high price, low price, price change percentage, trading volume, turnover amount). Valuation data (PE/PB/market capitalization, etc.) and financial data (operating income/net profit/ROE, etc.) are not supported yet. When users query valuation or financial fields for H-shares/U.S. stocks, actively inform users that it is not currently supported instead of silently skipping.

股票代码格式速查

Stock Code Format Quick Reference

市场格式示例
A股-上交所SH + 代码SH600000
A股-深交所SZ + 代码SZ000001
港股HK + 代码HK0001
美股-NASDAQ代码.NAAPL.N
美股-NYSE代码.OAAL.O
美股-AMEX代码.ASBE.A
确认资产失败(熔断规则)详见
workflows/quick-lookup.md
§ Step 1。
环境依赖(Python版本、Playwright、API Key)→
references/environment.md
故障排查 →
references/troubleshooting.md
RU 计费 →
references/ru-billing.md

MarketFormatExample
A-share - Shanghai Stock ExchangeSH + codeSH600000
A-share - Shenzhen Stock ExchangeSZ + codeSZ000001
H-shareHK + codeHK0001
U.S. Stock - NASDAQcode.NAAPL.N
U.S. Stock - NYSEcode.OAAL.O
U.S. Stock - AMEXcode.ASBE.A
See
workflows/quick-lookup.md
§ Step 1 for asset confirmation failure (circuit breaker rules).
Environment dependencies (Python version, Playwright, API Key) →
references/environment.md
Troubleshooting →
references/troubleshooting.md
RU billing →
references/ru-billing.md

前置条件(按需执行,不是简单查数的默认首步)

Prerequisites (Execute on Demand, Not the Default First Step for Simple Data Queries)

凭据存储说明:本 skill 的 quant-buddy API Key 只存放在 skill 目录下的
config.json
api_key
字段
,不使用环境变量(
QUANT_BUDDY_API_KEY
等环境变量不会被读取)。仅可选的
BOCHA_API_KEY
(事件新闻搜索)走环境变量。
仅在以下情形下,才需要显式读取
config.json
检查
api_key
  • 本轮实际需要调用本地脚本或平台工具,且当前环境尚未建立可用 session
  • 上一轮工具调用已出现 401 / 402 / 明确认证错误
  • workflow 明确要求执行脚本链(如本地 Python 脚本渲染)
对已命中 leaf workflow 的简单查数题(quick-snapshot / quick-window / quick-report-period / render-kline):
  • 不要为了形式完整额外读取
    config.json
  • 优先直接按 leaf workflow 执行
  • 仅当工具调用出现明确认证问题时,再回到认证向导
原则:认证检查服务于执行,不应成为简单题的固定额外步骤。
  • api_key
    非空 → 正常继续
  • api_key
    为空立即停止,禁止继续查数,输出以下新用户引导消息(原样输出,不得删减):

    ⚠️ 尚未配置 API Key,当前无法查询数据。
    前往 https://www.quantbuddy.cn/login 登录/注册并获取 API Key,然后直接发给我:
    帮我配置 APIkey:sk-xxxxxxxx


Credential Storage Instructions: The quant-buddy API Key of this skill is only stored in the
api_key
field of
config.json
under the skill directory
, environment variables (such as
QUANT_BUDDY_API_KEY
) are not read. Only the optional
BOCHA_API_KEY
(event news search) uses environment variables.
Only in the following cases do you need to explicitly read
config.json
to check
api_key
:
  • This round actually needs to call local scripts or platform tools, and no available session has been established in the current environment
  • The previous round of tool calls has returned 401 / 402 / explicit authentication errors
  • Workflow explicitly requires executing script chains (such as local Python script rendering)
For simple data query questions that have hit leaf workflows (quick-snapshot / quick-window / quick-report-period / render-kline):
  • Do not read
    config.json
    additionally just for formality
  • Prioritize executing directly according to the leaf workflow
  • Only return to the authentication wizard when tool calls have explicit authentication issues
Principle: Authentication checking serves execution, and should not be a fixed additional step for simple questions.
  • If
    api_key
    is non-empty → Proceed normally
  • If
    api_key
    is emptyStop immediately, prohibit continuing data query, output the following new user guide message (output as-is, do not delete or modify):

    ⚠️ API Key has not been configured, data query is not available currently.
    Go to https://www.quantbuddy.cn/login to log in/register and obtain an API Key, then send it to me directly:
    Help me configure APIkey: sk-xxxxxxxx


配置向导(用户粘贴 Key)

Configuration Wizard (User Pastes Key)

当用户消息中包含
sk-
开头的字符串时:
  1. 从用户消息中提取
    sk-
    开头的完整 Key 字符串
  2. 将 Key 写入
    config.json
    api_key
    字段(用
    replace_string_in_file
    直接写入)
  3. 必须输出:「✅ API Key 配置成功!」
  4. 自动重试:若本对话中有被 api_key 缺失错误中断的查询(如之前用户问过行情),先调
    newSession
    (以原始用户问题作为
    user_query
    )新建 session
    ,再立即重新执行该查询并给出数据结论,不需要用户再次发起。
运行时 401/402 → 立即停止,提示用户 API Key 无效/过期/配额耗尽,请重新前往官网获取新的 Key 并重新配置。

When the user's message contains a string starting with
sk-
:
  1. Extract the complete Key string starting with
    sk-
    from the user's message
  2. Write the Key into the
    api_key
    field of
    config.json
    (write directly using
    replace_string_in_file
    )
  3. Must output: "✅ API Key configured successfully!"
  4. Automatic Retry: If there is a query interrupted by api_key missing error in this conversation (e.g., the user asked about market data before), first call
    newSession
    (use the original user question as
    user_query
    ) to create a new session
    , then immediately re-execute the query and give the data conclusion, no need for the user to initiate it again.
Runtime 401/402 → Stop immediately, prompt the user that the API Key is invalid/expired/quota exhausted, please go to the official website to obtain a new Key and reconfigure.

工具调用方式

Tool Calling Method

所有工具通过
scripts/call.py
调用。
call.py
会同时将结果打印到 stdout 和写入临时文件。
All tools are called through
scripts/call.py
.
call.py
will print the result to stdout and write it to a temporary file at the same time.

标准调用(一步完成)

Standard Call (One Step to Complete)

bash
python scripts/call.py <工具名> '{"key":"value"}'
结果直接从 stdout 获取。若 stdout 被截断,可回读
/tmp/gzq_out.txt
也可通过环境变量传参(适用于参数含特殊字符的场景):
bash
GZQ_PARAMS='<JSON>' python scripts/call.py <工具名>
bash
python scripts/call.py <tool name> '{"key":"value"}'
Results are obtained directly from stdout. If stdout is truncated, you can read back
/tmp/gzq_out.txt
.
You can also pass parameters through environment variables (suitable for scenarios where parameters contain special characters):
bash
GZQ_PARAMS='<JSON>' python scripts/call.py <tool name>

禁止事项

Prohibited Items

禁止原因
创建自定义 .py 写参数文件环境变量方案已解决编码问题
直接调用
scripts/executor.py
call.py
封装了 renderChart 自动保存等逻辑
echo
管道传参(Windows)
GBK 编码截断中文
命令行参数传 JSON(Windows)PS 吃掉双引号

ProhibitedReason
Create custom .py to write parameter filesEnvironment variable scheme has solved encoding issues
Directly call
scripts/executor.py
call.py
encapsulates logic such as automatic saving for renderChart
echo
pipe parameter passing (Windows)
GBK encoding truncates Chinese
Command line parameter passing JSON (Windows)PS eats double quotes

presets/、recipes/、tools/ 三个目录的分工

Division of Labor Among presets/, recipes/, tools/ Directories

目录是什么何时读
presets/平台实际返回值的本地快照(YAML)。资产名、函数格式、数据集 index_title、行业/概念名等。直接可用于公式,省掉确认类 API 调用。写公式前先查 preset;找不到再调对应 API,并把新结果补回 preset。
cases_index.yaml
仅在选股/回测/因子/图表等量化标准场景
quant-standard.md
)开始时必读;快速查数场景(quick-snapshot/window/report-period)无需读取。
recipes/端到端使用示例(Markdown)。展示完整场景——从参数准备到最终输出。由 workflow 在具体步骤中指引加载(不独立触发)。
tools/API 参数手册(Markdown)。每个工具的字段、类型、约束。默认不读。workflow 工具表标注了「必读」或报错时再查。
简言之:presets 是数据快照,recipes 是完整教程,tools 是参数字典。 presets 6 个文件的详细用法和加载时机→ 当前 workflow 文档内的「预设资源」表。

DirectoryWhat It IsWhen to Read
presets/Local snapshots of actual platform return values (YAML). Asset names, function formats, dataset index_title, industry/concept names, etc. Can be directly used in formulas, saving confirmation API calls.Check preset before writing formulas; call the corresponding API only if not found, and add the new result back to preset.
cases_index.yaml
must be read at the beginning only in quantitative standard scenarios (stock selection/backtesting/factors/charts, etc.,
quant-standard.md
); not needed for quick data query scenarios (quick-snapshot/window/report-period).
recipes/End-to-end usage examples (Markdown). Show complete scenarios — from parameter preparation to final output.Loaded as guided by workflows in specific steps (not triggered independently).
tools/API parameter manuals (Markdown). Fields, types, constraints for each tool.Do not read by default. Read only when workflows mark "must read" or when errors occur.
In short: presets are data snapshots, recipes are complete tutorials, tools are parameter dictionaries. Detailed usage and loading timing of the 6 preset files → "Preset Resources" table in the current workflow document.

Skill 更新部署规范(LLM 必读)

Skill Update Deployment Specifications (Must Read for LLM)

当用户要求更新本 skill(发送 zip 压缩包)时,必须严格遵守以下规则:
When the user requests to update this skill (sends a zip package), must strictly comply with the following rules:

备份位置

Backup Location

⚠️ 备份目录禁止放在
skills/
目录下。
否则 openclaw 会把备份也识别为一个独立 skill,导致后续请求可能误用旧版代码。
正确做法:
bash
undefined
⚠️ Backup directory is prohibited from being placed under the
skills/
directory.
Otherwise, openclaw will recognize the backup as an independent skill, leading to possible misuse of old code in subsequent requests.
Correct approach:
bash
undefined

备份到 skills/ 之外的位置

Backup to a location outside skills/

cp -r ~/.openclaw/workspace/skills/quant-buddy-skill ~/.openclaw/workspace/quant-buddy-skill-backup-$(date +%Y%m%d%H%M)
cp -r ~/.openclaw/workspace/skills/quant-buddy-skill ~/.openclaw/workspace/quant-buddy-skill-backup-$(date +%Y%m%d%H%M)

❌ 错误:备份仍在 skills/ 下

❌ Wrong: Backup is still under skills/

cp -r ~/.openclaw/workspace/skills/quant-buddy-skill ~/.openclaw/workspace/skills/quant-buddy-skill-backup-xxx

cp -r ~/.openclaw/workspace/skills/quant-buddy-skill ~/.openclaw/workspace/skills/quant-buddy-skill-backup-xxx

undefined
undefined

解压覆盖

Unzip and Overwrite

bash
undefined
bash
undefined

解压到临时目录再拷贝(避免嵌套)

Unzip to temporary directory first then copy (avoid nesting)

TMPDIR=$(mktemp -d) unzip -o <压缩包路径> -d "$TMPDIR"
TMPDIR=$(mktemp -d) unzip -o <zip package path> -d "$TMPDIR"

如果解压出嵌套目录 quant-buddy-skill/,取内层

If unzipped to nested directory quant-buddy-skill/, take the inner layer

if [ -d "$TMPDIR/quant-buddy-skill" ]; then cp -rf "$TMPDIR/quant-buddy-skill/"* ~/.openclaw/workspace/skills/quant-buddy-skill/ else cp -rf "$TMPDIR/"* ~/.openclaw/workspace/skills/quant-buddy-skill/ fi rm -rf "$TMPDIR"
undefined
if [ -d "$TMPDIR/quant-buddy-skill" ]; then cp -rf "$TMPDIR/quant-buddy-skill/"* ~/.openclaw/workspace/skills/quant-buddy-skill/ else cp -rf "$TMPDIR/"* ~/.openclaw/workspace/skills/quant-buddy-skill/ fi rm -rf "$TMPDIR"
undefined

部署后检查

Post-Deployment Check

  1. 确认
    ~/.openclaw/workspace/skills/
    下只有
    quant-buddy-skill/
    一个与本 skill 相关的目录
  2. 读取
    SKILL.md
    确认版本号
  3. 保留
    config.json
    中已有的
    api_key
    (若用户之前已认证过)
  1. Confirm there is only one directory related to this skill,
    quant-buddy-skill/
    , under
    ~/.openclaw/workspace/skills/
  2. Read
    SKILL.md
    to confirm the version number
  3. Keep the existing
    api_key
    in
    config.json
    (if the user has authenticated before)