← 返回
数据分析 中文

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...
运行 QuantConnect LEAN 回测,管理美国股票算法开发。用于需要回测交易策略、运行 LEAN 算法、分析回测结果等场景。
cylqqqcyl
数据分析 clawhub v1.1.0 1 版本 100000 Key: 无需
★ 1
Stars
📥 646
下载
💾 21
安装
1
版本
#algorithmic-trading#backtesting#equities#finance#latest#quantconnect#trading

概述

LEAN Engine — QuantConnect Algorithmic Trading

Prerequisites & Setup

Required Environment Variables

VariablePurposeExample
----------------------------
LEAN_ROOTPath to cloned LEAN repository/home/user/lean
DOTNET_ROOTPath to .NET SDK installation/home/user/.dotnet
PYTHONNET_PYDLLPath 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:

```bash

# 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"

```

  1. Clone and build LEAN:

```bash

git clone https://github.com/QuantConnect/Lean.git "$LEAN_ROOT"

cd "$LEAN_ROOT"

dotnet build QuantConnect.Lean.sln -c Debug

```

  1. Download initial market data:

```bash

pip install yfinance pandas

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

```

  1. Verify setup:

```bash

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:

```bash

# Update config.json — set these fields:

# "algorithm-type-name": "YourClassName"

# "algorithm-language": "Python"

# "algorithm-location": "../../../Algorithm.Python/YourAlgo.py"

```

  1. Run:

```bash

export PATH="$PATH:$DOTNET_ROOT"

cd "$LEAN_ROOT/Launcher/bin/Debug"

dotnet QuantConnect.Lean.Launcher.dll

```

  1. 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:

FieldPurposeExample
-------------------------
algorithm-type-namePython class name"MyStrategy"
algorithm-languageLanguage"Python"
algorithm-locationPath to .py file"../../../Algorithm.Python/MyStrategy.py"
data-folderMarket data path"../Data/"
environmentMode"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,Open10000,High10000,Low10000,Close10000,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)

版本历史

共 1 个版本

  • v1.1.0 当前
    2026-03-29 22:09 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

productivity

Body

cylqqqcyl
体能表现——锻炼、健身追踪、营养、饮食记录、宏量营养素、食谱。当用户提及运动、举重、跑步、训练等时使用。
★ 2 📥 686
data-analysis

Excel / XLSX

ivangdavila
创建、检查和编辑 Microsoft Excel 工作簿及 XLSX 文件,支持可靠的公式、日期、类型、格式、重算及模板保留功能。
★ 367 📥 140,284
data-analysis

A股量化 AkShare

mbpz
A股量化数据分析工具,基于AkShare库获取A股行情、财务数据、板块信息等。用于回答关于A股股票查询、行情数据、财务分析、选股等问题。
★ 164 📥 59,892