Skip to content

title: Chapter 8: Algorithm Framework

Chapter 8: Algorithm Framework — Modular Strategy Development

This chapter introduces modular strategy development with the Lean Framework, splitting a strategy into five models: Alpha, Portfolio Construction, Execution, Risk, and Universe Selection.

8.1 Framework Overview

8.1.1 Why Use the Framework?

A traditional strategy puts all logic in a single class:

class TraditionalStrategy(QCAlgorithm):
    def OnData(self, data):
        # 信号生成
        # 组合构建
        # 订单执行
        # 风险控制
        # 全部混在一起...

The Framework splits the strategy into independent modules:

┌─────────────────────────────────────────────────────┐
│                  QCAlgorithm                         │
│  ┌─────────────┐  ┌──────────────┐  ┌────────────┐  │
│  │ Alpha Model │─>│ Portfolio    │─>│ Execution  │  │
│  │ (信号生成)   │  │ Construction │  │ (执行)     │  │
│  └─────────────┘  │ (组合构建)    │  └────────────┘  │
│                   └──────────────┘                   │
│  ┌─────────────┐  ┌──────────────┐                 │
│  │ Risk Model  │  │ Universe     │                 │
│  │ (风险控制)   │  │ Selection    │                 │
│  └─────────────┘  │ (证券选择)    │                 │
│                   └──────────────┘                   │
└─────────────────────────────────────────────────────┘

8.1.2 The Five Models

Model Responsibility Output
Alpha Model Generates trading signals Insight objects
Portfolio Construction Converts Insights into target weights PortfolioTarget
Execution Model Executes trade orders OrderTicket
Risk Model Monitors and manages risk PortfolioTarget
Universe Selection Selects tradable instruments Symbol list

8.2 Alpha Model

8.2.1 The Insight Object

An Insight is the output of the Alpha Model, representing a prediction about future prices:

from AlgorithmImports import *

# 创建 Insight
insight = Insight.Price(
    symbol,                    # Symbol
    TimeSpan.FromDays(7),      # 持有期
    InsightDirection.Up        # 方向: Up/Down/Flat
)

# Insight 属性
insight.Symbol      # 证券
insight.Direction   # 方向
insight.Magnitude   # 预测强度 (0-1)
insight.CloseTimeUtc  # 过期时间 (UTC)
insight.Period      # 持有期间

8.2.2 A Simple Alpha Model

class RsiAlphaModel(AlphaModel):
    """
    RSI Alpha 模型

    生成规则:
    - RSI < 30: 买入信号 (Up)
    - RSI > 70: 卖出信号 (Down)
    - 其他: 持有/观望 (Flat)
    """

    def __init__(self, period=14, overbought=70, oversold=30):
        self.period = period
        self.overbought = overbought
        self.oversold = oversold
        self.rsi_indicators = {}

    def Update(self, algorithm, data):
        """生成信号"""
        insights = []

        for symbol, rsi in self.rsi_indicators.items():
            if not rsi.IsReady:
                continue

            rsi_value = rsi.Current.Value

            # 超卖:买入信号
            if rsi_value < self.oversold:
                insights.append(Insight.Price(
                    symbol,
                    TimeSpan.FromDays(7),
                    InsightDirection.Up,
                    magnitude=(self.oversold - rsi_value) / self.oversold
                ))

            # 超买:卖出信号
            elif rsi_value > self.overbought:
                insights.append(Insight.Price(
                    symbol,
                    TimeSpan.FromDays(7),
                    InsightDirection.Down,
                    magnitude=(rsi_value - self.overbought) / (100 - self.overbought)
                ))

        return insights

    def OnSecuritiesChanged(self, algorithm, changes):
        """证券变化时创建/移除指标"""
        for added in changes.AddedSecurities:
            symbol = added.Symbol
            self.rsi_indicators[symbol] = algorithm.RSI(symbol, self.period)

        for removed in changes.RemovedSecurities:
            if removed.Symbol in self.rsi_indicators:
                del self.rsi_indicators[removed.Symbol]

8.2.3 Composite Alpha Model

