← 返回 Skills 市场
cylqqqcyl

LEAN Engine — Algorithmic Trading

作者 Yinliang Chen · GitHub ↗ · v1.1.0 · MIT-0
cross-platform ✓ 安全检测通过
274
总下载
1
收藏
0
当前安装
3
版本数
在 OpenClaw 中安装
/install lean-engine
功能描述
Run QuantConnect LEAN backtests and manage US equity algorithm development. Use when asked to backtest a trading strategy, run a LEAN algorithm, analyze back...
使用说明 (SKILL.md)

LEAN Engine — QuantConnect Algorithmic Trading

Prerequisites & Setup

Required Environment Variables

Variable Purpose Example
LEAN_ROOT Path to cloned LEAN repository /home/user/lean
DOTNET_ROOT Path to .NET SDK installation /home/user/.dotnet
PYTHONNET_PYDLL Path to Python shared library (required by LEAN's pythonnet) $LEAN_ROOT/.libs/libpython3.11.so.1.0

All three must be set before using this skill. Add to your shell profile:

export LEAN_ROOT="$HOME/lean"
export DOTNET_ROOT="$HOME/.dotnet"
export PATH="$PATH:$DOTNET_ROOT"
export PYTHONNET_PYDLL="$LEAN_ROOT/.libs/libpython3.11.so.1.0"

Note: LEAN bundles its own Python shared library in $LEAN_ROOT/.libs/. If you built LEAN from source, the library should be there after dotnet build. If not, install libpython3.11-dev and point PYTHONNET_PYDLL to your system's libpython3.11.so.

First-Time Setup

  1. Install .NET 8 SDK:

    # Linux/macOS
    wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh
    chmod +x dotnet-install.sh
    ./dotnet-install.sh --channel 8.0
    export DOTNET_ROOT="$HOME/.dotnet"
    export PATH="$PATH:$DOTNET_ROOT"
    
  2. Clone and build LEAN:

    git clone https://github.com/QuantConnect/Lean.git "$LEAN_ROOT"
    cd "$LEAN_ROOT"
    dotnet build QuantConnect.Lean.sln -c Debug
    
  3. Download initial market data:

    pip install yfinance pandas
    python3 {baseDir}/scripts/download_us_universe.py --symbols sp500 --start 2020-01-01 --data-dir "$LEAN_ROOT/Data"
    
  4. Verify setup:

    ls "$LEAN_ROOT/Data/equity/usa/daily/"  # Should list .zip files
    ls "$LEAN_ROOT/Launcher/bin/Debug/"      # Should contain QuantConnect.Lean.Launcher.dll
    

Environment

  • LEAN source: $LEAN_ROOT/
  • Launcher (pre-built): $LEAN_ROOT/Launcher/bin/Debug/
  • Config: $LEAN_ROOT/Launcher/config.json
  • Python algos: $LEAN_ROOT/Algorithm.Python/
  • Market data: $LEAN_ROOT/Data/
  • dotnet: $DOTNET_ROOT/dotnet (add to PATH: export PATH="$PATH:$DOTNET_ROOT")

Quick Reference

Run a Backtest

  1. Place algorithm in $LEAN_ROOT/Algorithm.Python/YourAlgo.py
  2. Edit config to point to it:
    # Update config.json — set these fields:
    # "algorithm-type-name": "YourClassName"
    # "algorithm-language": "Python"
    # "algorithm-location": "../../../Algorithm.Python/YourAlgo.py"
    
  3. Run:
    export PATH="$PATH:$DOTNET_ROOT"
    cd "$LEAN_ROOT/Launcher/bin/Debug"
    dotnet QuantConnect.Lean.Launcher.dll
    
  4. Results appear in stdout + $LEAN_ROOT/Results/

Or use the helper script:

bash {baseDir}/scripts/run_backtest.sh YourClassName YourAlgo.py

Config Editing

Edit $LEAN_ROOT/Launcher/config.json with these key fields:

Field Purpose Example
algorithm-type-name Python class name "MyStrategy"
algorithm-language Language "Python"
algorithm-location Path to .py file "../../../Algorithm.Python/MyStrategy.py"
data-folder Market data path "../Data/"
environment Mode "backtesting" or "live-interactive"

For IB live trading, set environment to "live-interactive" and configure the ib-* fields (account, username, password, host, port, trading-mode).

Data Management

Check available data:

ls "$LEAN_ROOT/Data/equity/usa/daily/"

Data format: ZIP files containing CSV. Each line: YYYYMMDD HH:MM,Open*10000,High*10000,Low*10000,Close*10000,Volume

Prices are stored as integers (multiply by 10000). LEAN handles conversion internally.

Download more data:

python3 {baseDir}/scripts/download_us_universe.py --symbols sp500 --data-dir "$LEAN_ROOT/Data"

See {baseDir}/references/data-download.md for additional methods to expand the universe.

Writing Algorithms

LEAN Python algorithms inherit from QCAlgorithm:

from AlgorithmImports import *

class MyAlgo(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2024, 1, 1)
        self.SetEndDate(2025, 1, 1)
        self.SetCash(100_000)
        self.AddEquity("SPY", Resolution.Daily)
        self.SetBenchmark("SPY")
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage,
                               AccountType.Margin)

    def OnData(self, data):
        if not self.Portfolio.Invested:
            self.SetHoldings("SPY", 1.0)

