title: Chapter 3: Quick Start¶
Chapter 3: Quick Start¶
This chapter walks you through getting started with Lean hands-on, from creating a project to running your first backtest.
3.1 Lean CLI Workflow¶
3.1.1 Create a New Project¶
# 创建项目目录
mkdir lean-tutorial
cd lean-tutorial
# 初始化 Lean
lean init
# 创建 Python 项目
lean project-create "SimpleMovingAverage" --language python
3.1.2 Project Structure¶
lean-tutorial/
├── SimpleMovingAverage/
│ └── main.py
├── config.json
└── data/
3.1.3 Write the Strategy¶
Edit SimpleMovingAverage/main.py:
from AlgorithmImports import *
class SimpleMovingAverageCrossAlgorithm(QCAlgorithm):
"""
简单移动平均线交叉策略
策略逻辑:
- 当短期均线(50日)上穿长期均线(200日)时买入
- 当短期均线下穿长期均线时卖出
"""
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
# 添加 SPY
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# 创建移动平均线指标
self.fast = self.SMA(self.spy, 50, Resolution.Daily)
self.slow = self.SMA(self.spy, 200, Resolution.Daily)
# 预热指标(避免等待数据积累)
self.SetWarmUp(TimeSpan.FromDays(200))
def OnData(self, data):
# 等待指标就绪
if not self.fast.IsReady or not self.slow.IsReady:
return
# 获取当前值
fastValue = self.fast.Current.Value
slowValue = self.slow.Current.Value
# 金叉:快线上穿慢线
if fastValue > slowValue and not self.Portfolio[self.spy].IsLong:
self.SetHoldings(self.spy, 1)
self.Debug(f"BUY at {data[self.spy].Price}")
# 死叉:快线下穿慢线
elif fastValue < slowValue and self.Portfolio[self.spy].IsLong:
self.Liquidate(self.spy)
self.Debug(f"SELL at {data[self.spy].Price}")
3.1.4 Run the Backtest¶
# 本地回测
lean backtest "SimpleMovingAverage"
# 查看结果
lean backtest "SimpleMovingAverage" --output ./results
3.2 Understanding Lean's Core Concepts¶
3.2.1 Data Flow¶
时间流逝 → 新数据到达 → OnData() 被调用 → 执行交易逻辑
3.2.2 Lifecycle¶
Initialize() → OnData()循环 → OnEndOfDay() → OnEndOfAlgorithm()
3.2.3 Key Objects¶
| Object | Description | Common Properties/Methods |
|---|---|---|
Portfolio |
Portfolio | Cash, TotalPortfolioValue, Invested |
Securities |
Securities collection | Price, Holdings, Symbol |
Time |
Current time | DateTime type |
Transactions |
Transaction management | GetOpenOrders(), CancelOrder() |
3.3 Common Commands Cheat Sheet¶
# 项目管理
# 项目就是工作区目录下的文件夹,可用 ls 直接查看
lean project-create "<项目名>" --language python
lean project-delete "<项目名>"
# 回测
lean backtest "<项目名>"
lean backtest "<项目名>" --output ./results
# 研究
lean research "<项目名>"
# 优化
lean optimize "<项目名>"
# 实盘
lean live deploy "<项目名>" --brokerage "Paper Trading"
3.4 Viewing Backtest Results¶
After the backtest completes, the results include:
3.4.1 Statistical Metrics¶
| Metric | Description |
|---|---|
| Total Return | Total return |
| Sharpe Ratio | Risk-adjusted return |
| Sortino Ratio | Downside-risk-adjusted return |
| Drawdown | Maximum drawdown |
| Win Rate | Win rate |
| Total Trades | Total number of trades |
3.4.2 Charts¶
- Equity curve
- Drawdown chart
- Holdings distribution
- Daily returns
3.5 Complete Example: Multi-Stock Momentum Strategy¶
from AlgorithmImports import *
import numpy as np
class MultiStockMomentumAlgorithm(QCAlgorithm):
"""
多股票动量策略
逻辑:
1. 每月第一个交易日计算过去3个月收益率
2. 买入表现最好的前10只股票
3. 等权重分配
"""
def Initialize(self):
self.SetStartDate(2018, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
# 设置 Universe(粗筛选 + 精筛选)
self.AddUniverse(
self.CoarseSelectionFunction,
self.FineSelectionFunction
)
# 设置每月第一个交易日调仓
self.Schedule.On(
self.DateRules.MonthStart(),
self.TimeRules.AfterMarketOpen("SPY", 30),
self.Rebalance
)
self._monthly_rebalance = True
self._lastMonth = -1
# 保存选中的股票
self.selectedSymbols = []
def CoarseSelectionFunction(self, coarse):
"""
粗筛选:按市值和交易量筛选
"""
# 筛选价格>10美元,交易量>100万的股票
filtered = [c for c in coarse
if c.Price > 10 and c.Volume > 1000000]
# 按美元交易量排序,取前500
sortedByVolume = sorted(
filtered,
key=lambda c: c.DollarVolume,
reverse=True
)
return [c.Symbol for c in sortedByVolume[:500]]
def FineSelectionFunction(self, fine):
"""
精筛选:计算动量并选择
"""
if self._monthly_rebalance:
# 筛选有足够数据的股票
filtered = [f for f in fine
if f.EarningReports.BasicAverageShares.ThreeMonths > 0]
# 获取3个月前的历史价格
history = self.History(
[f.Symbol for f in filtered],
TimeSpan.FromDays(90),
Resolution.Daily
)
# 计算动量
momentums = {}
for f in filtered:
symbol = f.Symbol
if symbol in history:
prices = history.loc[symbol]['close']
if len(prices) > 0:
momentum = (prices[-1] - prices[0]) / prices[0]
momentums[symbol] = momentum
# 选择动量最高的前10只
sortedByMomentum = sorted(
momentums.items(),
key=lambda x: x[1],
reverse=True
)
self.selectedSymbols = [x[0] for x in sortedByMomentum[:10]]
self._monthly_rebalance = False
return self.selectedSymbols
def Rebalance(self):
"""
调仓函数
"""
# 检查是否是新月份
if self.Time.month == self._lastMonth:
return
self._lastMonth = self.Time.month
self._monthly_rebalance = True
# 平仓所有不在新列表中的股票
for holding in self.Portfolio.Values:
if holding.Invested and holding.Symbol not in self.selectedSymbols:
self.Liquidate(holding.Symbol)
# 等权重买入新选中的股票
for symbol in self.selectedSymbols:
self.SetHoldings(symbol, 0.1)
self.Debug(f"Rebalanced at {self.Time}")
def OnData(self, data):
'''不需要特别处理,由调仓函数处理'''
pass
3.6 Debugging Tips¶
3.6.1 Using Debug Output¶
self.Debug("This is a debug message")
self.Log("This will appear in the log")
self.Error("This is an error message")
3.6.2 Using Plot for Charts¶
def Initialize(self):
# ...
# 添加自定义图表
self.PlotIndicator("Strategy", self.fast)
self.PlotIndicator("Strategy", self.slow)
# 或在 OnData 中
def OnData(self, data):
self.Plot("Portfolio", "Value", self.Portfolio.TotalPortfolioValue)
self.Plot("Portfolio", "Cash", self.Portfolio.Cash)
3.7 Next Steps¶
You now know the basics of using Lean. The next chapter covers QCAlgorithm fundamentals in detail.