### Configure Skill Workspace Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Before starting the skill, configure your workspace by copying the example environment file and adding your API key. The DEEPSEEK_API_KEY is recommended. ```bash # 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 ``` -------------------------------- ### Install X2Strategy Prompt for OpenClaw Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Paste this prompt into OpenClaw for remote or guided setup of the X2Strategy skill. ```text 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 Dependencies with uv Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Install all skill dependencies, including extras, using the `uv sync --all-extras` command. Ensure `uv` is installed (`pip install uv`). ```bash cd ~/.copilot/skills/x2strategy # or wherever you cloned # if you haven't installed uv, run `pip install uv` uv sync --all-extras ``` -------------------------------- ### Example SKILL Interactions Source: https://github.com/alagent-hku/x2strategy/blob/main/SKILL.md Illustrates various ways to interact with the SKILL project after setup, covering tasks like paper analysis, strategy implementation, and comparison. ```text ✅ Setup complete. You can now ask me for tasks directly, for example: • "Analyze this paper" + attach a PDF file • "Search for papers about momentum trading" • "Implement this strategy based on this paper" + provide the file path • "I wrote a strategy draft in Markdown; extract the spec and generate code" • "Compare the strategy differences between these two papers" Just tell me what you want to do, and I will handle the rest. ``` -------------------------------- ### Python Environment Setup without uv Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md Manually set up a Python virtual environment and install project dependencies using pip. This method is an alternative to using uv for environment management. ```bash cd python -m venv .venv && source .venv/bin/activate pip install -e ".[codegen,agent,dev]" ``` -------------------------------- ### Install Minimum Skill Runtime Dependencies Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Install only the minimum required dependencies for the skill runtime, including agent and codegen extras, using `uv sync`. ```bash uv sync --extra agent --extra codegen ``` -------------------------------- ### Install Project Dependencies with uv Source: https://github.com/alagent-hku/x2strategy/blob/main/SKILL.md Use this command to install all project dependencies, including extras, for a complete development environment. This is the recommended method. ```bash uv sync --all-extras ``` -------------------------------- ### Install Dependencies with pip Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Install skill dependencies using pip, creating a virtual environment and installing extras for codegen, agent, docx, and dev. ```bash python -m venv .venv && source .venv/bin/activate pip install -e ".[codegen,agent,docx,dev]" ``` -------------------------------- ### Example Project Structure Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md This snippet shows the directory structure for the UPSA example, detailing input files, content, specifications, and the generated Python implementation. ```text examples/upsa/ ├── README.md ├── upsa_content.json ├── upsa_content.md ├── upsa_spec.json ├── upsa_spec.md ├── upsa_operator_pitfall_context.md ├── upsa_review_and_diagnosis.md ├── upsa_metadata.json ├── universal_portfolio_shrinkage_approximation.py └── input/ ├── P10_Kelly_Malamud_Pourmohammadi_Trojani_2025_NBER.pdf ├── sample_instruction.md ├── jkp_factors_wide.csv ├── jkp_factors_long.csv └── upsa_weights.csv ``` -------------------------------- ### Install X2Strategy via ClawHub CLI Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Install the X2Strategy skill using the ClawHub CLI. This is an alternative to direct OpenClaw installation. ```bash npx clawhub@latest install x2strategy ``` -------------------------------- ### Install X2Strategy via ClawHub Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Use this command to install the X2Strategy skill directly from ClawHub for OpenClaw users. ```bash openclaw skills install patrick-lew/x2strategy ``` -------------------------------- ### Install Dependencies with DOCX Support Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Install dependencies including DOCX parsing support by adding the `--extra docx` flag to `uv sync`. ```bash uv sync --extra agent --extra codegen --extra docx ``` -------------------------------- ### Setup Development Environment Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Clone the repository, synchronize dependencies, configure environment variables, and run tests. Ensure you copy the .env.example file and add your API key. ```bash git clone https://github.com/ALAGENT-HKU/x2strategy.git && cd x2strategy ``` ```bash uv sync --all-extras ``` ```bash cp .env.example .env # add API key ``` ```bash pytest tests/ -v # verify everything passes ``` -------------------------------- ### Install Project Dependencies with pip Source: https://github.com/alagent-hku/x2strategy/blob/main/SKILL.md If uv is not available, use this pip command to install the project dependencies, including extras for codegen, agent, and dev functionalities. ```bash pip install -e ".[codegen,agent,dev]" ``` -------------------------------- ### Selective Package Installation with uv Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md Install specific sets of extra dependencies using uv sync with different --extra flags. This allows for tailored environments based on project needs, such as code generation, agent functionality, or development testing. ```bash uv sync uv sync --extra codegen uv sync --extra agent uv sync --extra dev uv sync --all-extras ``` -------------------------------- ### Backtrader Logic Pipeline Example Source: https://github.com/alagent-hku/x2strategy/blob/main/references/spec2code.md Translates a logic pipeline step from a specification into Backtrader code. This example checks if the current closing price is greater than a 200-period Simple Moving Average. ```python if self.data.close[0] > self.sma200[0]: # trend_filter ``` -------------------------------- ### Progress Marker Protocol Examples Source: https://github.com/alagent-hku/x2strategy/blob/main/SKILL.md Demonstrates the use of structured markers for tracking workflow progress, artifacts, and errors. These markers supplement natural language reporting. ```text [PROGRESS] paper2spec/extract — extracting strategy specs from content.json [ARTIFACT] library/upsa/spec.json — 1 strategy, 4 indicators, 3 logic steps [PROGRESS] HITL review — 1 open needs_human_review item, asking for resolution ``` -------------------------------- ### Verify LLM Initialization Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md Run a simple chat command to verify the LLM setup and API key. This command checks if the 'chat' function from paper2spec.llm is accessible and responsive. ```bash # Verify key works uv run python -c "from paper2spec.llm import chat; print(chat('Say OK'))" 2>&1 | head -1 ``` -------------------------------- ### Clone X2Strategy for Project-Scoped Installation Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Clone the X2Strategy repository into a project-scoped directory for local development or specific project integration. ```bash git clone https://github.com/ALAGENT-HKU/x2strategy.git .github/skills/x2strategy ``` -------------------------------- ### Get Index Real-time Data (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Fetches real-time spot data for all indices from Eastmoney. ```python # 指数实时行情 df = ak.stock_zh_index_spot_em() # 全部指数 ``` -------------------------------- ### Strategy Specification JSON Example Source: https://github.com/alagent-hku/x2strategy/blob/main/references/spec2code.md Example of a structured strategy specification in JSON format. Key fields include strategy name, type, asset class, indicators, logic pipeline, execution plan, risk management, and expected performance. ```json { "strategy_name": "Minimum Distance Pairs Trading", "strategy_type": "technical", "asset_class": ["equity"], "indicators": [...], "logic_pipeline": [...], "execution_plan": [...], "risk_management": [...], "expected_performance": {"sharpe": 1.8, "annual_return": 0.15} } ``` -------------------------------- ### Create and Run Strategy in Dedicated venv Source: https://github.com/alagent-hku/x2strategy/blob/main/references/spec2code.md If the strategy requires external libraries not present in the main venv, create a dedicated virtual environment within the library subdirectory. Install necessary packages and then run the strategy. ```bash cd library// uv venv && uv pip install backtrader yfinance akshare uv run python strategy_1.py ``` -------------------------------- ### Get Index Historical Data (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Recommended method to get historical index data from Eastmoney. Requires the index symbol. ```python # 指数历史行情-东财 (推荐) df = ak.stock_zh_index_daily_em(symbol="sh000300") # 沪深300 ``` -------------------------------- ### Reporting Results - Good vs. Bad Examples Source: https://github.com/alagent-hku/x2strategy/blob/main/SKILL.md Illustrates effective natural language reporting of findings versus showing raw commands. Focus on what was found, not how it was executed. ```text ❌ Bad: "I ran `uv run python scripts/analyze.py paper.pdf` and got 3 strategies." ✅ Good: "This paper contains 3 independent strategies: [1] minimum distance method, [2] ADF stationarity, and [3] Johansen cointegration. Which one should I implement?" ``` -------------------------------- ### Get All A-Share Real-time Data (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Fetches real-time spot data for all A-shares from Eastmoney, including a wide range of metrics like latest price, volume, turnover, and valuation ratios. ```python # 东财-全部A股实时 df = ak.stock_zh_a_spot_em() ``` -------------------------------- ### Get China Macroeconomic Data Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Fetches various Chinese macroeconomic indicators including CPI, GDP, PMI, and LPR. ```python cpi = ak.macro_china_cpi() # 居民消费价格指数 gdp = ak.macro_china_gdp() # 国内生产总值 pmi = ak.macro_china_pmi() # 采购经理人指数 lpr = ak.macro_china_lpr() # 贷款报价利率 ``` -------------------------------- ### Get A-Share Code and Name List Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Retrieves a list of all A-share stock codes and their corresponding names. ```python # 股票代码列表 df = ak.stock_info_a_code_name() # 输出: code, name ``` -------------------------------- ### Get Real-time Data for Specific A-Share Markets Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Fetches real-time spot data for specific A-share markets: Shanghai, Shenzhen, Beijing, and the STAR Market (Kechuang Board). ```python # 沪A股 / 深A股 / 京A股 / 科创板 df = ak.stock_sh_a_spot_em() df = ak.stock_sz_a_spot_em() df = ak.stock_bj_a_spot_em() df = ak.stock_kc_a_spot_em() ``` -------------------------------- ### Validate Strategy Code Source: https://github.com/alagent-hku/x2strategy/blob/main/references/spec2code.md Run this command to validate the strategy's AST syntax, import statements, and indicator existence against the installed backtrader version. Ensure all checks pass before proceeding. ```bash uv run python scripts/validate_strategy.py library//strategy_1.py ``` -------------------------------- ### Implement Rolling Beta Indicator Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md This indicator calculates the rolling beta between two assets. It requires a lookback period and uses numpy for calculations. Ensure numpy is installed. ```python class RollingBeta(bt.Indicator): lines = ('beta',) params = (('period', 60),) def next(self): asset = list(self.data0.close.get(size=self.p.period)) market = list(self.data1.close.get(size=self.p.period)) if len(asset) < self.p.period: return import numpy as np ret_a = np.diff(asset) / asset[:-1] ret_m = np.diff(market) / market[:-1] cov = np.cov(ret_a, ret_m)[0][1] var = np.var(ret_m) self.lines.beta[0] = cov / var if var > 0 else 0 ``` -------------------------------- ### Get A-Share Minutely Data (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Fetches A-share historical data for minute intervals (1, 5, 15, 30, 60 minutes) from Eastmoney. Note that 1-minute data is limited to the last 5 trading days and is not adjusted. ```python # 分时数据-东财 (近期, 1/5/15/30/60分钟) df = ak.stock_zh_a_hist_min_em(symbol="000001", period='5', adjust='qfq', start_date="2024-01-01 09:30:00", end_date="2024-01-05 15:00:00") ``` -------------------------------- ### Get HK Stock Historical Data (Sina) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Retrieves historical Hong Kong stock data from Sina. Requires stock symbol and adjustment type. ```python # 新浪-港股历史 df = ak.stock_hk_daily(symbol="00700", adjust="qfq") ``` -------------------------------- ### Get A-Share Historical Data (Sina) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Alternative interface for A-share historical data from Sina. This is an older interface and may be prone to IP blocking. It requires a market prefix in the symbol. ```python # 新浪-A股历史 (较老接口, 易被封IP, 建议用 stock_zh_a_hist) df = ak.stock_zh_a_daily(symbol="sz000001", start_date="20200101", end_date="20240101", adjust="qfq") ``` -------------------------------- ### Get Index Historical Data (Sina) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Retrieves historical index data from Sina. Requires the index symbol. ```python # 指数历史行情-新浪 df = ak.stock_zh_index_daily(symbol="sh000001") # 上证综指 ``` -------------------------------- ### Get US Stock Historical Data (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Fetches historical US stock data from Eastmoney. The symbol format may need to be obtained via `ak.stock_us_spot_em()`. Specify period, date range, and adjustment type. ```python # 东财-美股历史行情 df = ak.stock_us_hist( symbol='106.TTE', # 代码格式: 通过 ak.stock_us_spot_em() 获取 period="daily", start_date="20200101", end_date="20240101", adjust="qfq" ) ``` -------------------------------- ### Get A-Share Historical Data (Tencent) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Retrieves A-share historical data from Tencent. Requires stock symbol, date range, and adjustment type. ```python # 腾讯-A股历史 df = ak.stock_zh_a_hist_tx(symbol="sz000001", start_date="20200101", end_date="20240101", adjust="qfq") ``` -------------------------------- ### Multiple Symbols Download with yfinance Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Fetches historical data for multiple stock tickers using yfinance. This example demonstrates the default behavior of returning MultiIndex columns and how to access data for a specific symbol. ```python df = yf.download(['AAPL', 'MSFT', 'GOOGL'], start='2020-01-01', end='2024-01-02', auto_adjust=True, multi_level_index=True) # Returns MultiIndex columns: (Price, Symbol) # Access single: df[('Close', 'AAPL')] or df['Close']['AAPL'] # For per-symbol DataFrames: for sym in ['AAPL', 'MSFT', 'GOOGL']: sym_df = df.xs(sym, level=1, axis=1) # Single-level columns ``` -------------------------------- ### Get HK Stock Historical Data (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Recommended method for fetching historical Hong Kong stock data from Eastmoney. Specify stock symbol, period, date range, and adjustment type. ```python # 东财-港股历史行情 (推荐) df = ak.stock_hk_hist( symbol="00700", # 腾讯 period="daily", start_date="20200101", end_date="20240101", adjust="qfq" # qfq/hfq/" ) ``` -------------------------------- ### Get US Stock Historical Data (Sina) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Retrieves historical US stock data from Sina using a more direct symbol format (e.g., 'AAPL'). Requires stock symbol and adjustment type. ```python # 新浪-美股历史 (更直接的 symbol) df = ak.stock_us_daily(symbol="AAPL", adjust="qfq") ``` -------------------------------- ### Strategy Backtesting Source: https://github.com/alagent-hku/x2strategy/blob/main/SKILL.md Execute a backtest for a generated strategy. Ensure the strategy file path is correct. ```bash uv run python library//strategy_1.py ``` -------------------------------- ### Verify LLM API Key with Python Source: https://github.com/alagent-hku/x2strategy/blob/main/SKILL.md After setting the API key and model in the .env file, use this command to verify the connection and functionality of the LLM integration. ```python from paper2spec.llm import chat print(chat('Say OK')) ``` -------------------------------- ### Create and Activate Strategy Virtual Environment Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md Use uv to create a dedicated virtual environment for strategy dependencies within the library subdirectory. This isolates strategy dependencies from the skill's main environment. ```bash cd library// uv venv uv pip install backtrader yfinance akshare uv run python strategy_1.py ``` -------------------------------- ### Run Strategy Directly Source: https://github.com/alagent-hku/x2strategy/blob/main/references/spec2code.md Execute the strategy file directly to run the backtest and generate metrics. The strategy should be self-contained, fetching its own data and printing results to stdout/stderr. ```bash cd library// uv run python strategy_1.py ``` -------------------------------- ### Run Backtest with Analyzers in Python Source: https://github.com/alagent-hku/x2strategy/blob/main/references/backtrader_patterns.md Sets up a Backtrader Cerebro instance, adds data and a strategy, configures the broker with cash and commission, and adds several standard analyzers. Returns the first strategy instance after running the backtest. ```python def run_backtest(): cerebro = bt.Cerebro() data = bt.feeds.PandasData(dataname=df) cerebro.adddata(data) cerebro.addstrategy(MyStrategy, period=20) cerebro.broker.setcash(100000) cerebro.broker.setcommission(commission=0.001) # Standard analyzers — see "Analyzer Return Structures" below cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe', riskfreerate=0.0, annualize=True) cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown') cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='trades') cerebro.addanalyzer(bt.analyzers.Returns, _name='returns') cerebro.addanalyzer(bt.analyzers.SQN, _name='sqn') cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='annual') results = cerebro.run() return results[0] # first strategy instance if __name__ == '__main__': run_backtest() ``` -------------------------------- ### Run Full Analysis Pipeline Source: https://github.com/alagent-hku/x2strategy/blob/main/references/paper2spec.md Use this script for the complete PDF analysis pipeline. It supports various modes and custom instructions. ```bash uv run python scripts/analyze.py [-o DIR] [--parser-mode builtin|agent] [--model MODEL] [--instruction FILE] [--instructions-dir DIR] ``` -------------------------------- ### Get A-Share Historical Data (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Primary interface for A-share historical data. Specify stock symbol, period, date range, and adjustment type (forward/backward/none). ```python import akshare as ak df = ak.stock_zh_a_hist( symbol="000001", # 股票代码 (不带市场前缀) period="daily", # choice of {'daily', 'weekly', 'monthly'} start_date="20200101", # 格式 YYYYMMDD end_date="20240101", # 格式 YYYYMMDD adjust="qfq" # "qfq"=前复权, "hfq"=后复权, ""=不复权 ) ``` -------------------------------- ### construct_strategy_returns Source: https://github.com/alagent-hku/x2strategy/blob/main/examples/upsa/input/sample_instruction.md Constructs strategy returns based on UPSA portfolio weights and factor data. The strategy return at date t reflects weights from the previous rebalance date. ```APIDOC ## construct_strategy_returns(upsa_weights_df, jkp_factors_wide) ### Description Constructs strategy returns based on UPSA portfolio weights and factor data. The strategy return at date t reflects weights from the previous rebalance date. ### Input - `upsa_weights_df` (pd.DataFrame): DataFrame with columns `[date, upsa_weights, factor_ids]`. - `jkp_factors_wide` (pd.DataFrame): DataFrame with columns `[date, ...]`. ### Output - pd.DataFrame: DataFrame with columns `[date, strategy_ret]`. ### Temporal Anchor `strategy_ret` at date t is the realized return of the portfolio whose weights were fixed at the previous rebalance date (end of month t−1). ``` -------------------------------- ### Output Directory Structure Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md This illustrates the standard directory structure for storing the output files generated by the analysis tools. It includes original documents, machine-readable JSON, human-readable Markdown, and metadata files. ```bash library// # Original document (auto-copied) content.json # PaperContent (machine-readable) content.md # PaperContent (human-readable) spec.json # ExtractionResult with all strategies spec.md # Strategy summary (human-readable) metadata.json # Analysis metadata ``` -------------------------------- ### Clone X2Strategy for GitHub Copilot Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Clone the X2Strategy repository into the specified directory for GitHub Copilot integration. ```bash git clone https://github.com/ALAGENT-HKU/x2strategy.git ~/.copilot/skills/x2strategy ``` -------------------------------- ### Threshold Breakout Signal Generation (Python) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Generates buy signals when RSI falls below 30 (and no position is open) and sell signals when RSI rises above 70 (and a position is open). ```python def next(self): if self.rsi[0] < 30 and not self.position: self.buy() elif self.rsi[0] > 70 and self.position: self.sell() ``` -------------------------------- ### Backtrader Strategy Code Structure Source: https://github.com/alagent-hku/x2strategy/blob/main/references/spec2code.md Outlines the essential components of a Backtrader strategy file generated by the agent. Includes imports, data loading, strategy class, Cerebro setup, and output generation. ```python # Imports import backtrader as bt import yfinance import datetime import json # Data loading with local cache # ... # Strategy class class MyStrategy(bt.Strategy): def __init__(self): # ... pass def next(self): # ... pass # Cerebro setup # ... # Metrics output # ... # Visualization output # ... # Commission comparison output # ... if __name__ == "__main__": # ... pass ``` -------------------------------- ### OpenAI .env Configuration Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md Configure direct OpenAI access. Set the library path, model, and OpenAI API key. PAPER2SPEC_INIT_VERSION is required. ```dotenv PAPER2SPEC_LIBRARY_PATH=/absolute/path/to/library PAPER2SPEC_MODEL=openai/gpt-4o-mini OPENAI_API_KEY=sk-actualKeyFromUser PAPER2SPEC_INIT_VERSION=1 ``` -------------------------------- ### Document Analysis and Spec Generation Source: https://github.com/alagent-hku/x2strategy/blob/main/SKILL.md Use this command to analyze a file and generate a specification in the library. Ensure the output path is correctly specified. ```bash uv run python scripts/analyze.py -o library// ``` -------------------------------- ### Step-by-step Paper to Spec Extraction Source: https://github.com/alagent-hku/x2strategy/blob/main/SKILL.md These commands process a file to extract content and then generate a specification. The intermediate content JSON is useful for debugging. ```bash uv run python scripts/parse.py -o content.json ``` ```bash uv run python scripts/extract.py content.json -o spec.json ``` -------------------------------- ### Run Deterministic Tests Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Execute all deterministic tests in the project. This is the standard way to verify code correctness. ```bash pytest tests/ -v ``` -------------------------------- ### On-Balance Volume (OBV) in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement the On-Balance Volume indicator using the built-in OBV indicator. Requires a data feed. ```python bt.indicators.OBV(data) ``` -------------------------------- ### OpenRouter .env Configuration Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md Configure OpenRouter as a multi-model gateway. Specify the library path, model, and OpenRouter API key. PAPER2SPEC_INIT_VERSION should be set. ```dotenv PAPER2SPEC_LIBRARY_PATH=/absolute/path/to/library PAPER2SPEC_MODEL=openrouter/deepseek/deepseek-chat-v3-0324 OPENROUTER_API_KEY=sk-or-actualKeyFromUser PAPER2SPEC_INIT_VERSION=1 ``` -------------------------------- ### DeepSeek .env Configuration Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md Configure DeepSeek LLM with library path, model name, and API key. Ensure PAPER2SPEC_INIT_VERSION is set. ```dotenv PAPER2SPEC_LIBRARY_PATH=/absolute/path/to/library PAPER2SPEC_MODEL=deepseek/deepseek-chat DEEPSEEK_API_KEY=sk-actualKeyFromUser PAPER2SPEC_INIT_VERSION=1 ``` -------------------------------- ### Run Real API Tests Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Execute tests that interact with real APIs. Requires the DEEPSEEK_API_KEY environment variable to be set. ```bash pytest tests/ -v --run-real ``` -------------------------------- ### Create Backtrader Data Feed from CSV Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Use this to load data from a CSV file. Specify the file path and the format of the datetime string. Map the column indices to the corresponding data fields (datetime, open, high, low, close, volume). ```python data = bt.feeds.GenericCSVData( dataname='data.csv', dtformat='%Y-%m-%d', datetime=0, open=1, high=2, low=3, close=4, volume=5, openinterest=-1, ) ``` -------------------------------- ### yfinance download() Full Signature Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md This details the parameters available for the yfinance download function, used for fetching historical stock data. Note the default behaviors and available values for period and interval. ```python yfinance.download( tickers, start=None, end=None, actions=False, threads=True, ignore_tz=None, group_by='column', auto_adjust=True, back_adjust=False, repair=False, keepna=False, progress=True, period=None, interval='1d', prepost=False, rounding=False, timeout=10, session=None, multi_level_index=True, ) ``` -------------------------------- ### Access Multiple Data Feeds in Backtrader Strategy Source: https://github.com/alagent-hku/x2strategy/blob/main/references/backtrader_patterns.md Demonstrates how to access and process multiple data feeds within a Backtrader strategy using self.datas or self.dataX attributes. ```python class MultiStrategy(bt.Strategy): def __init__(self): # self.datas[0], self.datas[1], etc. or self.data0, self.data1 self.smas = {} for d in self.datas: self.smas[d._name] = bt.indicators.SMA(d.close, period=20) def next(self): for i, d in enumerate(self.datas): if d.close[0] > d.close[-1]: self.buy(data=d) ``` -------------------------------- ### Backtrader Strategy Template Source: https://github.com/alagent-hku/x2strategy/blob/main/references/spec2code.md A comprehensive template for building trading strategies with Backtrader. It includes placeholders for strategy logic and a function to run backtests and collect standard performance metrics. ```python import backtrader as bt import yfinance as yf import json import datetime class MyStrategy(bt.Strategy): params = (...) def __init__(self): # Map spec indicators to bt.indicators ... def next(self): # Map spec logic_pipeline to trading decisions ... def run_backtest(): cerebro = bt.Cerebro() # Load data # Network data must be loaded through a local cache first. data = bt.feeds.PandasData(dataname=df) cerebro.adddata(data) # Configure cerebro.broker.setcash(100000) cerebro.addstrategy(MyStrategy) # Add standard analyzers for metrics cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='trades') cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe', riskfreerate=0.01) # default is 0.01, explicit cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown') cerebro.addanalyzer(bt.analyzers.Returns, _name='returns') cerebro.addanalyzer(bt.analyzers.SQN, _name='sqn') cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='annual') results = cerebro.run() strat = results[0] # Extract metrics using .get() dict access — verified against source code. # Analyzer.get_analysis() returns AutoOrderedDict; use .get() to avoid # KeyError on no-trade runs. See backtrader_patterns.md for full details. initial_cash = 100000 final_value = cerebro.broker.getvalue() trades = strat.analyzers.trades.get_analysis() sharpe = strat.analyzers.sharpe.get_analysis() dd = strat.analyzers.drawdown.get_analysis() ret = strat.analyzers.returns.get_analysis() metrics = { 'final_value': round(final_value, 2), 'return_value': round(final_value, 2), 'total_return': round((final_value / initial_cash - 1) * 100, 2), 'sharpe_ratio': round(sharpe.get('sharperatio'), 4) if sharpe.get('sharperatio') is not None else None, 'max_drawdown_pct': round(dd.get('max', {}).get('drawdown', 0), 2), 'num_trades': trades.get('total', {}).get('closed', 0), 'won_trades': trades.get('won', {}).get('total', 0), 'lost_trades': trades.get('lost', {}).get('total', 0), 'normalized_annual_return': round( ret.get('rnorm100', 0), 2), # rnorm × 100 'sqn': round(strat.analyzers.sqn.get_analysis().get('sqn', 0), 4), } print(json.dumps(metrics, indent=2)) if __name__ == '__main__': run_backtest() ``` -------------------------------- ### Clone X2Strategy for Claude Code Source: https://github.com/alagent-hku/x2strategy/blob/main/README.md Clone the X2Strategy repository into the specified directory for Claude Code integration. ```bash git clone https://github.com/ALAGENT-HKU/x2strategy.git ~/.claude/skills/x2strategy ``` -------------------------------- ### Create Backtrader Data Feed from akshare DataFrame Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md This snippet is for data fetched using akshare. It requires renaming columns to match Backtrader's expected format (open, high, low, close, volume) and setting datetime to None to use the DataFrame's index. ```python data = bt.feeds.PandasData( dataname=df, datetime=None, # Use index open='open', high='high', low='low', close='close', volume='volume', openinterest=-1, ) ``` -------------------------------- ### TradeAnalyzer Return Keys Source: https://github.com/alagent-hku/x2strategy/blob/main/references/backtrader_patterns.md Accesses various trade statistics from TradeAnalyzer. Keys are created only when trades occur. Use dot notation for access. ```python rets.total.total # int — all trades (open + closed) rets.total.open # int — currently open trades rets.total.closed # int — closed trades rets.streak.won.current # int rets.streak.won.longest # int rets.streak.lost.current # int rets.streak.lost.longest # int rets.pnl.gross.total # float — sum of all gross PnL rets.pnl.gross.average # float rets.pnl.net.total # float — sum of all net PnL (after commission) rets.pnl.net.average # float rets.won.total # int — count of winning trades rets.won.pnl.total # float — sum of winning PnL rets.won.pnl.average # float rets.won.pnl.max # float — best single trade rets.lost.total # int — count of losing trades rets.lost.pnl.total # float — sum of losing PnL (NEGATIVE) rets.lost.pnl.average # float (NEGATIVE) rets.lost.pnl.max # float — worst single trade (NEGATIVE) rets.long.total # int rets.long.pnl.total # float rets.long.pnl.average # float rets.long.won # int rets.long.lost # int rets.long.pnl.won.total # float rets.long.pnl.lost.total # float rets.short.total # int (same sub-structure as long) rets.len.total # int — total bars in all trades rets.len.average # float rets.len.max # int rets.len.min # int rets.len.won.total / average / max / min # for winning trades rets.len.lost.total / average / max / min # for losing trades ``` -------------------------------- ### Kaufman's Adaptive Moving Average (KAMA) in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement Kaufman's Adaptive Moving Average using the built-in KAMA indicator. Requires a data feed and a period, with optional fast and slow parameters. ```python bt.indicators.KAMA(data, period=30, fast=2, slow=30) ``` -------------------------------- ### Basic Backtrader Strategy Structure Source: https://github.com/alagent-hku/x2strategy/blob/main/references/backtrader_patterns.md Defines a basic Backtrader strategy with parameters, indicator calculation in __init__, and trading logic in next. ```python import backtrader as bt class MyStrategy(bt.Strategy): params = ( ('period', 20), ('threshold', 0.02), ) def __init__(self): # Compute indicators once — these are lazy (Lines objects) self.sma = bt.indicators.SMA(self.data.close, period=self.p.period) self.rsi = bt.indicators.RSI(self.data.close, period=14) def next(self): # Called on every bar after all indicators have enough data if not self.position: if self.data.close[0] > self.sma[0]: self.buy() else: if self.data.close[0] < self.sma[0]: self.sell() ``` -------------------------------- ### Simple Moving Average (SMA) in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement a Simple Moving Average using the built-in SMA indicator. Requires a data feed and a period. ```python bt.indicators.SMA(data, period=30) ``` -------------------------------- ### Equal Weight Position Sizing in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/backtrader_patterns.md Distributes portfolio weight equally across all available data feeds. Use this when aiming for a balanced exposure to each asset. ```python def next(self): n = len(self.datas) for d in self.datas: target = 1.0 / n self.order_target_percent(data=d, target=target) ``` -------------------------------- ### Analyze Script - Full Pipeline Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md Execute the full analysis pipeline for documents. Supports various file types and offers options for parser mode, output directory, and instruction files. ```bash uv run python scripts/analyze.py [-o DIR] [--parser-mode builtin|agent] [--model MODEL] [--instruction FILE] [--instructions-dir DIR] ``` -------------------------------- ### One-Shot Paper Analysis Source: https://github.com/alagent-hku/x2strategy/blob/main/references/paper2spec.md Analyzes a PDF paper and extracts strategy specifications in a single command. Optionally uses instruction files for improved accuracy. ```bash uv run python scripts/analyze.py paper.pdf -o library/my_paper/ ``` ```bash uv run python scripts/analyze.py paper.pdf -o library/my_paper/ --instructions-dir uploads/ ``` -------------------------------- ### Returns Analyzer Output Source: https://github.com/alagent-hku/x2strategy/blob/main/references/backtrader_patterns.md Retrieves total, average, and annualized returns. Values are decimals, not percentages. ```python analysis = strat.analyzers.returns.get_analysis() analysis['rtot'] # float — total compound return (logarithmic) analysis['ravg'] # float — average period return analysis['rnorm'] # float — annualized return analysis['rnorm100'] # float — annualized return as % (rnorm * 100) ``` -------------------------------- ### Load Strategy Specification Source: https://github.com/alagent-hku/x2strategy/blob/main/references/skill-internals.md Load a strategy specification from a JSON file. This spec dictionary is then used by the agent to generate Backtrader code. ```python import json result = json.load(open("library/pairs_trading/spec.json")) strategy = result["strategies"][0] # Pick by index # Agent reads this spec dict and generates Backtrader code ``` -------------------------------- ### AnnualReturn Analyzer Output Source: https://github.com/alagent-hku/x2strategy/blob/main/references/backtrader_patterns.md Retrieves annual returns as an OrderedDict. Values are decimals, e.g., 0.15 for 15%. ```python analysis = strat.analyzers.annual.get_analysis() # Returns OrderedDict: {2020: 0.15, 2021: -0.03, ...} # Values are DECIMALS (0.15 = 15%), NOT percentages. ``` -------------------------------- ### Bollinger Bands in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement Bollinger Bands using the built-in BollingerBands indicator. Requires a data feed and optional period and deviation factor. ```python bt.indicators.BollingerBands(data) ``` -------------------------------- ### Full Stochastic Oscillator in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement the Full Stochastic Oscillator, which includes %K, %D, and %DSlow lines. Requires a data feed and period parameters. ```python bt.indicators.StochasticFull(data) ``` -------------------------------- ### Real-time A-Share Data (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Retrieves real-time spot data for all A-shares from Eastmoney. ```APIDOC ## stock_zh_a_spot_em ### Description Retrieves real-time spot data for all A-shares from Eastmoney. ### Method `ak.stock_zh_a_spot_em` ### Output Columns `序号, 代码, 名称, 最新价, 涨跌幅(%), 涨跌额, 成交量(手), 成交额(元), 振幅(%), 最高, 最低, 今开, 昨收, 量比, 换手率(%), 市盈率, 市净率, 总市值(元), 流通市值(元), 涨速, 5分钟涨跌(%), 60日涨跌幅(%), 年初至今涨跌幅(%)` ``` -------------------------------- ### Mode A: Parallel LLM Calls for Parsing Source: https://github.com/alagent-hku/x2strategy/blob/main/docs/ARCHITECTURE.md This snippet illustrates the parallel execution of three LLM calls for extracting methodology, data description, and signal logic. It's used in Mode A when the paper's full text fits within the context window. ```python asyncio.gather( methodology_prompt(context), data_description_prompt(context), signal_logic_prompt(context) ) ``` -------------------------------- ### RSI with SMA in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement Cutler's RSI variant using Simple Moving Average (SMA). Requires a data feed. ```python bt.indicators.RSI_SMA(data) ``` -------------------------------- ### Money Flow Indicator (MFI) in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement the Money Flow Indicator using the built-in MFI indicator. Requires a data feed and a period. ```python bt.indicators.MFI(data, period=14) ``` -------------------------------- ### Extract PaperContent to Strategy Specification Source: https://github.com/alagent-hku/x2strategy/blob/main/references/paper2spec.md Extracts a strategy specification from parsed PaperContent. Supports multi-strategy detection and optional instruction files. ```bash uv run python scripts/extract.py content.json -o spec.json ``` ```bash uv run python scripts/extract.py content.json -o spec.json --instruction notes.md ``` -------------------------------- ### Real-time Specific A-Share Markets (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Retrieves real-time spot data for specific A-share markets (Shanghai, Shenzhen, Beijing, STAR Market) from Eastmoney. ```APIDOC ## stock_sh_a_spot_em, stock_sz_a_spot_em, stock_bj_a_spot_em, stock_kc_a_spot_em ### Description Retrieves real-time spot data for specific A-share markets from Eastmoney. ### Methods - `ak.stock_sh_a_spot_em()`: Shanghai A-shares - `ak.stock_sz_a_spot_em()`: Shenzhen A-shares - `ak.stock_bj_a_spot_em()`: Beijing A-shares - `ak.stock_kc_a_spot_em()`: STAR Market (Kechuang Board) ``` -------------------------------- ### Crossover Signal Generation (Python) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Generates buy or sell signals when a fast moving average crosses above or below a slow moving average. Uses the built-in CrossOver indicator. ```python self.cross = bt.indicators.CrossOver(self.fast_ma, self.slow_ma) def next(self): if self.cross[0] > 0: # fast crossed above slow self.buy() elif self.cross[0] < 0: # fast crossed below slow self.sell() ``` -------------------------------- ### Zero Lag Exponential Moving Average (ZLEMA) in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement a Zero Lag Exponential Moving Average using the built-in ZeroLagExponentialMovingAverage indicator. Requires a data feed. ```python bt.indicators.ZeroLagExponentialMovingAverage(data) ``` -------------------------------- ### Implement VWAP Indicator Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md This indicator calculates the Volume Weighted Average Price (VWAP). It requires cumulative volume and price-volume data. ```python class VWAP(bt.Indicator): lines = ('vwap',) def __init__(self): cumvol = bt.indicators.CumSum(self.data.volume) cumtp = bt.indicators.CumSum( (self.data.high + self.data.low + self.data.close) / 3.0 * self.data.volume ) self.lines.vwap = cumtp / cumvol ``` -------------------------------- ### Create Backtrader Data Feed from yfinance DataFrame Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Use this when loading data downloaded via yfinance. Ensure the DataFrame is cleaned (e.g., timezone removed) and has a proper date index before passing it to PandasData. Specify the date range for the feed. ```python import backtrader as bt from datetime import datetime # After download with multi_level_index=False and tz removal data = bt.feeds.PandasData( dataname=df, fromdate=datetime(2020, 1, 1), todate=datetime(2024, 1, 1), ) ``` -------------------------------- ### Weighted Moving Average (WMA) in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement a Weighted Moving Average using the built-in WMA indicator. Requires a data feed and a period. ```python bt.indicators.WMA(data, period=30) ``` -------------------------------- ### MACD Indicator in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement the Moving Average Convergence Divergence indicator using the built-in MACD indicator. Requires a data feed. ```python bt.indicators.MACD(data) ``` -------------------------------- ### End-to-End Data Flow Source: https://github.com/alagent-hku/x2strategy/blob/main/docs/ARCHITECTURE.md Overview of the data flow from a PDF file to the final ExtractionResult, including parsing and LLM stages. ```text ┌─────────┐ pymupdf4llm ┌──────────┐ Mode A or B ┌──────────────┐ │ PDF │ ─────────────→ │ Raw Text │ ─────────────→ │ PaperContent │ │ File │ │ (MD fmt) │ 3 ∥ LLM calls │ .json/.md │ └─────────┘ └──────────┘ └──────────────┘ │ ▼ ┌──────────┐ │ Layer 0 │ │ Detect N │ └──────────┘ │ ┌───────────┼───────────┐ ▼ ▼ ▼ Strategy 1 Strategy 2 ...N L1→L2→L3→L4 L1→L2→L3→L4 │ │ │ └───────────┼───────────┘ ▼ ┌──────────────────┐ │ ExtractionResult │ │ .json / .md │ └──────────────────┘ ``` -------------------------------- ### Ichimoku Indicator in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement the Ichimoku Cloud indicator using the built-in Ichimoku indicator. Requires a data feed and specific period parameters. ```python bt.indicators.Ichimoku(data) ``` -------------------------------- ### Multi-strategy Parallelization Flow Source: https://github.com/alagent-hku/x2strategy/blob/main/docs/ARCHITECTURE.md Diagram illustrating how multiple strategies are processed in parallel after Layer 0 detection. ```text Layer 0 detects N strategies │ ├── Strategy 1: L1 → L2 → L3 → L4 ─┐ ├── Strategy 2: L1 → L2 → L3 → L4 ─┤ asyncio.gather() └── Strategy N: L1 → L2 → L3 → L4 ─┘ │ ▼ ExtractionResult (N specs) ``` -------------------------------- ### VWAP Indicator (Custom) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Volume Weighted Average Price is not a built-in indicator and requires a custom implementation. -------------------------------- ### Index Real-time Data (Eastmoney) Source: https://github.com/alagent-hku/x2strategy/blob/main/references/data_sources.md Retrieves real-time data for all indices from Eastmoney. ```APIDOC ## stock_zh_index_spot_em ### Description Retrieves real-time data for all indices from Eastmoney. ### Method `ak.stock_zh_index_spot_em` ``` -------------------------------- ### Commodity Channel Index (CCI) in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement the Commodity Channel Index using the built-in CCI indicator. Requires a data feed and a period, with optional factor and moving average type. ```python bt.indicators.CCI(data, period=20) ``` -------------------------------- ### Stochastic Oscillator in Backtrader Source: https://github.com/alagent-hku/x2strategy/blob/main/references/indicator_cookbook.md Implement the Stochastic Oscillator using the built-in Stochastic indicator. Requires a data feed and period parameters. ```python bt.indicators.Stochastic(data) ```