Key API patterns:

  • self.History(symbol, periods, resolution) — get historical bars
  • self.SetHoldings(symbol, weight) — target portfolio weight
  • self.Liquidate(symbol) — close position
  • self.AddUniverse(coarse_fn, fine_fn) — dynamic universe selection
  • self.Schedule.On(date_rule, time_rule, action) — scheduled events
  • self.Debug(msg) — log output

Analyzing Results

After a backtest run, check:

ls "$LEAN_ROOT/Results/"
# Key files: *-log.txt, *-order-log.txt, *.json (statistics)

Rebuild LEAN (if source changes)

export PATH="$PATH:$DOTNET_ROOT"
cd "$LEAN_ROOT"
dotnet build QuantConnect.Lean.sln -c Debug

Security Notes

Config.json Safety

The run_backtest.sh script does NOT modify your original config.json. Instead, it:

  1. Reads the original config as a template (read-only)
  2. Creates a separate config.backtest.json with only algorithm fields changed (class name, file path, language, environment=backtesting)
  3. Temporarily swaps it in for the LEAN run, then restores the original via a trap cleanup handler

The configure_algo.py helper performs the field substitution in an isolated output file. Your original config — including any Interactive Brokers credentials for live trading — is never modified.

Modified fields (in the temp copy only):

  • algorithm-type-name — set to the requested class name
  • algorithm-language — set to Python
  • algorithm-location — set to the requested .py file path
  • environment — set to backtesting

Network Access

The setup instructions involve network downloads:

  • git clone from GitHub (QuantConnect/Lean repository)
  • dotnet build may restore NuGet packages
  • pip install yfinance pandas installs Python packages from PyPI
  • download_us_universe.py fetches market data from Yahoo Finance

All downloads are from well-known public sources. For maximum isolation, run setup in a container or VM.

Environment Variables

This skill requires the following environment variables at runtime:

  • LEAN_ROOT — path to your cloned LEAN repository
  • DOTNET_ROOT — path to your .NET SDK installation
  • PYTHONNET_PYDLL — path to Python shared library (auto-detected from $LEAN_ROOT/.libs/ if not set)

These are declared in the skill metadata and must be set before use.

Troubleshooting

  • "No data files found" → Check data-folder in config.json points to correct path
  • Python import errors → LEAN bundles its own Python; check python-venv config if using custom packages
  • Slow backtest → Reduce universe size or date range; check Resolution (Minute >> Daily)
  • IB connection issues → Verify TWS/Gateway is running, port matches config (default 4002 for Gateway)
  • LEAN_ROOT not set → Add export LEAN_ROOT="$HOME/lean" to your shell profile
  • dotnet not found → Add export PATH="$PATH:$DOTNET_ROOT" to your shell profile
  • Runtime.PythonDLL was not set → Set PYTHONNET_PYDLL to the Python shared library path (see env var table above)
