附录:示例策略库¶
本附录提供完整的可运行策略示例。
B.1 基础策略示例¶
双均线交叉策略¶
from AlgorithmImports import *
class DualMovingAverageCross(QCAlgorithm):
"""
双均线交叉策略
逻辑:
- 短期均线上穿长期均线(金叉)时买入
- 短期均线下穿长期均线(死叉)时卖出
"""
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_fast = self.SMA(self.spy, 20, Resolution.Daily)
self.sma_slow = self.SMA(self.spy, 50, Resolution.Daily)
self.SetWarmUp(TimeSpan.FromDays(60))
def OnData(self, data):
if not self.sma_fast.IsReady:
return
if self.sma_fast.Current.Value > self.sma_slow.Current.Value:
if not self.Portfolio[self.spy].IsLong:
self.SetHoldings(self.spy, 1)
self.Debug(f"[BUY] {self.Time.date()}")
else:
if self.Portfolio[self.spy].IsLong:
self.Liquidate(self.spy)
self.Debug(f"[SELL] {self.Time.date()}")
RSI 均值回归策略¶
from AlgorithmImports import *
class RsiMeanReversion(QCAlgorithm):
"""
RSI 均值回归策略
逻辑:
- RSI < 30(超卖)时买入
- RSI > 70(超买)时卖出
"""
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.rsi = self.RSI(self.spy, 14, Resolution.Daily)
self.SetWarmUp(TimeSpan.FromDays(30))
def OnData(self, data):
if not self.rsi.IsReady:
return
rsi = self.rsi.Current.Value
if rsi < 30 and not self.Portfolio[self.spy].IsLong:
self.SetHoldings(self.spy, 1)
self.Debug(f"[BUY] RSI: {rsi:.2f}")
elif rsi > 70 and self.Portfolio[self.spy].IsLong:
self.Liquidate(self.spy)
self.Debug(f"[SELL] RSI: {rsi:.2f}")
B.2 高级策略示例¶
多因子选股策略¶
from AlgorithmImports import *
class MultiFactorStrategy(QCAlgorithm):
"""
多因子选股策略
因子:
1. 动量因子:3个月收益率
2. 价值因子:PE比率
3. 质量因子:ROE
"""
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
# Universe选择:粗筛 + 精筛
# (FineFundamentalUniverse 没有带名称的 5 参构造,标准写法是
# AddUniverse(粗筛函数, 精筛函数))
self.AddUniverse(self.CoarseSelection, self.FineSelection)
# 调度:每月调仓
self.Schedule.On(
self.DateRules.MonthStart(),
self.TimeRules.AfterMarketOpen("SPY", 30),
self.Rebalance
)
self.selected_symbols = []
def CoarseSelection(self, coarse):
"""粗筛选:按市值和交易量"""
filtered = [c for c in coarse
if c.HasFundamentalData and
c.Price > 10 and
c.DollarVolume > 1000000]
sorted_by_volume = sorted(filtered, key=lambda c: c.DollarVolume, reverse=True)
return [c.Symbol for c in sorted_by_volume[:300]]
def FineSelection(self, fine):
"""精筛选:多因子评分"""
scores = []
for f in fine:
# 跳过数据缺失
if (f.ValuationRatios.PERatio <= 0 or
f.OperationRatios.ROE.Value is None):
continue
# 动量得分:价格相对3月前涨幅
momentum_score = 0
# 价值得分:PE越低越好
pe_score = 1 / min(f.ValuationRatios.PERatio, 100)
# 质量得分:ROE越高越好
quality_score = min(f.OperationRatios.ROE.Value / 0.1, 2)
# 综合得分
total_score = momentum_score + pe_score + quality_score
scores.append((total_score, f.Symbol))
# 选择得分最高的20只
sorted_scores = sorted(scores, key=lambda x: x[0], reverse=True)
self.selected_symbols = [s[1] for s in sorted_scores[:20]]
return self.selected_symbols
def Rebalance(self):
"""调仓"""
# 平仓不在列表中的(Portfolio 通过 Keys 遍历,没有 Items() 方法)
for symbol in self.Portfolio.Keys:
holding = self.Portfolio[symbol]
if holding.Invested and symbol not in self.selected_symbols:
self.Liquidate(symbol)
# 等权买入
if self.selected_symbols:
weight = 1.0 / len(self.selected_symbols)
for symbol in self.selected_symbols:
self.SetHoldings(symbol, weight)
配对交易策略¶
from AlgorithmImports import *
class PairsTradingStrategy(QCAlgorithm):
"""
配对交易策略
逻辑:
- 两个高度相关的股票
- 当价差异超过2倍标准差时开仓
- 价差回归到0时平仓
"""
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
# 选择一对相关性高的股票
self.stock1 = self.AddEquity("KO", Resolution.Daily).Symbol # 可口可乐
self.stock2 = self.AddEquity("PEP", Resolution.Daily).Symbol # 百事可乐
# 计算价差的参数
self.hedge_ratio = 1.0 # 对冲比率
# 计算价差的窗口
self.spread_window = 20
self.spread_std_multiplier = 2
self.SetWarmUp(TimeSpan.FromDays(30))
def OnData(self, data):
# 获取历史数据计算价差
history = self.History(
[self.stock1, self.stock2],
self.spread_window + 10,
Resolution.Daily
)
if history.empty or len(history) < self.spread_window:
return
# 计算价差:stock1价格 - hedge_ratio * stock2价格
spread = history['close'][self.stock1] - self.hedge_ratio * history['close'][self.stock2]
# 计算价差的均值和标准差
spread_mean = spread.rolling(self.spread_window).mean().iloc[-1]
spread_std = spread.rolling(self.spread_window).std().iloc[-1]
# 当前价差
current_spread = data[self.stock1].Price - self.hedge_ratio * data[self.stock2].Price
# 获取持仓
holding1 = self.Portfolio[self.stock1]
holding2 = self.Portfolio[self.stock2]
# 检查开仓信号
if not holding1.Invested and not holding2.Invested:
z_score = (current_spread - spread_mean) / spread_std if spread_std > 0 else 0
# 价差异常扩大时开仓
if z_score > 2: # stock1相对昂贵
self.Sell(self.stock1, 100)
self.Buy(self.stock2, int(100 * self.hedge_ratio))
self.Debug(f"[OPEN] Spread: {current_spread:.2f}, Z: {z_score:.2f}")
elif z_score < -2: # stock2相对昂贵
self.Buy(self.stock1, 100)
self.Sell(self.stock2, int(100 * self.hedge_ratio))
self.Debug(f"[OPEN] Spread: {current_spread:.2f}, Z: {z_score:.2f}")
# 检查平仓信号
elif holding1.Invested and holding2.Invested:
z_score = (current_spread - spread_mean) / spread_std if spread_std > 0 else 0
# 价差回归到0附近时平仓
if abs(z_score) < 0.5:
self.Liquidate(self.stock1)
self.Liquidate(self.stock2)
self.Debug(f"[CLOSE] Spread normalized, Z: {z_score:.2f}")
波动率策略¶
from AlgorithmImports import *
class VolatilityStrategy(QCAlgorithm):
"""
波动率策略
逻辑:
- 使用 ATR 衡量市场波动率
- 低波动率时买入
- 高波动率时减仓
"""
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.vix = self.AddEquity("VIX", Resolution.Daily).Symbol
# 指标
self.atr = self.ATR(self.spy, 14, Resolution.Daily)
self.atr_sma = self.SMA(self.atr, 50, Resolution.Daily)
self.SetWarmUp(TimeSpan.FromDays(60))
# 波动率状态
self.volatility_state = None
def OnData(self, data):
if not self.atr.IsReady:
return
# 计算相对波动率
current_atr = self.atr.Current.Value
avg_atr = self.atr_sma.Current.Value
relative_vol = current_atr / avg_atr if avg_atr > 0 else 1
# 获取VIX
vix = self.Securities[self.vix].Price
# 判断波动率状态
if relative_vol < 0.8 and vix < 20:
# 低波动
if self.volatility_state != "low":
self.volatility_state = "low"
# 增加仓位
if not self.Portfolio[self.spy].IsLong:
self.SetHoldings(self.spy, 1)
self.Debug(f"[LOW VOL] Vol: {relative_vol:.2f}, VIX: {vix:.2f}")
elif relative_vol > 1.2 or vix > 30:
# 高波动
if self.volatility_state != "high":
self.volatility_state = "high"
# 减仓
if self.Portfolio[self.spy].IsLong:
self.SetHoldings(self.spy, 0.5)
self.Debug(f"[HIGH VOL] Vol: {relative_vol:.2f}, VIX: {vix:.2f}")
B.3 完整策略框架示例¶
from AlgorithmImports import *
class CompleteStrategy(QCAlgorithm):
"""
完整的框架策略示例
包含:
- Alpha 模型
- 组合构建
- 执行模型
- 风险管理
- Universe 选择
"""
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
# Universe
symbols = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]
self.SetUniverseSelection(
ManualUniverseSelectionModel(
[self.AddEquity(s, Resolution.Daily).Symbol for s in symbols]
)
)
# 框架模型
# 注意:内置已有 RsiAlphaModel,为避免名称冲突,
# 下面自定义的 RSI Alpha 模型命名为 CustomRsiAlphaModel
self.SetAlpha(CustomRsiAlphaModel())
self.SetPortfolioConstruction(
EqualWeightingPortfolioConstructionModel()
)
self.SetExecution(ImmediateExecutionModel())
# 内置风险管理模型:MaximumDrawdownPercentPerSecurity,
# 构造参数为最大回撤百分比(小数)
self.SetRiskManagement(
MaximumDrawdownPercentPerSecurity(0.15)
)
self.SetWarmUp(TimeSpan.FromDays(60))
class CustomRsiAlphaModel(AlphaModel):
"""自定义 RSI Alpha 模型"""
def __init__(self, period=14, oversold=30, overbought=70):
self.period = period
self.oversold = oversold
self.overbought = overbought
self.rsi_indicators = {}
def Update(self, algorithm, data):
insights = []
for symbol, rsi in self.rsi_indicators.items():
if not rsi.IsReady:
continue
if rsi.Current.Value < self.oversold:
insights.append(Insight.Price(
symbol,
TimeSpan.FromDays(7),
InsightDirection.Up
))
elif rsi.Current.Value > self.overbought:
insights.append(Insight.Price(
symbol,
TimeSpan.FromDays(7),
InsightDirection.Down
))
return insights
def OnSecuritiesChanged(self, algorithm, changes):
for added in changes.AddedSecurities:
symbol = added.Symbol
if symbol not in self.rsi_indicators:
self.rsi_indicators[symbol] = algorithm.RSI(symbol, self.period)