Skip to content

Lean Quantitative Trading Tutorial Outline

This tutorial is aimed at developers with quantitative trading experience, providing a comprehensive learning guide to the Lean quantitative trading engine.

Target Audience

Developers with foundational quantitative trading knowledge who are familiar with Python or C# and want to quickly master the Lean engine for strategy development.

Content characteristics: - Includes complete, runnable example code - Focuses on Lean-specific APIs and patterns - Skips basic programming and quantitative concept instruction


Part 1: Introduction

1. What is Lean?

Project Overview and Core Features

  • Open-source quantitative trading engine
  • Supports strategy development in both C# and Python
  • Hybrid local and cloud development model

Lean vs Lean CLI

  • Lean Engine: the core trading engine (this project)
  • Lean CLI: command-line tool (recommended for strategy development)

Core Feature Overview

  • Event-driven architecture
  • Multi-asset class support (equities, options, futures, forex, crypto, etc.)
  • Modular design

2. Environment Setup

# 安装 Lean CLI
pip install lean

# 初始化项目
lean init

# 创建新项目
lean project-create
  • Docker environment configuration
  • Cross-platform support (Windows / macOS / Linux)

Option 2: Building the Lean Engine Locally

Windows: Visual Studio macOS: VS Code + .NET SDK Linux: .NET CLI

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

# 编译
dotnet build QuantConnect.Lean.sln

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

Option 3: Dev Container

# 拉取镜像
docker pull quantconnect/research:latest

# 在 VS Code 中打开容器
# 使用 "Reopen in Container" 功能

Python Environment Setup

# 安装 Python 3.11
# 使用 Anaconda 或 miniconda

# 设置环境变量
export PYTHONNET_PYDLL="/path/to/libpython3.11.so"

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

# 安装自动补全
pip install quantconnect-stubs

3. Quick Start

Creating Your First Project

# 使用 CLI 创建项目(项目名为位置参数)
lean project-create "MyFirstStrategy" --language python

Running a Backtest

# 本地回测(项目名为位置参数)
lean backtest "MyFirstStrategy"

# 云端回测(项目名为位置参数)
lean cloud backtest "MyFirstStrategy"

Viewing the Results Report

# 生成报告(指定回测结果与输出位置)
lean report --backtest-results "<backtest结果JSON路径>" --report-destination "<输出目录>"

Part 2: Strategy Development Basics

4. QCAlgorithm Basics

Algorithm Lifecycle

C# example:

public class BasicTemplateAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        // 设置日期范围
        SetStartDate(2023, 1, 1);
        SetEndDate(2023, 12, 31);

        // 设置初始资金
        SetCash(100000);

        // 添加证券
        AddEquity("SPY", Resolution.Daily);
    }

    public override void OnData(Slice slice)
    {
        // 数据处理主入口
    }
}

Python example:

from AlgorithmImports import *

class BasicTemplateAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2023, 1, 1)
        self.SetEndDate(2023, 12, 31)
        self.SetCash(100000)
        self.AddEquity("SPY", Resolution.Daily)

    def OnData(self, slice):
        pass

Basic Configuration

Method Description
SetStartDate(year, month, day) Set the backtest start date
SetEndDate(year, month, day) Set the backtest end date
SetCash(amount) Set the initial capital
SetAccountCurrency(currency) Set the account currency

Adding Securities

Method Purpose
AddEquity(symbol, resolution) Add equities
AddForex(symbol, resolution) Add forex
AddFuture(symbol, resolution) Add futures
AddOption(symbol, resolution) Add options
AddCrypto(symbol, resolution) Add crypto

Data Resolutions

  • Tick - tick data
  • Second - second-level
  • Minute - minute-level
  • Hour - hourly
  • Daily - daily

5. Order Management

Basic Order Types

// 市价单
MarketOrder("SPY", 100);

// 限价单
LimitOrder("SPY", 100, 450m);

// 止损市价单
StopMarketOrder("SPY", -100, 440m);

// 止损限价单
StopLimitOrder("SPY", -100, 440m, 438m);

Portfolio Management

// 按比例设置持仓(90% 资金买入 SPY)
SetHoldings("SPY", 0.9);

// 平掉所有持仓
Liquidate();

// 平掉指定证券
Liquidate("SPY");

Order Management

// 获取订单票
var ticket = MarketOrder("SPY", 100);

// 检查订单状态
if (ticket.Status == OrderStatus.Filled)
{
    // 订单已成交
}

// 更新订单
ticket.Update(new UpdateOrderFields()
{
    Quantity = 150,
    LimitPrice = 455m
});

// 取消订单
ticket.Cancel();

6. Technical Indicators

Using Built-in Indicators

// 简单移动平均线
var sma = SMA("SPY", 20);

// 指数移动平均线
var ema = EMA("SPY", 20);