安全使用建议
This skill appears to do what it says: build/run LEAN backtests and manage data. Before using it: (1) set LEAN_ROOT and DOTNET_ROOT to a repository you control (do not point to any sensitive system path), (2) inspect your Launcher/config.json for live brokerage credentials — consider removing or backing them up if you only want to backtest, (3) run the scripts in a non-production environment first so you can confirm behavior (they will temporarily overwrite config.json in the Launcher folder but restore it), and (4) only run the dotnet install script from the official Microsoft URL (the skill suggests the official source). If you need higher assurance, review the three included scripts (configure_algo.py, download_us_universe.py, run_backtest.sh) locally before invoking the skill.
功能分析
Type: OpenClaw Skill Name: lean-engine Version: 1.1.0 The skill bundle provides a legitimate interface for the QuantConnect LEAN algorithmic trading engine. It includes helper scripts for environment setup, market data downloading via yfinance (download_us_universe.py), and automated backtest configuration (run_backtest.sh). The scripts demonstrate security-conscious design by using temporary configuration files and cleanup traps to protect the user's original config.json (which may contain sensitive Interactive Brokers credentials) from being permanently modified or exposed. No evidence of data exfiltration, malicious execution, or prompt injection was found.
能力评估
Purpose & Capability
The name/description (LEAN backtests, data management, IB deployment) aligns with the included files and required items: dotnet and Python are required, and LEAN_ROOT/DOTNET_ROOT/PYTHONNET_PYDLL make sense for running LEAN. Scripts perform backtest config manipulation, data download, and launching the LEAN launcher — all expected for this functionality.
Instruction Scope
SKILL.md and the scripts operate on the LEAN repository paths (config.json, Data/, Algorithm.Python/) and instruct network calls only to expected sources (git clone GitHub, yfinance for market data, dotnet install from Microsoft). One minor inconsistency: SKILL.md and run_backtest.sh claim the original config is "NEVER modified," but the script temporarily overwrites the Launcher config.json (it does make a backup and restores it on exit). No instructions read unrelated system files or external endpoints beyond expected package/data sources.
Install Mechanism
There is no packaged install; the skill is instruction-first and suggests installing .NET via the official dot.net install script and cloning QuantConnect/Lean from GitHub. The dotnet install URL is an official Microsoft domain. No opaque downloads, shorteners, or arbitrary code-hosted archives are used.
Credentials
The required environment variables (LEAN_ROOT, DOTNET_ROOT, PYTHONNET_PYDLL) are proportionate to running LEAN. The skill does not request unrelated secrets. Caution: the Launcher config.json (which the scripts temporarily replace) commonly contains brokerage credentials for live trading (Interactive Brokers). While the script sets environment to backtesting and backs up/restores the original config, users should verify their config.json does not contain sensitive live credentials they don't want loaded or exposed during runs.
Persistence & Privilege
The skill does not request permanent/always-on privileges. It is user-invocable and does not set always: true. The scripts write files inside the LEAN repo (Data/, Results/) which is expected; they create temporary config copies and restore the original on exit.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install lean-engine
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /lean-engine 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.1.0
Security hardening: run_backtest.sh no longer modifies original config.json — uses temp copy with trap-based restore. Extracted config editor into standalone configure_algo.py (no inline heredoc). Added PYTHONNET_PYDLL to requires.env. All 3 required env vars now declared in metadata. Added detailed Security Notes section.
v1.0.1
Security fixes: declared LEAN_ROOT and DOTNET_ROOT in metadata requires.env. Added Security Notes section documenting config.json sensitivity, network access scope, and credential isolation. Added safety comments to run_backtest.sh.
v1.0.0
Initial release: QuantConnect LEAN backtesting for US equities. Includes backtest runner script, S&P 500 data downloader, data format docs, and full setup guide. Requires .NET 8 SDK and Python 3.
元数据
Slug lean-engine
版本 1.1.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 3
常见问题

LEAN Engine — Algorithmic Trading 是什么?

Run QuantConnect LEAN backtests and manage US equity algorithm development. Use when asked to backtest a trading strategy, run a LEAN algorithm, analyze back... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 274 次。

如何安装 LEAN Engine — Algorithmic Trading?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install lean-engine」即可一键安装,无需额外配置。

LEAN Engine — Algorithmic Trading 是免费的吗?

是的,LEAN Engine — Algorithmic Trading 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

LEAN Engine — Algorithmic Trading 支持哪些平台?

LEAN Engine — Algorithmic Trading 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 LEAN Engine — Algorithmic Trading?

由 Yinliang Chen(@cylqqqcyl)开发并维护,当前版本 v1.1.0。

💬 留言讨论