跳转至

第2章 环境搭建

本章介绍三种 Lean 环境搭建方式:Lean CLI(推荐)、本地编译、Dev Container。

2.1 方式选择指南

方式 适用场景 难度 推荐度
Lean CLI 策略开发、快速上手 ⭐ ⭐⭐⭐⭐⭐
本地编译 深度定制、贡献代码 ⭐⭐⭐ ⭐⭐⭐
Dev Container 跨平台开发、避免环境问题 ⭐⭐ ⭐⭐⭐⭐

2.2 方式一:Lean CLI(推荐)

2.2.1 系统要求

  • Python 3.8+
  • Docker(用于运行容器化的 Lean)
  • 4GB+ 内存
  • 10GB+ 磁盘空间

2.2.2 安装步骤

步骤 1:安装 Python

# macOS(使用 Homebrew)
brew install python@3.11

# Ubuntu/Debian
sudo apt update
sudo apt install python3.11 python3-pip

# Windows
# 从 python.org 下载安装程序

步骤 2:安装 Docker

# macOS
# 下载 Docker Desktop for Mac

# Ubuntu/Debian
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

# 验证安装
docker --version

步骤 3:安装 Lean CLI

# 使用 pip 安装
pip install lean

# 验证安装
lean --version

2.2.3 初始化项目

# 创建工作目录
mkdir lean-projects
cd lean-projects

# 初始化 Lean
lean init

# 创建新项目
lean project-create "MyFirstStrategy" --language python

2.2.4 项目结构

lean-projects/
├── config.json          # Lean 配置文件
├── data/                # 本地数据目录
├── MyFirstStrategy/     # 你的项目目录
│   └── main.py
└── output/              # 回测输出目录

2.3 方式二:本地编译 Lean Engine

2.3.1 系统要求

  • .NET 10 SDK
  • Visual Studio(Windows)或 VS Code(跨平台)
  • Python 3.11(可选,用于 Python 策略)

2.3.2 安装步骤

Windows

# 1. 安装 Visual Studio 2022
# 下载地址:visualstudio.microsoft.com
# 需要安装:.NET 桌面开发 工作负载

# 2. 克隆仓库
git clone https://github.com/QuantConnect/Lean.git
cd Lean

# 3. 打开 QuantConnect.Lean.sln
# 在 Visual Studio 中打开解决方案

# 4. 编译并运行
# 按 F5 或点击"开始调试"按钮

macOS

# 1. 安装 .NET 10 SDK
# 下载地址:dotnet.microsoft.com/download

# 2. 安装 Visual Studio Code
# 下载地址:code.visualstudio.com

# 3. 安装 C# 扩展
code --install-extension ms-dotnettools.csharp
code --install-extension ms-dotnettools.csdevkit

# 4. 克隆仓库
git clone https://github.com/QuantConnect/Lean.git
cd Lean

# 5. 编译
dotnet build QuantConnect.Lean.sln

# 6. 运行
cd Launcher/bin/Debug
dotnet QuantConnect.Lean.Launcher.dll

Linux (Ubuntu/Debian)

# 1. 安装 .NET 10 SDK
wget https://dot.net/v1/dotnet-install.sh
chmod +x dotnet-install.sh
./dotnet-install.sh --channel 10.0

# 2. 克隆并编译
git clone https://github.com/QuantConnect/Lean.git
cd Lean
dotnet build QuantConnect.Lean.sln

# 3. 运行
cd Launcher/bin/Debug
dotnet QuantConnect.Lean.Launcher.dll

2.3.3 配置文件

回测的起止日期与初始资金不在 Launcher/config.json 中配置(引擎不读取此类键),而是由算法在 Initialize() 中决定:

def Initialize(self):
    self.SetStartDate(2023, 1, 1)    # 回测开始日期
    self.SetEndDate(2023, 12, 31)    # 回测结束日期
    self.SetCash(100000)             # 初始资金 $100,000

Launcher/config.json 只存放引擎级配置(运行环境、算法入口、数据源等),例如:

{
  "environment": "backtesting",

  "algorithm-type-name": "BasicTemplateAlgorithm",
  "algorithm-language": "CSharp",
  "algorithm-location": "QuantConnect.Algorithm.CSharp.dll",

  "data-folder": "../../../Data/",

  "data-provider": "QuantConnect.Lean.Engine.DataFeeds.DefaultDataProvider"
}

2.4 方式三:Dev Container

2.4.1 什么是 Dev Container?

Dev Container 是一个预配置的 Docker 容器,包含所有 Lean 开发所需的依赖。

2.4.2 使用步骤

# 1. 安装 Docker Desktop

# 2. 安装 Visual Studio Code

# 3. 安装 Remote Containers 扩展
code --install-extension ms-vscode-remote.remote-containers

# 4. 拉取 Lean 研究镜像
docker pull quantconnect/research:latest

# 5. 克隆 Lean 仓库
git clone https://github.com/QuantConnect/Lean.git
cd Lean

# 6. 在 VS Code 中打开
code .

# 7. 选择 "Reopen in Container"
# 或使用命令面板:Ctrl+Shift+P -> "Remote-Containers: Reopen in Container"

2.5 Python 环境配置

2.5.1 Python 版本要求

Lean 要求 Python 3.11.11

2.5.2 使用 Anaconda(推荐)

# 下载 Anaconda
# macOS: https://www.anaconda.com/download#macos
# Windows: https://www.anaconda.com/download#windows
# Linux: https://www.anaconda.com/download#linux

# 安装后,创建 Python 3.11 环境
conda create -n lean python=3.11.11 -y

# 激活环境
conda activate lean

# 安装依赖
pip install pandas==2.3.3 wrapt==1.17.3

# 设置环境变量
export PYTHONNET_PYDLL="$(conda env list | grep lean | awk '{print $2}')/lib/libpython3.11.dylib"

2.5.3 自动补全设置

# 安装 Lean 类型存根
pip install quantconnect-stubs

# 在 Python 文件顶部添加
# from AlgorithmImports import *

2.5.4 VS Code 配置

创建 .vscode/settings.json:

{
  "python.defaultInterpreterPath": "/path/to/conda/envs/lean/bin/python",
  "python.linting.enabled": true,
  "python.linting.pylintEnabled": true,
  "python.formatting.provider": "black",
  "python.analysis.extraPaths": [
    "/path/to/lean/Algorithm.Python"
  ]
}

2.6 验证安装

创建测试文件 test_setup.py:

from AlgorithmImports import *

class TestSetupAlgorithm(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2023, 1, 1)
        self.SetEndDate(2023, 1, 31)
        self.SetCash(100000)
        self.AddEquity("SPY", Resolution.Daily)
        self.Debug("Setup successful!")

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

运行测试:

# 使用 Lean CLI
lean backtest "MyFirstStrategy" --output ./output

# 或使用本地编译的 Lean
cd Launcher/bin/Debug
dotnet QuantConnect.Lean.Launcher.dll

2.7 常见问题

Q1: Docker 权限问题(Linux)

# 将用户添加到 docker 组
sudo usermod -aG docker $USER

# 重新登录或执行
newgrp docker

Q2: Python 版本不匹配

# 检查 Python 版本
python --version

# 必须是 Python 3.11.11

Q3: quantconnect-stubs 安装失败

# 升级 pip
pip install --upgrade pip

# 重新安装
pip uninstall quantconnect-stubs
pip install quantconnect-stubs

Q4: .NET SDK 未找到

# 验证 .NET 安装
dotnet --version

# 如果未安装,访问 dotnet.microsoft.com

2.8 下一步

环境搭建完成后,下一章将介绍 Lean 的快速开始示例。