// 相对强弱指标
var rsi = RSI("SPY", 14);

// MACD
var macd = MACD("SPY", 12, 26, 9);

// 布林带
var bb = BB("SPY", 20, 2);

// 在 OnData 中使用
public override void OnData(Slice slice)
{
    if (!sma.IsReady) return;

    var currentPrice = Securities["SPY"].Price;
    var average = sma.Current.Value;

    if (currentPrice > average)
    {
        SetHoldings("SPY", 1);
    }
}

Indicator Warm-Up

// 自动预热指标
WarmUpIndicator("SPY", sma, TimeSpan.FromDays(30));

// 或使用全局预热
SetWarmUp(TimeSpan.FromDays(30));

7. Data and Historical Queries

Historical Data Requests

// 获取历史数据
var history = History<TradeBar>("SPY", TimeSpan.FromDays(30));

// 获取多个证券的历史数据
var history = History(
    new List<string>() { "SPY", "QQQ" },
    TimeSpan.FromDays(30),
    Resolution.Daily
);

// 获取特定时间段的数据
var history = History<TradeBar>(
    "SPY",
    new DateTime(2023, 1, 1),
    new DateTime(2023, 12, 31),
    Resolution.Daily
);

Universe Selection

// 手动 Universe(构造函数接收 IEnumerable<Symbol> / Symbol[])
AddUniverseSelection(new ManualUniverseSelectionModel(
    new List<Symbol> { "AAPL", "MSFT", "GOOGL" }
));

// 粗粒度 Universe(按市值、价格等筛选)
AddUniverse(
    (coarse) => {
        return from c in coarse
               where c.Price > 10 && c.Volume > 1000000
               orderby c.DollarVolume descending
               select c.Symbol;
    }
);

// 精细粒度 Universe(粗筛 + 精筛,结合基本面数据)
AddUniverse(
    (coarse) => {
        return from c in coarse
               where c.Price > 10 && c.Volume > 1000000
               orderby c.DollarVolume descending
               select c.Symbol;
    },
    (fine) => {
        return from f in fine
               where f.ValuationRatios.PERatio < 20
               orderby f.ValuationRatios.PBRatio ascending
               select f.Symbol;
    }
);

Part 3: Advanced Strategy Development

8. Algorithm Framework Development

Framework Model Overview

The Lean Framework splits a strategy into five pluggable models: - Alpha Model: generates trading signals - Portfolio Construction: builds the portfolio - Execution: order execution - Risk: risk management - Universe Selection: security selection

Alpha Model

public class RsiAlpha : AlphaModel
{
    private Dictionary<Symbol, IndicatorBase> _rsiIndicators = new();

    public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
    {
        var insights = new List<Insight>();

        foreach (var kvp in _rsiIndicators)
        {
            var symbol = kvp.Key;
            var rsi = kvp.Value as RelativeStrengthIndex;

            if (!rsi.IsReady) continue;

            // RSI < 30 时生成买入信号
            if (rsi.Current.Value < 30)
            {
                insights.Add(Insight.Price(
                    symbol,
                    TimeSpan.FromDays(7),
                    InsightDirection.Up
                ));
            }
            // RSI > 70 时生成卖出信号
            else if (rsi.Current.Value > 70)
            {
                insights.Add(Insight.Price(
                    symbol,
                    TimeSpan.FromDays(7),
                    InsightDirection.Down
                ));
            }
        }

        return insights;
    }
}

Portfolio Construction Model

public class EqualWeightingPortfolioConstruction : PortfolioConstructionModel
{
    public override IEnumerable<IPortfolioTarget> CreateTargets(
        QCAlgorithm algorithm,
        Insight[] insights)
    {
        var targets = new List<PortfolioTarget>();

        if (insights.Length == 0) return targets;

        // 等权重分配
        var weight = 1m / insights.Length;

        foreach (var insight in insights)
        {
            if (insight.Direction == InsightDirection.Up)
            {
                targets.Add(PortfolioTarget.Percent(
                    insight.Symbol,
                    weight
                ));
            }
            else if (insight.Direction == InsightDirection.Down)
            {
                targets.Add(PortfolioTarget.Percent(
                    insight.Symbol,
                    -weight
                ));
            }
        }

        return targets;
    }
}

9. Advanced Features

Custom Fee Model

public class CustomFeeModel : IFeeModel
{
    public OrderFee GetOrderFee(
        OrderFeeParameters parameters)
    {
        var security = parameters.Security;
        var order = parameters.Order;

        // 自定义手续费计算逻辑
        var fee = order.AbsoluteQuantity * security.Price * 0.001m;

        return new OrderFee(new CashAmount(fee, "USD"));
    }
}

// 使用自定义手续费模型
Securities["SPY"].FeeModel = new CustomFeeModel();

Options Strategies

// 添加期权
var option = AddOption("SPY", Resolution.Minute);

