title: Chapter 6: Technical Indicators¶
Chapter 6: Technical Indicators¶
This chapter takes a detailed look at using technical indicators in Lean, including built-in indicators, custom indicators, and indicator warm-up.
6.1 Indicator Overview¶
Lean provides a rich library of technical indicators in the QuantConnect.Indicators namespace.
6.1.1 Indicator Categories¶
| Category | Common Indicators |
|---|---|
| Trend | SMA, EMA, MACD |
| Momentum | RSI, Stochastic, ROC |
| Volatility | ATR, Bollinger Bands, Standard Deviation |
| Volume | OBV, VWAP, Money Flow Index |
6.2 Using Built-in Indicators¶
6.2.1 Moving Averages¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# 简单移动平均线
self.sma_20 = self.SMA(self.spy, 20, Resolution.Daily)
self.sma_50 = self.SMA(self.spy, 50)
# 指数移动平均线
self.ema_12 = self.EMA(self.spy, 12)
self.ema_26 = self.EMA(self.spy, 26)
# 加权移动平均线(API 名为 LWMA)
self.lwma = self.LWMA(self.spy, 20)
# 三角移动平均线(API 名为 TRIMA)
self.trima = self.TRIMA(self.spy, 20)
6.2.2 Trend Indicators¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# MACD (12, 26, 9)
self.macd = self.MACD(self.spy, 12, 26, 9, MovingAverageType.Exponential)
# 访问 MACD 组件
# self.macd.Fast # 快线
# self.macd.Slow # 慢线
# self.macd.Signal # 信号线
# self.macd.Histogram # 柱状图
def OnData(self, data):
if not self.macd.IsReady:
return
# 金叉:MACD 上穿信号线
if self.macd.Current.Value > self.macd.Signal.Current.Value:
# ...
6.2.3 Momentum Indicators¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# RSI (14)
self.rsi = self.RSI(self.spy, 14, MovingAverageType.Simple)
# 随机指标 (14, 3, 3)(API 名为 STO,成员为 StochK / StochD)
self.stoch = self.STO(self.spy, 14, 3, 3, Resolution.Daily)
# 变化率
self.roc = self.ROC(self.spy, 10)
# 威廉指标(API 名为 WILR)
self.wilr = self.WILR(self.spy, 14)
6.2.4 Volatility Indicators¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# ATR (平均真实波幅)
self.atr = self.ATR(self.spy, 14, MovingAverageType.Simple)
# 布林带 (20, 2)
self.bb = self.BB(self.spy, 20, 2, MovingAverageType.Simple)
# 标准差
self.std = self.STD(self.spy, 20)
def OnData(self, data):
if not self.bb.IsReady:
return
# 布林带组件
middle_band = self.bb.MiddleBand.Current.Value
upper_band = self.bb.UpperBand.Current.Value
lower_band = self.bb.LowerBand.Current.Value
bandwidth = self.bb.BandWidth.Current.Value # 注意是大写 W:BandWidth
# 布林带挤压
if bandwidth < 0.1: # 低波动率
self.Debug("Bollinger Band Squeeze detected")
6.2.5 Volume Indicators¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# 成交量加权平均价
self.vwap = self.VWAP(self.spy)
# 能量潮
self.obv = self.OBV(self.spy)
# 资金流量指数
self.mfi = self.MFI(self.spy, 14)
6.3 Indicator Properties and Methods¶
6.3.1 Common Properties¶
def OnData(self, data):
indicator = self.sma_20
# 检查是否就绪
if indicator.IsReady:
# 获取当前值
current_value = indicator.Current.Value
# 获取历史值
samples = indicator.Samples # 样本数
warm_up_period = indicator.WarmUpPeriod # 预热期
# 获取多个历史值
for i in range(5):
value = indicator.Current.Value # 最新的值
6.3.2 Indicator Updates¶
# 指标自动更新(默认行为)
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
self.sma = self.SMA(self.spy, 20) # 自动更新
# 手动更新指标
def Initialize(self):
self.sma = SimpleMovingAverage(20)
self.RegisterIndicator("SPY", self.sma, Resolution.Daily)
def OnData(self, data):
if data.ContainsKey("SPY") and data["SPY"] is not None:
# 手动更新
self.sma.Update(data["SPY"].EndTime, data["SPY"].Close)
6.4 Indicator Warm-Up¶
6.4.1 Global Warm-Up¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# 方式1:设置时间预热
self.SetWarmUp(TimeSpan.FromDays(100))
# 方式2:设置柱数预热
self.SetWarmUp(100)
# 预热后,所有指标立即就绪
self.sma = self.SMA(self.spy, 50) # 立即可用
6.4.2 Warming Up a Single Indicator¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
self.sma = SMA(self.spy, 50, Resolution.Daily)
# 预热特定指标
self.WarmUpIndicator(self.spy, self.sma, TimeSpan.FromDays(50))
def OnData(self, data):
# sma 立即可用
if self.sma.IsReady:
pass
6.4.3 Warm-Up with Historical Data¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
self.sma = self.SMA(self.spy, 50)
# 获取历史数据预热
history = self.History(self.spy, 50, Resolution.Daily)
# 注意:Python 的 History 返回 pandas DataFrame,
# 不能按 bar 对象迭代;用 iterrows 逐行遍历,
# 行索引是每根 bar 的 EndTime,列名为小写('close' 等)
for index, row in history.iterrows():
self.sma.Update(index, row['close'])
6.5 Custom Indicators¶
6.5.1 A Simple Custom Indicator¶
class CustomIndicator(PythonIndicator):
"""
自定义指标示例:价格动量指标
计算价格相对于 N 天前的变化百分比
"""
def __init__(self, period):
self.Period = period
self.Value = 0
self._prices = RollingWindow[float](period)
def Update(self, input):
"""
更新指标
Args:
input: IBaseData 对象,通常是 TradeBar
"""
# 添加新价格
self._prices.Add(input.Value)
# 如果窗口未满,返回 False
if not self._prices.IsReady:
return False
# 计算动量
current_price = self._prices[0] # 最新价格
past_price = self._prices[self.Period-1] # N 天前价格
self.Value = (current_price / past_price - 1) * 100
return True
6.5.2 Using a Custom Indicator¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# 创建自定义指标
self.momentum = CustomIndicator(20)
# 注册指标
self.RegisterIndicator(self.spy, self.momentum, Resolution.Daily)
6.5.3 A More Complex Custom Indicator¶
class AdaptiveMovingAverage(PythonIndicator):
"""
自适应移动平均线 (AMA)
根据市场波动率调整移动平均速度
"""
def __init__(self, fast_period=2, slow_period=30):
self.Value = 0
self._fast_alpha = 2 / (fast_period + 1)
self._slow_alpha = 2 / (slow_period + 1)
self._prev_value = 0
self._is_ready = False
# 用于计算效率比率
self._price_changes = RollingWindow[float](10)
@property
def IsReady(self):
return self._is_ready
@property
def WarmUpPeriod(self):
return 10
def Update(self, input):
if not self._is_ready:
self._prev_value = input.Value
self._price_changes.Add(input.Value)
if self._price_changes.IsReady:
self._is_ready = True
return self._is_ready
# 计算方向性
direction = abs(input.Value - self._price_changes[self._price_changes.Count-1])
volatility = sum(abs(input.Value - self._price_changes[i])
for i in range(self._price_changes.Count))
# 效率比率
er = direction / volatility if volatility != 0 else 0
# 自适应平滑系数
sc = (er * (self._fast_alpha - self._slow_alpha) + self._slow_alpha) ** 2
# 计算 AMA
self.Value = self._prev_value + sc * (input.Value - self._prev_value)
self._prev_value = self.Value
self._price_changes.Add(input.Value)
return True
6.6 Combining Indicators¶
6.6.1 Composite Indicators¶
def Initialize(self):
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# 创建多个指标
self.sma = self.SMA(self.spy, 20)
self.std = self.STD(self.spy, 20)
# 创建布林带组件(手动)
# 注意:类名是 IndicatorExtensions(复数,没有单数的 IndicatorExtension);
# 它也没有接收 lambda 的组合方法,四则组合用 Plus / Minus / Times / Over
two_std = IndicatorExtensions.Times(self.std, 2) # 2 倍标准差
self.upper_band = IndicatorExtensions.Plus(self.sma, two_std) # SMA + 2×STD
6.6.2 Combining Indicator Signals¶
def OnData(self, data):
# 获取多个指标信号
signals = []
# MA 信号
if self.sma_20.Current.Value > self.sma_50.Current.Value:
signals.append("MA_Bullish")
# RSI 信号
if self.rsi.Current.Value < 30:
signals.append("RSI_Oversold")
elif self.rsi.Current.Value > 70:
signals.append("RSI_Overbought")
# MACD 信号
if self.macd.Histogram.Current.Value > 0:
signals.append("MACD_Positive")
# 综合信号
if len(signals) >= 2:
self.Debug(f"Combined signals: {signals}")
6.7 Complete Example: Multi-Indicator Strategy¶
from AlgorithmImports import *
class MultiIndicatorStrategy(QCAlgorithm):
"""
多指标组合策略
条件:
1. 短期 MA > 长期 MA (趋势向上)
2. RSI < 70 (不超买)
3. 价格 > 布林带中轨 (不在弱势)
4. MACD 柱状图 > 0 (动量向上)
"""
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
# 指标
self.sma_20 = self.SMA(self.spy, 20)
self.sma_50 = self.SMA(self.spy, 50)
self.rsi = self.RSI(self.spy, 14)
self.bb = self.BB(self.spy, 20, 2)
self.macd = self.MACD(self.spy, 12, 26, 9)
# 预热
self.SetWarmUp(TimeSpan.FromDays(60))
def OnData(self, data):
if not self.IsIndicatorsReady():
return
price = data[self.spy].Price
# 检查买入条件
if self.CheckBuyConditions():
if not self.Portfolio[self.spy].IsLong:
self.SetHoldings(self.spy, 1)
self.Debug(f"Buy at {price}")
# 检查卖出条件
elif self.CheckSellConditions():
if self.Portfolio[self.spy].IsLong:
self.Liquidate(self.spy)
self.Debug(f"Sell at {price}")
def IsIndicatorsReady(self):
"""检查所有指标是否就绪"""
return (self.sma_20.IsReady and
self.sma_50.IsReady and
self.rsi.IsReady and
self.bb.IsReady and
self.macd.IsReady)
def CheckBuyConditions(self):
"""检查买入条件"""
conditions = [
self.sma_20.Current.Value > self.sma_50.Current.Value,
self.rsi.Current.Value < 70,
self.Securities[self.spy].Price > self.bb.MiddleBand.Current.Value,
self.macd.Histogram.Current.Value > 0
]
return all(conditions)
def CheckSellConditions(self):
"""检查卖出条件"""
conditions = [
self.sma_20.Current.Value < self.sma_50.Current.Value,
self.rsi.Current.Value > 70
]
return any(conditions)