Skip to content

title: Chapter 1: What is Lean?

Chapter 1: What is Lean?

This chapter introduces the basic concepts and core features of the Lean quantitative trading engine, and the difference between Lean and Lean CLI.

1.1 Project Overview

Lean is an open-source event-driven algorithmic trading platform from QuantConnect, designed for quantitative trading developers. It provides full capabilities for strategy research, historical backtesting, parameter optimization, and live trading.

Core Features

Feature Module Description
Strategy research Explore data and validate strategies in Jupyter Notebook
Historical backtesting Simulate strategy performance on historical data
Parameter optimization Automatically search for optimal strategy parameters
Live trading Live brokerage connections with multiple brokers
Multiple asset classes Equities, options, futures, forex, crypto, and more

Supported Programming Languages

  • C# - Native language, best performance
  • Python - Integrated via Python.NET, rich ecosystem

1.2 Lean vs Lean CLI

Lean Engine (this project)

The Lean Engine is the core trading engine, which contains:

Lean/
├── Engine/              # 核心引擎
├── Algorithm/           # 算法基类
├── Algorithm.CSharp/    # C# 示例策略
├── Algorithm.Python/    # Python 示例策略
├── Algorithm.Framework/ # 框架化模型
├── Common/              # 通用组件
├── Brokerages/          # 券商接口
└── Launcher/            # 程序入口

The Lean CLI is a command-line tool that simplifies working with Lean:

# 安装 CLI
pip install lean

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

# 运行回测
lean backtest "MyFirstStrategy"

# 启动研究环境
lean research

Which one should you use?

Scenario Recommended Tool
Developing trading strategies Lean CLI
Contributing to Lean source code Lean Engine
Learning the internals Lean Engine
Quickly validating ideas Lean CLI

1.3 Core Features

Event-Driven Architecture

Lean uses an event-driven architecture where the algorithm responds to various events:

from AlgorithmImports import *

class MyAlgorithm(QCAlgorithm):

    def Initialize(self):
        # 初始化设置
        self.AddEquity("SPY", Resolution.Minute)

    def OnData(self, data):
        # 每个数据点触发
        pass

    def OnOrderEvent(self, orderEvent):
        # 订单事件触发
        pass

    def OnEndOfDay(self, symbol):
        # 每日收盘时触发
        pass

Multiple Asset Class Support

Asset Type Add Method Market Examples
Equities AddEquity() USA, China, India
Forex AddForex() EURUSD, USDJPY
Futures AddFuture() ES, NQ, CL
Options AddOption() SPY, AAPL
Crypto AddCrypto() BTCUSD, ETHUSD
CFD AddCfd() Various CFDs
Indices AddIndex() SPX, VIX

Modular Design

Every component of Lean is customizable:

┌─────────────────────────────────────────────┐
│              QCAlgorithm                    │
│  ┌──────────────────────────────────────┐  │
│  │  Alpha Model        (交易信号生成)    │  │
│  │  Portfolio Model    (组合构建)        │  │
│  │  Execution Model    (订单执行)        │  │
│  │  Risk Model         (风险控制)        │  │
│  │  Universe Model     (证券选择)        │  │
│  └──────────────────────────────────────┘  │
│                                             │
│  ┌──────────────────────────────────────┐  │
│  │  Brokerage          (券商接口)        │  │
│  │  Data Feed          (数据源)          │  │
│  │  Fill Model         (成交模型)        │  │
│  │  Fee Model          (手续费模型)      │  │
│  │  Slippage Model     (滑点模型)        │  │
│  └──────────────────────────────────────┘  │
└─────────────────────────────────────────────┘

1.4 Architecture Overview

                        ┌─────────────┐
                        │   用户输入   │
                        └──────┬──────┘
                               │
                        ┌──────▼──────┐
                        │  Launcher   │
                        └──────┬──────┘
                               │
        ┌──────────────────────┼──────────────────────┐
        │                      │                      │
┌───────▼────────┐    ┌────────▼────────┐    ┌───────▼────────┐
│  Algorithm     │    │   Data Feed     │    │   Transaction  │
│  (策略逻辑)    │    │  (数据提供器)    │    │   (交易处理)    │
└───────┬────────┘    └────────┬────────┘    └───────┬────────┘
        │                      │                      │
        └──────────────────────┼──────────────────────┘
                               │
                        ┌──────▼──────┐
                        │   Results    │
                        │  (结果输出)   │
                        └─────────────┘

1.5 Hybrid Local and Cloud Development

Lean supports a hybrid mode of local development and cloud deployment:

┌─────────────┐         ┌─────────────┐
│  本地开发    │  <--->  │  云端平台    │
│  (Lean CLI) │         │(QuantConnect)│
└─────────────┘         └─────────────┘
     • 完整控制              • 数据获取
     • 调试方便              • 云计算资源
     • 数据隐私              • 策略分享

1.6 Example: Your First Lean Algorithm

Here is the simplest possible Lean algorithm example:

from AlgorithmImports import *

class HelloWorldAlgorithm(QCAlgorithm):
    """
    最简单的 Lean 算法示例
    功能:买入并持有 SPY
    """

    def Initialize(self):
        # 1. 设置回测时间范围
        self.SetStartDate(2023, 1, 1)    # 开始日期
        self.SetEndDate(2023, 12, 31)    # 结束日期
        self.SetCash(100000)             # 初始资金

        # 2. 添加证券
        self.AddEquity("SPY", Resolution.Daily)

        # 3. 设置benchmark
        self.SetBenchmark("SPY")

    def OnData(self, data):
        # 4. 如果还没有持仓,买入SPY
        if not self.Portfolio.Invested:
            self.SetHoldings("SPY", 1)   # 使用100%资金买入
            self.Debug("Purchased SPY")

1.7 Next Steps

In the next chapter, we will learn how to set up a Lean development environment.