// 设置过滤器(筛选近月、平值期权)
option.SetFilter(-2, 2, TimeSpan.FromDays(0), TimeSpan.FromDays(30));

// 在 OnData 中操作期权链
public override void OnData(Slice slice)
{
    // 获取期权链:从 slice.OptionChains 取,键为标的对应的 canonical 期权 Symbol
    var canonical = Symbol.Create("SPY", SecurityType.Option, Market.USA);
    if (!slice.OptionChains.TryGetValue(canonical, out var chain)) return;

    // 获取看涨期权
    var calls = chain.Where(x => x.Right == OptionRight.Call);

    // 获取平值看涨期权(Underlying 是标的代码,标的价格需从数据/证券中取)
    var underlyingPrice = Securities["SPY"].Price;
    var atmCall = calls
        .OrderBy(x => Math.Abs(x.Strike - underlyingPrice))
        .FirstOrDefault();

    if (atmCall != null)
    {
        MarketOrder(atmCall.Symbol, 1);
    }
}

Scheduled Events

// 在特定时间执行
Schedule.On(
    DateRules.EveryDay("SPY"),
    TimeRules.At(9, 30),
    () => {
        // 开盘后 30 分钟执行
    }
);

// 每周一执行
Schedule.On(
    DateRules.Every(DayOfWeek.Monday),
    TimeRules.AfterMarketOpen("SPY", 30),
    () => {
        // 每周一开盘后 30 分钟执行
    }
);

// 每月执行
Schedule.On(
    DateRules.MonthStart(),
    TimeRules.AfterMarketOpen("SPY", 30),
    () => {
        // 每月第一个交易日开盘后执行
    }
);

10. Research Environment

# 在 Jupyter Notebook 中使用 QuantBook
from QuantConnect import *
from QuantConnect.Data import *

# 创建 QuantBook
qb = QuantBook()

# 添加证券
spy = qb.AddEquity("SPY", Resolution.Daily)

# 获取历史数据
history = qb.History([spy.Symbol], 30, Resolution.Daily)

# 计算指标
sma = qb.SMA(spy.Symbol, 20)

# 显示数据
print(history.head())

Start the research environment:

lean research

Part 4: Backtesting and Optimization

11. Backtesting In Depth

Backtest Configuration

Modify config.json:

{
  "algorithm-type-name": "MyStrategy",
  "algorithm-language": "Python",
  "algorithm-location": "./MyStrategy.py",

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

  "live-mode": false
}

Note: config.json does not contain start-date, end-date, or initial-cash keys. The backtest start/end dates and initial capital must be set in the strategy's Initialize() via SetStartDate() / SetEndDate() / SetCash() (see Chapter 4). Commonly used real configuration keys include algorithm-type-name, algorithm-language, algorithm-location, data-folder, parameters, live-mode, etc.

Results Analysis

Key statistics: - Sharpe Ratio: Sharpe ratio - Sortino Ratio: Sortino ratio - Drawdown: maximum drawdown - Total Return: total return - Win Rate: win rate - Profit-Loss Ratio: profit-loss ratio

12. Parameter Optimization

# 配置并运行优化(项目名为位置参数,按提示配置目标/约束/参数;
# 可用 --max-concurrent-backtests 控制并发回测数,默认为 CPU 核数的一半)
lean optimize "MyStrategy"
lean optimize "MyStrategy" --max-concurrent-backtests 10

Example optimization configuration (schema matches Optimizer.Launcher/config.example.json):

{
  "optimization-criterion": {
    "target": "Statistics.Sharpe Ratio",
    "extremum": "max"
  },

  "constraints": [
    {
      "target": "Drawdown",
      "operator": "lessOrEqual",
      "target-value": 0.15
    }
  ],

  "parameters": [
    {
      "name": "rsiPeriod",
      "min": 10,
      "max": 30,
      "step": 2
    },
    {
      "name": "overboughtThreshold",
      "min": 65,
      "max": 80,
      "step": 5
    }
  ]
}

Field descriptions:

  • optimization-criterion: the optimization objective. target is the path to a statistic in the backtest output JSON; extremum is max or min (optionally target-value ends the run early once the target is met).
  • constraints: constraint conditions; backtest results that fail them are discarded. operator can be less, greaterOrEqual, greater, notEqual, equals, lessOrEqual.
  • parameters: parameters to optimize, corresponding one-to-one with the strategy's runtime parameters; supports step, min-step.

Part 5: Live Trading

13. Live Trading Preparation

Brokerage Integration

Supported brokerages include: - Interactive Brokers - Bitfinex (crypto) - Coinbase (crypto) - Binance (crypto) - Kraken (crypto)

Example configuration (flat keys, no nested brokerage config block):