class CompositeAlphaModel(AlphaModel):
    """
    复合 Alpha 模型

    结合多个信号源的 Alpha Model
    """

    def __init__(self):
        self.alpha_models = [
            RsiAlphaModel(),      # 8.2.2 中定义的自定义模型
            MacdAlphaModel()      # Lean 内置模型(Algorithm.Framework/Alphas)
        ]

    def Update(self, algorithm, data):
        """聚合所有模型的信号"""
        all_insights = []

        for alpha_model in self.alpha_models:
            insights = alpha_model.Update(algorithm, data)
            all_insights.extend(insights)

        return all_insights

    def OnSecuritiesChanged(self, algorithm, changes):
        """传递给所有子模型"""
        for alpha_model in self.alpha_models:
            alpha_model.OnSecuritiesChanged(algorithm, changes)

8.3 Portfolio Construction Model

8.3.1 Basic Portfolio Construction Model

class EqualWeightingPortfolioConstructionModel(PortfolioConstructionModel):
    """
    等权重组合构建模型

    所有 Insight 获得相同的资金分配
    """

    def CreateTargets(self, algorithm, insights):
        """创建组合目标"""
        targets = []

        if not insights:
            return targets

        # 计算权重
        long_count = sum(1 for i in insights if i.Direction == InsightDirection.Up)
        short_count = sum(1 for i in insights if i.Direction == InsightDirection.Down)

        long_weight = 1.0 / long_count if long_count > 0 else 0
        short_weight = 1.0 / short_count if short_count > 0 else 0

        # 创建目标
        for insight in insights:
            if insight.Direction == InsightDirection.Up:
                targets.append(PortfolioTarget.Percent(
                    insight.Symbol,
                    long_weight * insight.Magnitude
                ))
            elif insight.Direction == InsightDirection.Down:
                targets.append(PortfolioTarget.Percent(
                    insight.Symbol,
                    -short_weight * insight.Magnitude
                ))

        return targets

8.3.2 Black-Litterman Model

class BlackLittermanPortfolioModel(PortfolioConstructionModel):
    """
    Black-Litterman 组合模型

    结合市场均衡和投资者观点
    """

    def __init__(self, rebalance=Expiry.EndOfMonth, portfolioBias=PortfolioBias.LongShort):
        self.rebalance = rebalance
        self.portfolioBias = portfolioBias
        self.symbolData = {}

    def CreateTargets(self, algorithm, insights):
        """基于 Black-Litterman 创建目标"""
        # 这里简化实现
        # 实际需要实现完整的 BL 模型

        targets = []

        for insight in insights:
            # 根据 Insight 的 Magnitude 分配权重
            weight = insight.Magnitude / len(insights)

            if self.portfolioBias == PortfolioBias.Long:
                weight = abs(weight)

            targets.append(PortfolioTarget.Percent(
                insight.Symbol,
                weight
            ))

        return targets

8.4 Execution Model

8.4.1 Immediate Execution Model

class ImmediateExecutionModel(ExecutionModel):
    """
    立即执行模型

    收到目标后立即下单
    """

    def Execute(self, algorithm, targets):
        """执行目标"""
        for target in targets:
            # 计算需要交易的数量
            if not algorithm.Portfolio.ContainsKey(target.Symbol):
                continue

            holdings = algorithm.Portfolio[target.Symbol]

            # 目标数量减去当前持仓,得到需要交易的数量
            # 注意:PortfolioTarget.Quantity 是目标股数;
            # CalculateOrderQuantity 的第二参是目标持仓百分比,勿混用
            quantity = target.Quantity - holdings.Quantity

            if quantity != 0:
                algorithm.MarketOrder(target.Symbol, quantity)

8.4.2 VWAP Execution Model

class VwapExecutionModel(ExecutionModel):
    """
    VWAP 执行模型

    在一段时间内分批执行,追求接近 VWAP 价格
    """

    def __init__(self, period=TimeSpan.FromMinutes(30)):
        self.period = period
        self.targets = {}
        self.executed_symbols = set()

    def Execute(self, algorithm, targets):
        """执行目标"""
        for target in targets:
            symbol = target.Symbol

            # 新目标
            if symbol not in self.targets:
                self.targets[symbol] = {
                    'target': target,
                    'remaining': target.Quantity,
                    'start_time': algorithm.Time
                }

            # 检查是否完成
            if self.targets[symbol]['remaining'] <= 0:
                continue

            # 计算本次应该执行的数量
            # (.NET TimeSpan 用 TotalSeconds 属性)
            time_elapsed = (algorithm.Time - self.targets[symbol]['start_time']).TotalSeconds
            total_period = self.period.TotalSeconds

            if time_elapsed >= total_period:
                # 时间到,立即完成剩余
                quantity = self.targets[symbol]['remaining']
            else:
                # 按时间比例执行
                quantity = int(self.targets[symbol]['target'].Quantity *
                             (time_elapsed / total_period)) - \
                         (self.targets[symbol]['target'].Quantity - self.targets[symbol]['remaining'])

            if quantity != 0:
                algorithm.MarketOrder(symbol, quantity)
                self.targets[symbol]['remaining'] -= quantity

