Skip to content
Back to search

x2strategy

Extract structured strategy specifications from quantitative finance research papers — Agent Skill for GitHub Copilot & Claude Code

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/alagent-hku--x2strategy/badge.svg)](/listings/alagent-hku--x2strategy)

HTML

<a href="/listings/alagent-hku--x2strategy"><img src="/api/listings/alagent-hku--x2strategy/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

As an Agent Skill

[Agent Skills](https://agentskills.io/) is an open standard. Clone into the agent's skill directory — it auto-discovers `SKILL.md` and registers the `/x2strategy` slash command.

Install to OpenClaw / OpenClaw Users

For OpenClaw users, install directly from ClawHub:

openclaw skills install patrick-lew/x2strategy

Or use the ClawHub CLI:

npx clawhub@latest install x2strategy

For remote or guided setup, paste this prompt into OpenClaw:

Install the skill "X2strategy" (patrick-lew/x2strategy) from ClawHub.
Skill page: https://clawhub.ai/patrick-lew/x2strategy
Keep the work scoped to this skill only.
After install, inspect the skill metadata and help me finish setup.
Use only the metadata you can verify from ClawHub; do not invent missing requirements.
Ask before making any broader environment changes.

Install to Claude Code / Codex / Copilot

<table> <tr><td><b>GitHub Copilot</b></td><td>

git clone https://github.com/ALAGENT-HKU/x2strategy.git ~/.copilot/skills/x2strategy

</td></tr> <tr><td><b>Claude Code</b></td><td>

git clone https://github.com/ALAGENT-HKU/x2strategy.git ~/.claude/skills/x2strategy

</td></tr> <tr><td><b>Project-scoped</b></td><td>

git clone https://github.com/ALAGENT-HKU/x2strategy.git .github/skills/x2strategy

</td></tr> </table>

Then install dependencies. After successful skill installation, the agent may auto-install them during initialization, but manual setup is the most predictable path:

cd ~/.copilot/skills/x2strategy   # or wherever you cloned
# if you haven't installed uv, run `pip install uv`
uv sync --all-extras

<details> <summary>Manual dependency variants</summary>

# minimum skill runtime
uv sync --extra agent --extra codegen

# add DOCX parsing support
uv sync --extra agent --extra codegen --extra docx

# pip alternative
python -m venv .venv && source .venv/bin/activate
pip install -e ".[codegen,agent,docx,dev]"

</details>

> [!IMPORTANT] > The directory name **must** be `x2strategy` (matching the `name` field in `SKILL.md`). Once installed, type `/x2strategy` in chat or the agent auto-activates when relevant.

Skill Quick Start

# 1. Configure the skill workspace
cp .env.example .env          # add your API key (DEEPSEEK_API_KEY recommended)

# 2. Start the skill in your agent
# /x2strategy

Then ask for work in natural language, for example:

> *"Analyze this paper and implement the main strategy."* + attach a PDF + optional data files + optional clarification/user-customization prompts such as *"When the paper underspecifies a formula, you can either explicitly ask me or refer to the sample_instruction.md file."*

The skill handles parsing, extraction, code generation, validation, backtesting, and diagnosis. Before extraction, it should ask whether you want to add custom instructions, implementation constraints, known pitfalls, or reference files. After extraction and strategy/plan selection, it must read [references/extraction_quality.md](references/extraction_quality.md) before any repair, code generation, or deterministic local implementation. It should also use the same interactive flow when you pick search results, add repair-time pitfall notes or clarifications, approve inferred defaults, or resolve any `needs_human_review` items surfaced by compare/repair. After code generation and diagnosis, it should present an interactive next-action menu instead of assuming the workflow is finished.

Generated files should be written under `PAPER2SPEC_LIBRARY_PATH/<slug>/` by default, for example `content.json`, `spec.json`, the generated implementation file, and `results/metrics.json`. If a referenced Copilot/VS Code log path is empty or incomplete, regenerate the artifacts from the original paper, instructions, and data instead of relying on the log summary.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 325 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: x2strategy
  3. description: >
  4. ALAGENT X2Strategy: any research input (PDF paper, Markdown draft,
  5. DOCX report, text notes, or keyword search) → structured strategy
  6. specification → executable Backtrader code → backtest → diagnosis report.
  7. Two core capabilities: (1) paper2spec extracts multi-strategy specs from
  8. any document via 5-layer LLM extraction, and (2) spec2code generates
  9. validated Backtrader code, runs backtests, and compares against paper
  10. metrics. Use this skill whenever the user wants to analyze a quant paper,
  11. extract trading strategies, generate strategy code, run a backtest, search
  12. for papers, or go end-to-end from any input to executable results. Also
  13. triggers on: "look at this paper", "what strategies does this use",
  14. "implement this strategy", "search for momentum papers", "turn this into
  15. code", or any request about quantitative finance research → implementation.
  16. Even if the user doesn't mention "strategy" explicitly — if they provide a
  17. finance paper or research document, use this skill.
  18. argument-hint: "[paper.pdf | strategy.md | report.docx | search query]"
  19. metadata:
  20. version: 0.6.1
  21. author: ALAGENT AI (alagent-ai)
  22. tags: [quantitative-finance, paper-parsing, strategy-extraction, code-generation, backtesting]
  23. ---
  24. # X2Strategy
  25. Any finance-related input → Strategy spec → Executable code → Backtest → Diagnosis.
  26. ## Capabilities
  27. | Capability | What it does | Deep dive |
  28. |-----------|-------------|-----------|
  29. | **paper2spec** | Any document (PDF/MD/DOCX/TXT) → structured strategy specification | [references/paper2spec.md](references/paper2spec.md) |
  30. | **spec2code** | Strategy spec → Backtrader code → validate → backtest → diagnosis | [references/spec2code.md](references/spec2code.md) |
  31. Input format auto-detected from extension:
  32. | Format | Extension | Notes |
  33. |--------|-----------|-------|
  34. | PDF (papers) | `.pdf` | PyMuPDF → Mode A (direct) or Mode B (FAISS) |
  35. | Markdown (drafts) | `.md`, `.markdown` | Direct text read |
  36. | DOCX (reports) | `.docx` | python-docx (requires `uv sync --extra docx`) |
  37. | Plain text | `.txt` | Direct read |
  38. ---
  39. ## Interaction Principles
  40. **You are the executor. The user is the requester.**
  41. - Run tools silently, present results and insights in natural language.
  42. - Never show CLI commands (`uv run python scripts/...`) unless user asks.
  43. - Offer next actions conversationally: "Would you like me to implement the second strategy as well?"
  44. When reporting results, focus on **what you found**, not how:
  45. ```
  46. ❌ Bad: "I ran `uv run python scripts/analyze.py paper.pdf` and got 3 strategies."
  47. ✅ Good: "This paper contains 3 independent strategies: [1] minimum distance method, [2] ADF stationarity, and [3] Johansen cointegration. Which one should I implement?"
  48. ```
  49. **Use interactive tools aggressively.** When your platform provides
  50. interactive question tools — `vscode_askQuestions` (VS Code Copilot),
  51. `AskUserQuestion` (Claude Code), or equivalent — use them for ALL
  52. user-facing choices. Interactive tools present clickable options,
  53. which is faster and less error-prone than asking the user to type.
  54. Apply interactive tools to:
  55. - First-Run Setup choices (workspace path, API provider, key input)
  56. - Input confirmation (proceed / add clarification / adjust settings)
  57. - Review checkpoints and implementation approval
  58. - `needs_human_review` resolution after extraction or repair
  59. - Search result selection (pick papers from a numbered list)
  60. - Any scenario where the user picks from options
  61. If no interactive tool is available, fall back to numbered text menus.
  62. ### Progress Marker Protocol
  63. Run tools silently, but make long pipelines **traceable**. While working through
  64. the eight-step workflow, prefix status lines with one of three structured
  65. markers so the user (and any outer parser) can follow phase progress without
  66. reading raw command output. The markers carry the discipline; the surrounding
  67. prose stays natural-language.
  68. | Marker | When to emit | Format |
  69. |--------|-------------|--------|
  70. | `[PROGRESS]` | Entering or finishing a workflow step | `[PROGRESS] <step> — <one-line status>` |
  71. | `[ARTIFACT]` | A concrete file was written | `[ARTIFACT] <workspace-relative-path> — <what it is>` |
  72. | `[ERROR]` | A step failed or a check did not pass | `[ERROR] <step> — <what failed> — <next action>` |
  73. Rules:
  74. - One marker per line, at the start of the line, then plain language.
  75. - Every `[ARTIFACT]` must name a concrete workspace-relative path that was
  76. actually written (this satisfies the Output Paths contract below).
  77. - `[ERROR]` must always be followed by what you will do next (retry once,
  78. stop and report, ask the user) — never a bare failure.
  79. - Markers supplement natural-language reporting; they do not replace it. Still
  80. explain *what you found*, not *how you ran it*. Never show the CLI command.
  81. Example:
  82. ```
  83. [PROGRESS] paper2spec/extract — extracting strategy specs from content.json
  84. [ARTIFACT] library/upsa/spec.json — 1 strategy, 4 indicators, 3 logic steps
  85. [PROGRESS] HITL review — 1 open needs_human_review item, asking for resolution
  86. ```
  87. ### Iteration & Retry Discipline
  88. Generation and repair must be bounded. Translate the backend's hard turn gate
  89. (`--max-turns`) into agent discipline:
  90. - **Generate once, then at most one smoke-test repair round.** Write the code,
  91. validate, run. If it fails, apply one targeted fix round (see the triage flow
  92. in [references/spec2code.md](references/spec2code.md)) and re-run.
  93. - **If it still fails after that one repair round, stop and report.** Emit an
  94. `[ERROR]` line, summarize what failed and the most likely root cause, and ask
  95. the user how to proceed. Do not keep patching incrementally.
  96. - **A single runtime-error category gets at most 3 fix attempts.** If the same
  97. error class persists, the strategy logic likely needs a fundamentally
  98. different approach — say so rather than tweaking further.
  99. - Never silently loop. Each retry must be visible via a `[PROGRESS]` or
  100. `[ERROR]` marker so the user can see the gate working.
  101. ### First Response Contract
  102. For any paper2code, research-to-code, or “use this skill” request, the first response must not promise immediate implementation. First identify the visible inputs, then use an interactive dialog to confirm setup status, input files, extra instructions/clarifications, and intended workflow scope. Only proceed after that confirmation.
  103. ---
  104. ## First-Run Setup
  105. On first use, walk through three steps. If a step is already configured, report the detected value and ask the user to confirm or change it. Always confirm task scope before extraction or implementation. Persist all choices to `.env` (gitignored) for session stability.
  106. ### Step 1 — Workspace Location
  107. Present choice via interactive tool:
  108. - `./library/` (default, recommended)
  109. - Custom path
  110. Write `PAPER2SPEC_LIBRARY_PATH=/absolute/path` to `.env`.
  111. Scan the directory for existing `metadata.json` to detect prior analyses.
  112. ### Step 2 — LLM API Key
  113. Check env for `DEEPSEEK_API_KEY`, `OPENROUTER_API_KEY`, `OPENAI_API_KEY`,
  114. or `ANTHROPIC_API_KEY`.
  115. If none found, present via interactive tool:
  116. ```
  117. An LLM API key is required for strategy extraction and code generation. Recommended options:
  118. 1. DeepSeek (best cost-performance, about ¥0.7 per paper) → https://platform.deepseek.com
  119. 2. OpenRouter (one key for access to multiple models) → https://openrouter.ai/keys
  120. Please provide your API key and tell me which provider it belongs to.
  121. ```
  122. Once received, write key + matching model to `.env`, then verify:
  123. `uv run python -c "from paper2spec.llm import chat; print(chat('Say OK'))"`.
  124. See [references/skill-internals.md](references/skill-internals.md) for
  125. `.env` format examples per provider.
  126. ### Step 3 — Python Environment
  127. ```bash
  128. cd <skill-path>
  129. uv sync --all-extras # Recommended: installs everything
  130. ```
  131. If `uv` unavailable: `pip install -e ".[codegen,agent,dev]"`.
  132. Always use `uv run` to execute scripts (auto-activates correct venv).
  133. See [references/skill-internals.md](references/skill-internals.md) for
  134. selective install options and non-uv alternatives.
  135. ### Completion
  136. Once configured, confirm naturally with examples:
  137. ```
  138. ✅ Setup complete. You can now ask me for tasks directly, for example:
  139. • "Analyze this paper" + attach a PDF file
  140. • "Search for papers about momentum trading"
  141. • "Implement this strategy based on this paper" + provide the file path
  142. • "I wrote a strategy draft in Markdown; extract the spec and generate code"
  143. • "Compare the strategy differences between these two papers"
  144. Just tell me what you want to do, and I will handle the rest.
  145. ```
  146. ---
  147. ## Single Workflow
  148. Use one workflow for all tasks. Do not choose between competing routers.
  149. 1. **Setup** — verify `.env`, library path, API key if needed, Python environment, and user-selected scope.
  150. 2. **Input confirmation** — identify the paper/spec/data/instruction files or search results; ask whether to add clarification, constraints, selected-plan preferences, known pitfalls, or reference files.
  151. 3. **paper2spec: PDF/text to content** — parse the selected document into grounded content artifacts.
  152. 4. **paper2spec: extract** — extract candidate strategy specs/plans from the content plus user instructions.
  153. 5. **paper2spec: repair/review** — read `references/extraction_quality.md`, retrieve relevant operator pitfalls when high-risk formulas are present, and repair only the selected plan/spec with grounded evidence.
  154. 6. **HITL review** — after repair, always inspect `needs_human_review`. If any item exists, present it through the interactive dialog and do not continue until answered or explicitly accepted. If none exists, still report that review found no open items and ask for implementation approval.
  155. 7. **spec2code** — after HITL approval, confirm the implementation target and generate code for that target.
  156. 8. **Validation/backtest/diagnosis** — validate generated code, run available checks/backtests, compare against expected or reference outputs, summarize mismatches, then ask what to do next.
  157. No bypass: never silently chain extraction → repair → implementation. User-provided papers, instructions, data files, existing specs, or reference outputs are evidence, not permission to skip review or HITL.
  158. When previous Copilot, VS Code, or agent logs are mentioned, verify that the referenced path exists and contains the needed files before using them. If the path is missing, empty, or incomplete, regenerate the required artifacts from the original paper/instructions/data instead of relying on the log summary.
  159. ## Output Paths
  160. Default generated artifacts go under `PAPER2SPEC_LIBRARY_PATH/<slug>/`, where `<slug>` is the paper or task slug confirmed with the user. If a custom output path is requested, confirm it before writing files.
  161. Expected artifact paths:
  162. - `content.json` and `content.md` from paper2spec parsing
  163. - `spec.json` and `spec.md` from extraction and repair
  164. - `operator_pitfall_context.md` when pitfall retrieval is used
  165. - `strategy.py`, `strategy_1.py`, or the user-confirmed implementation filename from spec2code
  166. - `data/` for any data used by generated strategy code
  167. - `results/backtest_output.txt`, `results/metrics.json`, and `results/diagnosis_report.md` from validation/backtest/diagnosis
  168. - `results/portfolio_vs_assets.csv` and `results/portfolio_vs_assets.png` comparing the strategy portfolio value against same-capital buy-and-hold curves for every used equity/ETF/asset in one image; asset curves must use distinguishable colors and symbol labels/legend entries, and SPY and portfolio must be boldface (comparing same-parameter portfolio curves at 0%, 0.01%, and 0.05% commission in one image)
  169. - `results/key_pred/` with one CSV and one PNG per key observerable factors used by the strategy
  170. Every status update after file generation should name the concrete workspace-relative path that was written.
  171. ## Spec2Code Metrics
  172. For every runnable strategy, spec2code should compute and report at least: Sharpe ratio, maximum drawdown, total return, and return value/final portfolio value. If a strategy is not runnable as a broker-connected strategy, report why and still compute the metrics that are meaningful for the confirmed research/backtest contract.
  173. Spec2Code-generated code must cache all network data locally, save headless-safe visual diagnostics, plot all used asset prices together, compare the strategy account value against same-capital buy-and-hold curves for all used assets, include a 0% / 0.01% / 0.05% commission equity-curve comparison for trading strategies, and include a combined portfolio-vs-assets chart where all three commission portfolio curves are plotted with all asset buy-and-hold
  174. curves.
  175. For US equity strategies, SPY must be included and highlighted as the market baseline in asset and portfolio-vs-assets plots. See [references/spec2code.md](references/spec2code.md) and [references/data_sources.md](references/data_sources.md) for the required data cache and visualization contract.
  176. ---
  177. ## Agent Pipeline Flow
  178. ```
  179. 1. Setup: confirm environment, library path, keys if needed, and task scope
  180. 2. Confirm inputs: paper/spec/data/instructions/search result + clarifications
  181. 3. paper2spec: parse PDF/text/doc to content artifacts
  182. 4. paper2spec: extract candidate specs/plans
  183. 5. paper2spec: select target plan/spec and repair with extraction_quality + matched pitfalls
  184. 6. HITL: inspect needs_human_review and resolve through interactive dialog
  185. 7. spec2code: confirm output contract, generate code, validate, run checks/backtest
  186. 8. Diagnose results and ask next action
  187. ```
  188. For code generation patterns: [references/spec2code.md](references/spec2code.md)
  189. For Backtrader patterns: [references/backtrader_patterns.md](references/backtrader_patterns.md)
  190. ---
  191. ## Internal Toolchain
  192. Agent-only. Run silently; present results in natural language.
  193. ```bash
  194. # Document → spec
  195. uv run python scripts/analyze.py <file> -o library/<slug>/
  196. # Step-by-step paper2spec
  197. uv run python scripts/parse.py <file> -o content.json
  198. uv run python scripts/extract.py content.json -o spec.json
  199. # Matched operator-pitfall context for repair/review
  200. uv run python scripts/operator_pitfalls.py spec.json -o operator_pitfall_context.md
  201. # Validate generated code
  202. uv run python scripts/validate_strategy.py library/<slug>/strategy_1.py
  203. # Run backtest
  204. uv run python library/<slug>/strategy_1.py
  205. # Search papers
  206. uv run python scripts/search.py "<query>" -n 5
  207. ```
  208. For full flags, output formats, and library management:
  209. [references/skill-internals.md](references/skill-internals.md)
  210. ---
  211. ## Configuration
  212. | Variable | Default | Purpose |
  213. |----------|---------|---------|
  214. | `PAPER2SPEC_LIBRARY_PATH` | `./library` | Output root |
  215. | `PAPER2SPEC_MODEL` | `openai/gpt-4o-mini` | Default LLM ([litellm-supported](https://docs.litellm.ai/docs/providers)) |
  216. | `DEEPSEEK_API_KEY` | — | DeepSeek (recommended) |
  217. | `OPENROUTER_API_KEY` | — | OpenRouter (multi-model) |
  218. | `OPENAI_API_KEY` | — | OpenAI direct |
  219. | `PAPER2SPEC_ARXIV_MIN_INTERVAL` | `3.0` | Seconds between arXiv requests |
  220. | `PAPER2SPEC_SEARCH_MAX_RETRIES` | `3` | Retry on HTTP 429/5xx |
  221. Any [litellm-supported model](https://docs.litellm.ai/docs/providers) works.
  222. The `--model` flag on any script overrides `PAPER2SPEC_MODEL`.
  223. Full config + .env examples: [references/skill-internals.md](references/skill-internals.md)
  224. ---
  225. ## References
  226. Read on demand for implementation details:
  227. - [references/paper2spec.md](references/paper2spec.md) — Parser modes, multi-strategy detection, output schemas
  228. - [references/extraction_quality.md](references/extraction_quality.md) — Mandatory review/repair and `needs_human_review` rules
  229. - [paper2spec/resources/operator_pitfall_index.md](paper2spec/resources/operator_pitfall_index.md) — Retrieval corpus for high-risk formula pitfalls
  230. - [references/spec2code.md](references/spec2code.md) — Code generation workflow, Backtrader patterns
  231. - [references/skill-internals.md](references/skill-internals.md) — Script flags, output formats, .env examples, library management, project structure
  232. - [references/backtrader_patterns.md](references/backtrader_patterns.md) — Strategy class, data loading, position sizing
  233. - [references/indicator_cookbook.md](references/indicator_cookbook.md) — Built-in and custom indicators
  234. - [references/data_sources.md](references/data_sources.md) — yfinance, akshare, FRED API
  235. ## Limitations
  236. - **Mode A** truncates at 100K chars (first 90K + last 10K). Use Mode B for >100 page papers.
  237. - **Tables/formulas**: not yet extracted from PDFs.
  238. - **Multi-strategy**: conservative — may merge borderline-distinct strategies.
  239. - **DOCX**: paragraph text only (tables, images not preserved — use PDF for rich docs).
  240. - **SSRN search**: best-effort HTML scraping, may break on layout changes.
README.md · README · 378 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <div align="center">
  2. <img src="assets/alagent_logo.png" alt="ALAGENT Logo" width="120">
  3. # X2Strategy
  4. **Any Research Input → Strategy Spec → Executable Code → Backtest → Diagnosis**
  5. [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue?logo=python&logoColor=white)](https://python.org)
  6. [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)
  7. [![Agent Skills](https://img.shields.io/badge/Agent_Skills-compatible-blueviolet?logo=visualstudiocode)](https://agentskills.io/)
  8. [![Tests](https://img.shields.io/badge/tests-180_passed-brightgreen)]()
  9. [![LiteLLM](https://img.shields.io/badge/LLM-any_provider-orange?logo=openai)](https://docs.litellm.ai/docs/providers)
  10. [Getting Started](#-getting-started) · [How It Works](#-how-it-works) · [Examples](#-examples) · [Docs](#-documentation) · [简体中文](README_CN.md)
  11. ---
  12. *Turn quantitative finance research — papers, drafts, reports, or strategy ideas — into validated, executable trading strategies. Automatically.*
  13. </div>
  14. ## Highlights
  15. - **🔬 Multi-Format Input** — PDF papers, Markdown drafts, DOCX reports, plain text. Auto-detected.
  16. - **🧠 5-Layer LLM Extraction** — Multi-strategy detection → indicators → signal logic → execution plan → risk controls.
  17. - **🧾 Grounded Extraction Quality** — Optional instruction/customization/clarification context, retrieved repair-time operator-pitfall checks, canonical `portfolio_weights`, and structured `needs_human_review` flags.
  18. - **✅ Verified Code Generation** — AST validation + Backtrader structural checks + indicator registry, not just "generate and hope".
  19. - **📊 Automated Backtesting** — Execute, extract metrics, and diagnose against paper-reported performance.
  20. - **🤖 Agent-Native** — Works as an [Agent Skill](https://agentskills.io/) (`/x2strategy`) in VS Code Copilot, Claude Code, or any compatible agent.
  21. - **💰 ~$0.1 per paper** — DeepSeek-powered. Any [LiteLLM-supported provider](https://docs.litellm.ai/docs/providers) works.
  22. ## How It Works
  23. ```
  24. ┌──────────────────────────────────────────────────────────────┐
  25. │ X2Strategy │
  26. │ │
  27. PDF / MD / DOCX / TXT │ ┌─────────┐ ┌───────────┐ ┌──────────┐ ┌─────────┐ │
  28. ─────────────────────►│ │ Parse ├──►│ Extract ├──►│ Generate ├──►│Backtest │ │
  29. │ │ (parser) │ │ (L0 → L4) │ │ (code) │ │+ Diagnose││
  30. │ └─────────┘ └───────────┘ └──────────┘ └─────────┘ │
  31. │ ▼ ▼ ▼ ▼ │
  32. │ PaperContent StrategySpec Backtrader.py Report.md │
  33. └──────────────────────────────────────────────────────────────┘
  34. ```
  35. | Stage | Input | Output | What Happens |
  36. |:------|:------|:-------|:-------------|
  37. | **Parse** | Any document | `PaperContent` | Format-aware extraction (PyMuPDF / direct read / python-docx) |
  38. | **Extract** | PaperContent | `StrategySpec[]` | 5-layer LLM with optional instruction grounding: detect strategies → extract indicators, logic, execution, risk |
  39. | **Generate** | StrategySpec | `strategy.py` | Data module → signal module → backtest module → integration |
  40. | **Validate** | strategy.py | Pass / Fail | AST syntax + Backtrader structure + indicator existence checks |
  41. | **Backtest** | strategy.py | Metrics | Subprocess execution with timeout, metric extraction |
  42. | **Diagnose** | Metrics | `report.md` | Compare against paper-reported results, flag deviations |
  43. ## Getting Started
  44. ### As an Agent Skill
  45. [Agent Skills](https://agentskills.io/) is an open standard. Clone into the agent's skill directory — it auto-discovers `SKILL.md` and registers the `/x2strategy` slash command.
  46. #### Install to OpenClaw / OpenClaw Users
  47. For OpenClaw users, install directly from ClawHub:
  48. ```bash
  49. openclaw skills install patrick-lew/x2strategy
  50. ```
  51. Or use the ClawHub CLI:
  52. ```bash
  53. npx clawhub@latest install x2strategy
  54. ```
  55. For remote or guided setup, paste this prompt into OpenClaw:
  56. ```text
  57. Install the skill "X2strategy" (patrick-lew/x2strategy) from ClawHub.
  58. Skill page: https://clawhub.ai/patrick-lew/x2strategy
  59. Keep the work scoped to this skill only.
  60. After install, inspect the skill metadata and help me finish setup.
  61. Use only the metadata you can verify from ClawHub; do not invent missing requirements.
  62. Ask before making any broader environment changes.
  63. ```
  64. #### Install to Claude Code / Codex / Copilot
  65. <table>
  66. <tr><td><b>GitHub Copilot</b></td><td>
  67. ```bash
  68. git clone https://github.com/ALAGENT-HKU/x2strategy.git ~/.copilot/skills/x2strategy
  69. ```
  70. </td></tr>
  71. <tr><td><b>Claude Code</b></td><td>
  72. ```bash
  73. git clone https://github.com/ALAGENT-HKU/x2strategy.git ~/.claude/skills/x2strategy
  74. ```
  75. </td></tr>
  76. <tr><td><b>Project-scoped</b></td><td>
  77. ```bash
  78. git clone https://github.com/ALAGENT-HKU/x2strategy.git .github/skills/x2strategy
  79. ```
  80. </td></tr>
  81. </table>
  82. Then install dependencies. After successful skill installation, the agent may auto-install them during initialization, but manual setup is the most predictable path:
  83. ```bash
  84. cd ~/.copilot/skills/x2strategy # or wherever you cloned
  85. # if you haven't installed uv, run `pip install uv`
  86. uv sync --all-extras
  87. ```
  88. <details>
  89. <summary>Manual dependency variants</summary>
  90. ```bash
  91. # minimum skill runtime
  92. uv sync --extra agent --extra codegen
  93. # add DOCX parsing support
  94. uv sync --extra agent --extra codegen --extra docx
  95. # pip alternative
  96. python -m venv .venv && source .venv/bin/activate
  97. pip install -e ".[codegen,agent,docx,dev]"
  98. ```
  99. </details>
  100. > [!IMPORTANT]
  101. > The directory name **must** be `x2strategy` (matching the `name` field in `SKILL.md`). Once installed, type `/x2strategy` in chat or the agent auto-activates when relevant.
  102. ### Skill Quick Start
  103. ```bash
  104. # 1. Configure the skill workspace
  105. cp .env.example .env # add your API key (DEEPSEEK_API_KEY recommended)
  106. # 2. Start the skill in your agent
  107. # /x2strategy
  108. ```
  109. Then ask for work in natural language, for example:
  110. > *"Analyze this paper and implement the main strategy."* + attach a PDF + optional data files + optional clarification/user-customization prompts such as *"When the paper underspecifies a formula, you can either explicitly ask me or refer to the sample_instruction.md file."*
  111. The skill handles parsing, extraction, code generation, validation, backtesting, and diagnosis.
  112. Before extraction, it should ask whether you want to add custom instructions, implementation constraints, known pitfalls, or reference files.
  113. After extraction and strategy/plan selection, it must read [references/extraction_quality.md](references/extraction_quality.md) before any repair, code generation, or deterministic local implementation.
  114. It should also use the same interactive flow when you pick search results, add repair-time pitfall notes or clarifications, approve inferred defaults, or resolve any `needs_human_review` items surfaced by compare/repair.
  115. After code generation and diagnosis, it should present an interactive next-action menu instead of assuming the workflow is finished.
  116. Generated files should be written under `PAPER2SPEC_LIBRARY_PATH/<slug>/` by default, for example `content.json`, `spec.json`, the generated implementation file, and `results/metrics.json`. If a referenced Copilot/VS Code log path is empty or incomplete, regenerate the artifacts from the original paper, instructions, and data instead of relying on the log summary.
  117. Spec2Code outputs should include Sharpe ratio, maximum drawdown, total return, and return value/final portfolio value whenever those metrics are meaningful for the confirmed implementation target.
  118. Here, “custom instructions” means extra extraction requirements you want the skill to follow, not shell commands or implementation details.
  119. - Use them to say which rules or assumptions must be preserved.
  120. - Use them to point out mistakes or pitfalls the skill should avoid.
  121. - Use them to add background context that you have already confirmed.
  122. Examples:
  123. "Only implement the main strategy in the paper, not the appendix variants."
  124. "If the weighting rule is ambiguous, prefer equal weight."
  125. "Treat the rebalance frequency as monthly, not weekly."
  126. If extraction, compare, or repair leaves `needs_human_review` questions, it should ask them through an interactive dialog before generating code. In VS Code Copilot, that means `vscode_askQuestions` when available rather than only writing the questions in prose. If validation or diagnosis still leaves unresolved decisions, it should ask again before silently retrying or stopping.
  127. ## Supported Input Formats
  128. | Format | Extensions | Parser | Notes |
  129. |:-------|:-----------|:-------|:------|
  130. | **PDF** | `.pdf` | PyMuPDF → Mode A (direct) or Mode B (FAISS) | Full support, covering 95%+ of papers |
  131. | **Markdown** | `.md` `.markdown` | Direct text read | Ideal for strategy drafts and notes |
  132. | **Word** | `.docx` | python-docx (`uv sync --extra docx`) | Internal research reports |
  133. | **Plain text** | `.txt` | Direct read | Raw strategy descriptions |
  134. Format is auto-detected from file extension. No configuration needed.
  135. ## Examples
  136. The primary shipped example in [`examples/`](examples/) is the UPSA paper2code case, generated by Copilot GPT-5.4:
  137. | Paper | Strategies Detected | Artifacts |
  138. |:------|:-------------------|:----------|
  139. | **Universal Portfolio Shrinkage Approximation** (Kelly, Malamud, Pourmohammadi & Trojani 2025) | 1 — UPSA ridge-ensemble portfolio | content + spec + paper2code contract |
  140. The UPSA example lives in `examples/upsa/`. Reproducible inputs are stored in `examples/upsa/input/`, and the generated implementation is `examples/upsa/universal_portfolio_shrinkage_approximation.py`.
  141. <details>
  142. <summary>Example output structure</summary>
  143. ```
  144. examples/upsa/
  145. ├── README.md
  146. ├── upsa_content.json
  147. ├── upsa_content.md
  148. ├── upsa_spec.json
  149. ├── upsa_spec.md
  150. ├── upsa_operator_pitfall_context.md
  151. ├── upsa_review_and_diagnosis.md
  152. ├── upsa_metadata.json
  153. ├── universal_portfolio_shrinkage_approximation.py
  154. └── input/
  155. ├── P10_Kelly_Malamud_Pourmohammadi_Trojani_2025_NBER.pdf
  156. ├── sample_instruction.md
  157. ├── jkp_factors_wide.csv
  158. ├── jkp_factors_long.csv
  159. └── upsa_weights.csv
  160. ```
  161. </details>
  162. > [!IMPORTANT]
  163. > Not every strategy extracted by this skill is suitable for direct broker-connected (live/paper) trading. Many research strategies consume factor returns, synthetic portfolios, ranking panels, or other non-tradable inputs; some are portfolio-construction or SDF/asset-pricing procedures rather than order-generating live strategies. The open-source skill focuses on grounded extraction, code generation, validation, and research backtests. ALAGENT's website can generate broker-connected strategies when the selected strategy and data contract are suitable for live/paper trading.
  164. ## Project Structure
  165. ```
  166. x2strategy/
  167. ├── paper2spec/ # Phase 1: Document → Structured Spec
  168. │ ├── __init__.py
  169. │ ├── config.py # Environment and library path configuration
  170. │ ├── parser.py # Multi-format parser (PDF / MD / DOCX / TXT)
  171. │ ├── pdf_utils.py # PDF extraction helpers
  172. │ ├── extractor.py # PaperContent → ExtractionResult (L0-L4)
  173. │ ├── models.py # Data models (PaperContent, StrategySpec, etc.)
  174. │ ├── prompts.py # 5-layer extraction prompt templates
  175. │ ├── operator_pitfall.py # Semantic retrieval for repair pitfall checks
  176. │ ├── resources/
  177. │ │ └── operator_pitfall_index.md # Editable pitfall corpus for retrieval
  178. │ ├── llm.py # LiteLLM unified interface
  179. │ ├── render.py # JSON → Markdown rendering
  180. │ └── search.py # arXiv + SSRN paper search
  181. │
  182. ├── spec2code/ # Phase 2 support: agent-driven codegen validation
  183. │ ├── __init__.py
  184. │ ├── validator.py # AST + structural + indicator validation
  185. │ ├── config.py # Codegen and backtest configuration
  186. │ └── models.py # CodeModules, ValidationResult, BacktestMetrics
  187. │
  188. ├── references/ # Verified domain knowledge (not LLM hallucinations)
  189. │ ├── backtrader_patterns.md # Source-verified Backtrader patterns
  190. │ ├── indicator_cookbook.md # Official indicator params (from bt source code)
  191. │ ├── data_sources.md # yfinance + akshare API docs
  192. │ ├── extraction_quality.md # Grounded extraction / repair quality rules
  193. │ ├── paper2spec.md # Paper2Spec deep-dive guide
  194. │ ├── spec2code.md # Spec2Code deep-dive guide
  195. │ └── skill-internals.md # Skill setup and environment details
  196. │
  197. ├── scripts/ # CLI entry points
  198. │ ├── analyze.py # Full paper2spec pipeline
  199. │ ├── extract.py # Extract specs from parsed content
  200. │ ├── parse.py # Parse documents into PaperContent
  201. │ ├── search.py # Search for papers
  202. │ ├── operator_pitfalls.py # Retrieve matched operator-pitfall context
  203. │ ├── generate_schemas.py # Generate JSON schemas
  204. │ ├── run_full_tests.sh # Test runner helper
  205. │ └── validate_strategy.py # Standalone validation
  206. │
  207. ├── docs/ # Architecture and design docs
  208. │ └── ARCHITECTURE.md
  209. │
  210. ├── assets/ # README / skill images
  211. ├── schemas/ # JSON Schema definitions
  212. ├── examples/ # Pre-generated reference outputs
  213. ├── tests/ # 180+ unit & integration tests
  214. ├── .env.example # Environment variable template
  215. ├── requirements.txt # pip fallback dependencies
  216. ├── README_CN.md # Chinese README
  217. ├── SKILL.md # Agent Skill entry point
  218. ├── pyproject.toml # Project config & dependencies
  219. └── uv.lock # Locked uv dependency graph
  220. ```
  221. ## Key Design Decisions
  222. ### Why Reference Docs, Not Prompts?
  223. LLMs frequently hallucinate Backtrader API details:
  224. - SMA default `period` is `30`, not `20`
  225. - RSI uses `SmoothedMovingAverage`, not EMA
  226. - BollingerBands lines are `.top/.mid/.bot`, not `.upper/.lower`
  227. Our `references/` directory contains **source-code-verified** knowledge. The agent reads these docs on demand instead of relying on improvised API recall.
  228. ### Why Structured Specs as Intermediate?
  229. Going directly from paper → code loses auditability. The `StrategySpec` intermediate:
  230. - **Auditable** — humans can review the spec before code generation
  231. - **Reusable** — the same spec can target different backtest engines
  232. - **Testable** — extraction and code generation are independently verifiable
  233. ### Grounded Extraction and Repair
  234. `paper2spec` supports optional instruction/clarification context during
  235. extraction. Use this when a paper has appendix-only formulas, missing constants,
  236. ambiguous allocation logic, or the user wants to customize extraction requirements.
  237. - The skill should ask for instruction files, clarifications, or reference notes before extraction when the input is ambiguous.
  238. - [references/extraction_quality.md](references/extraction_quality.md) is the canonical audit guide for manual review.
  239. - For repair-style RAG, use only the pitfalls retrieved from [paper2spec/resources/operator_pitfall_index.md](paper2spec/resources/operator_pitfall_index.md), not the full index.
  240. - Ground truth still comes from the paper, selected plan, user clarifications, and approved customization notes. The pitfall index is only an audit aid.
  241. ## Configuration
  242. | Variable | Default | Description |
  243. |:---------|:--------|:------------|
  244. | `PAPER2SPEC_LIBRARY_PATH` | `./library` | Output root directory |
  245. | `PAPER2SPEC_MODEL` | `openai/gpt-4o-mini` | LLM model ([LiteLLM format](https://docs.litellm.ai/docs/providers)) |
  246. | `SPEC2CODE_BACKTEST_TIMEOUT` | `300` | Backtest timeout in seconds |
  247. | `DEEPSEEK_API_KEY` | — | DeepSeek (recommended: best cost/quality) |
  248. | `OPENROUTER_API_KEY` | — | OpenRouter (one key, all models) |
  249. | `OPENAI_API_KEY` | — | OpenAI direct |
  250. | `ANTHROPIC_API_KEY` | — | Anthropic direct |
  251. All scripts accept `--model` to override `PAPER2SPEC_MODEL`.
  252. ## Documentation
  253. | Resource | Description |
  254. |:---------|:------------|
  255. | [SKILL.md](SKILL.md) | Agent skill instructions — setup, single workflow, HITL review, output paths |
  256. | [references/paper2spec.md](references/paper2spec.md) | Paper → Spec extraction deep-dive |
  257. | [references/extraction_quality.md](references/extraction_quality.md) | Grounded extraction and repair quality rules |
  258. | [paper2spec/resources/operator_pitfall_index.md](paper2spec/resources/operator_pitfall_index.md) | Editable semantic retrieval corpus for high-risk formula pitfalls |
  259. | [references/spec2code.md](references/spec2code.md) | Spec → Code generation deep-dive |
  260. | [references/backtrader_patterns.md](references/backtrader_patterns.md) | Source-verified Backtrader patterns |
  261. | [references/indicator_cookbook.md](references/indicator_cookbook.md) | Official indicator parameter reference |
  262. | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Pipeline architecture |
  263. ## Testing
  264. ```bash
  265. pytest tests/ -v # 180+ deterministic tests
  266. pytest tests/ -v --run-real # + real API tests (requires DEEPSEEK_API_KEY)
  267. ```
  268. ## Contributing
  269. We welcome contributions! Please see the [Architecture Doc](docs/ARCHITECTURE.md) for codebase orientation.
  270. ```bash
  271. git clone https://github.com/ALAGENT-HKU/x2strategy.git && cd x2strategy
  272. uv sync --all-extras
  273. cp .env.example .env # add API key
  274. pytest tests/ -v # verify everything passes
  275. ```
  276. ## License
  277. [Apache-2.0](LICENSE) · Built by **[ALAGENT AI 优彦智能](http://home.alagent.cloud)** — Verifiable & Trustworthy Financial AI
  278. ---
  279. <div align="center">
  280. ## 💬 Join the Community
  281. <a href="https://home.alagent.cloud">🌐 Website</a> &nbsp;·&nbsp; <a href="https://github.com/ALAGENT-HKU">GitHub</a> &nbsp;·&nbsp; <a href="mailto:contact@alagent.cloud">📧 contact@alagent.cloud</a>
  282. <br>
  283. <img src="assets/wechat_QR.jpg" alt="WeChat Group QR" width="260">
  284. **Scan to join the ALAGENT Open-Source WeChat Group**
  285. </div>

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.