{
  "live-mode": true,
  "live-mode-brokerage": "InteractiveBrokersBrokerage",

  "ib-account": "DU1234567",
  "ib-host": "127.0.0.1",
  "ib-port": 7497
}

Paper trading (no actual brokerage) only needs:

{
  "live-mode": true,
  "live-mode-brokerage": "PaperBrokerage"
}

14. Live Deployment

# 启动实盘交易(项目名为位置参数)
lean live deploy "MyStrategy"

# 查看云端状态
lean cloud status

Part 6: Data Management

15. Data Download and Management

Data Directory Structure

Data/
├── equity/
│   └── usa/
│       └── daily/
│           └── spy.zip
├── forex/
│   └── daily/
├── crypto/
│   └── daily/
├── future/
│   └── daily/
└── option/
    └── daily/

Using QuantConnect Cloud Data

# 下载所需数据
lean data download --dataset "QuantConnect - USA Equity Price Data"

Custom Data Import

Inherit from PythonData, override GetSource to define the data source and Reader to parse each line (PythonData has no Update(BaseData) pattern):

from AlgorithmImports import *

class CustomData(PythonData):
    """自定义数据类型"""

    def GetSource(self, config, date, isLiveMode):
        """定义数据源(返回 SubscriptionDataSource)"""
        return SubscriptionDataSource(
            "data/custom_data.csv",
            SubscriptionTransportMedium.LocalFile,
            FileFormat.Csv
        )

    def Reader(self, config, line, date, isLiveMode):
        """解析每一行数据(返回 None 表示跳过)"""
        if not line.strip():
            return None

        parts = line.split(',')

        data = CustomData()
        data.Symbol = config.Symbol
        # 时间解析用 datetime.strptime(按数据文件中的日期格式)
        data.Time = datetime.strptime(parts[0], "%Y-%m-%d")
        data.EndTime = data.Time + timedelta(days=1)
        data.Value = float(parts[1])
        return data

# 添加自定义数据(Python 包装只接收单个 timeZone 参数)
self.AddData(CustomData, "CUSTOM", Resolution.Daily)

Part 7: Best Practices and Advanced Topics

16. Code Organization and Design Patterns

Project Structure

MyLeanProject/
├── algorithms/
│   ├── strategies/
│   │   ├── MeanReversion.py
│   │   └── Momentum.py
│   ├── indicators/
│   │   └── CustomIndicator.cs
│   └── alpha/
│       └── RsiAlpha.cs
├── library/
│   └── common.py
└── config.json

Appendix A. API Quick Reference

Note: The performance optimization topic has been merged into the best practices chapters. This appendix provides a quick reference of commonly used APIs, including securities management, order management, historical data, technical indicators, scheduling, Portfolio/Securities APIs, common constants, and quick code snippets (corresponding to docs/07-best-practices/17-performance-optimization.md).

18. Debugging and Testing

Local Debugging

C#: set breakpoints in VS Code and debug with F5

Python: enable debugging in config.json:

{
  "debugging": true,
  "debugging-method": "DebugPy"
}

Unit Testing

[TestClass]
public class MyStrategyTests
{
    [TestMethod]
    public void TestInitialize()
    {
        var algorithm = new MyStrategy();
        algorithm.Initialize();

        Assert.IsTrue(algorithm.Portfolio.Cash == 100000);
    }
}

Appendix

A. Common Method Index

Category Method Description
Securities management AddEquity() Add equities
Securities management AddForex() Add forex
Securities management AddFuture() Add futures
Securities management AddOption() Add options
Securities management AddCrypto() Add crypto
Order management MarketOrder() Market order
Order management LimitOrder() Limit order
Order management SetHoldings() Set holdings by proportion
Order management Liquidate() Liquidate positions
Historical data History() Get historical data
Indicators SMA() Simple moving average
Indicators EMA() Exponential moving average
Indicators RSI() Relative strength index
Indicators MACD() MACD indicator
Indicators BB() Bollinger Bands
Scheduling Schedule.On() Scheduled tasks

B. Example Strategy Library

Basic Strategy Examples

  • Mean reversion: a mean reversion strategy using the RSI indicator
  • Momentum: a trend-following strategy based on price momentum
  • Dual moving average crossover: the classic dual moving average crossover strategy

Advanced Strategy Examples

  • Multi-factor: a stock selection strategy combining multiple factors
  • Statistical arbitrage: a pairs trading strategy
  • Options volatility: a VIX-based options strategy

C. FAQ

Q: How do I run a Python strategy locally?

A: Make sure Python 3.11 and the relevant dependencies are installed, then set algorithm-language to Python in config.json.

Q: How do I add custom data?

A: Inherit from PythonData (or from BaseData), override the GetSource and Reader methods, then add it with AddData<T>().

Q: What are the differences between backtesting and live trading?

A: The main differences include: data quality, slippage realism, order fill timing, market hours, etc.