8.5 Risk Model

8.5.1 Maximum Drawdown Risk Model

class MaxDrawdownRiskManagementModel(RiskManagementModel):
    """
    最大回撤风险管理模型

    当组合回撤超过阈值时平仓
    """

    def __init__(self, max_drawdown=0.1):
        self.max_drawdown = max_drawdown
        self.high_watermark = None

    def ManageRisk(self, algorithm, targets):
        """管理风险"""
        portfolio_value = algorithm.Portfolio.TotalPortfolioValue

        # 更新最高水位
        if self.high_watermark is None or portfolio_value > self.high_watermark:
            self.high_watermark = portfolio_value
            return targets  # 正常,返回原目标

        # 计算回撤
        drawdown = (self.high_watermark - portfolio_value) / self.high_watermark

        if drawdown > self.max_drawdown:
            # 超过最大回撤,平掉所有持仓
            algorithm.Debug(f"Max drawdown exceeded: {drawdown:.2%}. Liquidating all positions.")
            algorithm.Liquidate()

            return []  # 清空所有目标

        return targets

8.5.2 Maximum Single-Position Risk Model

class MaxPositionSizeRiskModel(RiskManagementModel):
    """
    单股最大持仓风险管理模型
    """

    def __init__(self, max_position_size=0.2):
        self.max_position_size = max_position_size

    def ManageRisk(self, algorithm, targets):
        """管理风险"""
        filtered_targets = []

        for target in targets:
            # 计算目标持仓占比
            target_value = abs(target.Quantity) * algorithm.Securities[target.Symbol].Price
            portfolio_value = algorithm.Portfolio.TotalPortfolioValue

            if portfolio_value > 0:
                position_size = target_value / portfolio_value

                if position_size > self.max_position_size:
                    # 超过限制,调整到最大值
                    adjusted_quantity = int(
                        (self.max_position_size * portfolio_value) /
                        algorithm.Securities[target.Symbol].Price
                    )

                    if target.Quantity > 0:
                        adjusted_quantity = abs(adjusted_quantity)
                    else:
                        adjusted_quantity = -abs(adjusted_quantity)

                    target = PortfolioTarget(target.Symbol, adjusted_quantity)

            filtered_targets.append(target)

        return filtered_targets

8.6 Complete Framework Strategy Example

from AlgorithmImports import *

class FrameworkStrategyAlgorithm(QCAlgorithm):
    """
    完整的 Framework 策略

    使用所有五个模型构建
    """

    def Initialize(self):
        self.SetStartDate(2020, 1, 1)
        self.SetEndDate(2023, 12, 31)
        self.SetCash(100000)

        # 设置 Universe:惯用入口是 AddUniverse(粗筛 + 精筛)
        # 注意:Framework 模式下 SetUniverseSelection 只接受
        # IUniverseSelectionModel(如 ManualUniverseSelectionModel),
        # 不能传入 Universe 对象
        self.AddUniverse(self.CoarseSelection, self.FineSelection)

        # 设置 Alpha 模型
        self.SetAlpha(RsiAlphaModel(period=14, overbought=70, oversold=30))

        # 设置组合构建模型
        self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())

        # 设置执行模型
        self.SetExecution(ImmediateExecutionModel())

        # 设置风险管理模型
        self.SetRiskManagement(MaxDrawdownRiskManagementModel(max_drawdown=0.15))

        # 设置预热
        self.SetWarmUp(TimeSpan.FromDays(30))

    def CoarseSelection(self, coarse):
        """粗筛选"""
        filtered = [c for c in coarse if c.Price > 10 and c.Volume > 1000000]
        sorted_by_volume = sorted(filtered, key=lambda c: c.DollarVolume, reverse=True)
        return [c.Symbol for c in sorted_by_volume[:100]]

    def FineSelection(self, fine):
        """精筛选"""
        filtered = [f for f in fine if 0 < f.ValuationRatios.PERatio < 30]
        sorted_by_pe = sorted(filtered, key=lambda f: f.ValuationRatios.PERatio)
        return [f.Symbol for f in sorted_by_pe[:20]]