Skip to content

title: Chapter 2: Environment Setup

Chapter 2: Environment Setup

This chapter covers three ways to set up a Lean environment: Lean CLI (recommended), building locally, and Dev Container.

2.1 Choosing an Approach

Approach Best For Difficulty Recommendation
Lean CLI Strategy development, quick start ⭐ ⭐⭐⭐⭐⭐
Local build Deep customization, contributing code ⭐⭐⭐ ⭐⭐⭐
Dev Container Cross-platform development, avoiding environment issues ⭐⭐ ⭐⭐⭐⭐

2.2.1 System Requirements

  • Python 3.8+
  • Docker (to run the containerized Lean)
  • 4GB+ RAM
  • 10GB+ disk space

2.2.2 Installation Steps

Step 1: Install Python

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

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

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

Step 2: Install 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

Step 3: Install Lean CLI

# 使用 pip 安装
pip install lean

# 验证安装
lean --version

2.2.3 Initialize a Project

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

# 初始化 Lean
lean init

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

2.2.4 Project Structure

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

2.3 Option 2: Build the Lean Engine Locally

2.3.1 System Requirements

  • .NET 10 SDK
  • Visual Studio (Windows) or VS Code (cross-platform)
  • Python 3.11 (optional, for Python strategies)

2.3.2 Installation Steps

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 Configuration File

The backtest start/end dates and initial cash are not configured in Launcher/config.json (the engine does not read such keys); instead, they are decided by the algorithm in Initialize():

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

Launcher/config.json only holds engine-level configuration (environment, algorithm entry point, data source, etc.), for example:

{
  "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 Option 3: Dev Container

2.4.1 What Is a Dev Container?

A Dev Container is a preconfigured Docker container that includes all dependencies needed for Lean development.

2.4.2 Usage Steps

# 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 Environment Configuration

2.5.1 Python Version Requirement

Lean requires Python 3.11.11

# 下载 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 Autocomplete Setup

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

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

2.5.4 VS Code Configuration

Create .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 Verify the Installation

Create a test file 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)

Run the test:

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

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

2.7 Troubleshooting

Q1: Docker Permission Issues (Linux)

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

# 重新登录或执行
newgrp docker

Q2: Python Version Mismatch

# 检查 Python 版本
python --version

# 必须是 Python 3.11.11

Q3: quantconnect-stubs Installation Fails

# 升级 pip
pip install --upgrade pip

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

Q4: .NET SDK Not Found

# 验证 .NET 安装
dotnet --version

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

2.8 Next Steps

With the environment set up, the next chapter introduces Lean's quick-start example.