Chapter 5: Investment Strategy Design¶
Notes - This chapter mixes two kinds of content: the real
qlib.strategy.base.BaseStrategyentry point, and teaching-style strategy sketches written to explain stock-selection and allocation ideas. - Unless stated otherwise, theStrategyFactory, layered portfolios, and severalgenerate_trade_decision(score)examples should be read as "design illustrations", not complete in-repo implementations that can be plugged directly into a backtest.
Learning Objectives¶
After studying this chapter, you will be able to: - Understand the design principles of Qlib's strategy framework - Master the implementation of common investment strategies - Learn to design and develop custom strategies - Understand strategy parameter configuration and optimization - Master advanced strategy techniques and the nested decision framework
5.1 The Strategy Framework¶
5.1.1 Qlib's Strategy Base Class¶
Structure of the Base Class¶
Qlib provides a unified strategy base class that all investment strategies inherit from.
from qlib.strategy.base import BaseStrategy
class MyStrategy(BaseStrategy):
"""Custom strategy base class"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.risk_degree = 0.95 # risk degree
self.benchmark = "SH000300" # benchmark
self.universe = "csi300" # stock universe
def generate_trade_decision(self, execute_result=None):
"""Generate a trading decision"""
# The concrete BaseTradeDecision construction is omitted here
pass
def get_score(self, score):
"""Get prediction scores"""
return score
def get_risk_degree(self):
"""Get the risk degree"""
return self.risk_degree
Strategy Interface Specification¶
1. Core methods
class StrategyInterface:
"""Strategy interface specification"""
def __init__(self, **kwargs):
"""Initialize the strategy"""
pass
def generate_trade_decision(self, score):
"""Generate a trading decision"""
# Input: prediction scores
# Output: trading decision
pass
def get_score(self, score):
"""Process prediction scores"""
# Input: raw scores
# Output: processed scores
pass
def get_risk_degree(self):
"""Get the risk degree"""
# Output: the risk-degree parameter
pass
2. Strategy configuration
class StrategyConfig:
"""Strategy configuration class"""
def __init__(self):
self.risk_degree = 0.95
self.benchmark = "SH000300"
self.universe = "csi300"
self.start_time = "2020-01-01"
self.end_time = "2020-12-31"
self.freq = "day"
self.model = None
self.data_handler = None
5.1.2 Strategy Interface Conventions¶
The Standard Strategy Interface¶
Note: the interface below is closer to a "strategy design sketch" explaining what inputs and outputs a stock selector typically exposes. A real Qlib strategy participating in a backtest must additionally align with
BaseTradeDecision, executors, and the account infrastructure.
from abc import ABC, abstractmethod
import pandas as pd
import numpy as np
class BaseStrategy(ABC):
"""Strategy base class"""
def __init__(self, risk_degree=0.95, benchmark="SH000300", universe="csi300"):
self.risk_degree = risk_degree
self.benchmark = benchmark
self.universe = universe
self.positions = {}
@abstractmethod
def generate_trade_decision(self, score):
"""Generate a trading decision - subclasses must implement this"""
pass
def get_score(self, score):
"""Get prediction scores - default implementation"""
return score
def get_risk_degree(self):
"""Get the risk degree"""
return self.risk_degree
def update_positions(self, positions):
"""Update positions"""
self.positions = positions
def get_positions(self):
"""Get current positions"""
return self.positions
The Strategy Factory Pattern¶
class StrategyFactory:
"""Strategy factory class"""
_strategies = {}
@classmethod
def register(cls, name, strategy_class):
"""Register a strategy"""
cls._strategies[name] = strategy_class
@classmethod
def create(cls, name, **kwargs):
"""Create a strategy instance"""
if name not in cls._strategies:
raise ValueError(f"Strategy {name} does not exist")
return cls._strategies[name](**kwargs)
@classmethod
def list_strategies(cls):
"""List all available strategies"""
return list(cls._strategies.keys())
# Register strategies
StrategyFactory.register("TopkDropout", TopkDropoutStrategy)
StrategyFactory.register("WeightStrategy", WeightStrategy)
5.1.3 Strategy Parameter Configuration¶
The Parameter Configuration System¶
import yaml
from dataclasses import dataclass
@dataclass
class StrategyParams:
"""Strategy parameter configuration"""
risk_degree: float = 0.95
benchmark: str = "SH000300"
universe: str = "csi300"
topk: int = 50
n_drop: int = 5
method_sell: str = "bottom"
method_buy: str = "top"
close_cost: float = 0.0005
open_cost: float = 0.0005
trade_unit: int = 100
limit_threshold: float = 0.095
max_weight: float = 0.05
def load_strategy_config(config_path):
"""Load a strategy configuration"""
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
return StrategyParams(**config)
def save_strategy_config(params, config_path):
"""Save a strategy configuration"""
config = {
'risk_degree': params.risk_degree,
'benchmark': params.benchmark,
'universe': params.universe,
'topk': params.topk,
'n_drop': params.n_drop,
'method_sell': params.method_sell,
'method_buy': params.method_buy,
'close_cost': params.close_cost,
'open_cost': params.open_cost,
'trade_unit': params.trade_unit,
'limit_threshold': params.limit_threshold,
'max_weight': params.max_weight
}
with open(config_path, 'w') as f:
yaml.dump(config, f, default_flow_style=False)
Dynamic Parameter Adjustment¶
class AdaptiveStrategyParams:
"""Adaptive strategy parameters"""
def __init__(self, base_params):
self.base_params = base_params
self.adaptation_history = []
def adapt_to_market_conditions(self, market_data):
"""Adjust parameters based on market conditions"""
# Compute market volatility
volatility = self.calculate_market_volatility(market_data)
# Adjust the risk degree
if volatility > 0.3: # high volatility
self.base_params.risk_degree *= 0.9
elif volatility < 0.1: # low volatility
self.base_params.risk_degree *= 1.1
# Keep the risk degree in range
self.base_params.risk_degree = max(0.5, min(0.99, self.base_params.risk_degree))
# Record the adjustment history
self.adaptation_history.append({
'volatility': volatility,
'risk_degree': self.base_params.risk_degree,
'timestamp': pd.Timestamp.now()
})
def calculate_market_volatility(self, market_data):
"""Compute market volatility"""
returns = market_data['close'].pct_change().dropna()
return returns.std() * np.sqrt(252)
5.1.4 Combining Strategies¶
Multi-Strategy Ensembles¶
class StrategyEnsemble:
"""Strategy ensemble class"""
def __init__(self, strategies, weights=None):
self.strategies = strategies
self.weights = weights or [1/len(strategies)] * len(strategies)
if len(self.weights) != len(self.strategies):
raise ValueError("Number of strategies and weights do not match")
def generate_ensemble_decision(self, scores):
"""Generate an ensemble decision"""
decisions = []
for strategy, score in zip(self.strategies, scores):
decision = strategy.generate_trade_decision(score)
decisions.append(decision)
# Weighted combination of decisions
ensemble_decision = self.combine_decisions(decisions)
return ensemble_decision
def combine_decisions(self, decisions):
"""Combine multiple decisions"""
# Simple weighted average
combined_decision = {}
for decision in decisions:
for stock, weight in decision.items():
if stock not in combined_decision:
combined_decision[stock] = 0
combined_decision[stock] += weight
# Normalize
total_weight = sum(combined_decision.values())
if total_weight > 0:
combined_decision = {k: v/total_weight for k, v in combined_decision.items()}
return combined_decision
Hierarchical Strategy Combination¶
class HierarchicalStrategy:
"""Hierarchical strategy combination"""
def __init__(self, asset_allocation_strategy, stock_selection_strategies):
self.asset_allocation_strategy = asset_allocation_strategy
self.stock_selection_strategies = stock_selection_strategies
def generate_hierarchical_decision(self, market_data, stock_scores):
"""Generate a hierarchical decision"""
# Layer 1: asset allocation
asset_allocation = self.asset_allocation_strategy.generate_allocation(market_data)
# Layer 2: stock selection
stock_selections = {}
for asset_class, allocation_weight in asset_allocation.items():
if asset_class in self.stock_selection_strategies:
strategy = self.stock_selection_strategies[asset_class]
stock_weights = strategy.generate_trade_decision(stock_scores[asset_class])
# Adjust the weights
adjusted_weights = {stock: weight * allocation_weight
for stock, weight in stock_weights.items()}
stock_selections.update(adjusted_weights)
return stock_selections
5.2 Common Strategy Implementations¶
Note: the multi-factor, momentum, and mean-reversion classes below mainly express "how to go from scores to weights". Plugging them into a real Qlib backtest usually requires additionally wrapping signal generation, trade decisions, and executor configuration.
5.2.1 Multi-Factor Strategies¶
Multi-Factor Model Principles¶
Multi-factor strategies predict stock returns from multiple factors and are among the most common strategies in quantitative investing.
class MultiFactorStrategy(BaseStrategy):
"""Multi-factor strategy"""
def __init__(self, factors, factor_weights=None, **kwargs):
super().__init__(**kwargs)
self.factors = factors
self.factor_weights = factor_weights or [1/len(factors)] * len(factors)
def calculate_factor_scores(self, data):
"""Compute factor scores"""
factor_scores = {}
for factor_name in self.factors:
if factor_name == 'momentum':
factor_scores[factor_name] = self.calculate_momentum_factor(data)
elif factor_name == 'value':
factor_scores[factor_name] = self.calculate_value_factor(data)
elif factor_name == 'quality':
factor_scores[factor_name] = self.calculate_quality_factor(data)
elif factor_name == 'size':
factor_scores[factor_name] = self.calculate_size_factor(data)
return factor_scores
def calculate_momentum_factor(self, data):
"""Compute the momentum factor"""
# Return over the past 20 days
returns = data['close'].pct_change(periods=20)
return returns.rank(pct=True) # normalized rank
def calculate_value_factor(self, data):
"""Compute the value factor"""
# Use the inverse P/E as the value factor
pe_ratio = data['close'] / data['eps']
value_factor = 1 / pe_ratio
return value_factor.rank(pct=True)
def calculate_quality_factor(self, data):
"""Compute the quality factor"""
# Use ROE as the quality factor
roe = data['net_income'] / data['equity']
return roe.rank(pct=True)
def calculate_size_factor(self, data):
"""Compute the size factor"""
# Use the inverse market cap as the size factor
market_cap = data['close'] * data['shares_outstanding']
size_factor = 1 / market_cap
return size_factor.rank(pct=True)
def generate_trade_decision(self, factor_scores):
"""Generate a trading decision"""
# Composite score
composite_score = pd.DataFrame()
for factor_name, factor_score in factor_scores.items():
weight = self.factor_weights[self.factors.index(factor_name)]
composite_score[factor_name] = factor_score * weight
# Total score
total_score = composite_score.sum(axis=1)
# Select the top-k stocks
top_stocks = total_score.nlargest(self.topk).index
# Generate weights
weights = {}
for stock in top_stocks:
weights[stock] = total_score[stock] / total_score[top_stocks].sum()
return weights
Factor Effectiveness Testing¶
class FactorAnalysis:
"""Factor analysis class"""
def __init__(self):
self.factor_ic_history = {}
def calculate_factor_ic(self, factor_scores, future_returns):
"""Compute factor IC values"""
ic_values = {}
for factor_name, factor_score in factor_scores.items():
# Correlation between the factor and future returns
ic = factor_score.corr(future_returns)
ic_values[factor_name] = ic
return ic_values
def calculate_factor_icir(self, factor_scores, future_returns, window=252):
"""Compute factor ICIR values"""
ic_series = pd.DataFrame()
for factor_name, factor_score in factor_scores.items():
# Rolling IC
rolling_ic = factor_score.rolling(window).corr(future_returns)
ic_series[factor_name] = rolling_ic
# ICIR
icir = ic_series.mean() / ic_series.std()
return icir
def factor_turnover_analysis(self, factor_scores, window=20):
"""Factor turnover analysis"""
turnover_rates = {}
for factor_name, factor_score in factor_scores.items():
# Changes in factor rank
rank_changes = factor_score.rank(pct=True).diff().abs()
turnover = rank_changes.rolling(window).mean()
turnover_rates[factor_name] = turnover
return turnover_rates
5.2.2 Momentum Strategies¶
Momentum Strategy Implementation¶
class MomentumStrategy(BaseStrategy):
"""Momentum strategy"""
def __init__(self, lookback_period=20, momentum_type='price', **kwargs):
super().__init__(**kwargs)
self.lookback_period = lookback_period
self.momentum_type = momentum_type
def calculate_momentum_scores(self, data):
"""Compute momentum scores"""
if self.momentum_type == 'price':
# Price momentum
momentum = data['close'].pct_change(periods=self.lookback_period)
elif self.momentum_type == 'return':
# Return momentum
returns = data['close'].pct_change()
momentum = returns.rolling(self.lookback_period).mean()
elif self.momentum_type == 'relative':
# Relative momentum
benchmark_returns = data['benchmark'].pct_change(periods=self.lookback_period)
stock_returns = data['close'].pct_change(periods=self.lookback_period)
momentum = stock_returns - benchmark_returns
else:
raise ValueError(f"Unsupported momentum type: {self.momentum_type}")
return momentum.rank(pct=True)
def generate_trade_decision(self, momentum_scores):
"""Generate a trading decision"""
# Select the stocks with the strongest momentum
top_momentum = momentum_scores.nlargest(self.topk)
# Generate weights
weights = {}
for stock in top_momentum.index:
weights[stock] = momentum_scores[stock] / top_momentum.sum()
return weights
Momentum Strategy Variants¶
class DualMomentumStrategy(MomentumStrategy):
"""Dual momentum strategy"""
def __init__(self, short_period=10, long_period=60, **kwargs):
super().__init__(**kwargs)
self.short_period = short_period
self.long_period = long_period
def calculate_dual_momentum(self, data):
"""Compute dual momentum"""
# Short-term momentum
short_momentum = data['close'].pct_change(periods=self.short_period)
# Long-term momentum
long_momentum = data['close'].pct_change(periods=self.long_period)
# Dual momentum signal
dual_momentum = (short_momentum > 0) & (long_momentum > 0)
return dual_momentum.astype(int)
def generate_trade_decision(self, dual_momentum_scores):
"""Generate a trading decision"""
# Only select stocks with positive dual momentum
positive_momentum = dual_momentum_scores[dual_momentum_scores > 0]
if len(positive_momentum) == 0:
return {} # no qualifying stocks
# Select the strongest momentum stocks
top_stocks = positive_momentum.nlargest(self.topk)
# Equal weights
weights = {stock: 1/len(top_stocks) for stock in top_stocks.index}
return weights
5.2.3 Mean-Reversion Strategies¶
Mean-Reversion Principles¶
Mean-reversion strategies assume prices revert toward their mean and take contrarian positions when prices deviate significantly.
class MeanReversionStrategy(BaseStrategy):
"""Mean-reversion strategy"""
def __init__(self, lookback_period=60, std_threshold=2.0, **kwargs):
super().__init__(**kwargs)
self.lookback_period = lookback_period
self.std_threshold = std_threshold
def calculate_mean_reversion_signal(self, data):
"""Compute mean-reversion signals"""
# Moving average
ma = data['close'].rolling(self.lookback_period).mean()
# Standard deviation
std = data['close'].rolling(self.lookback_period).std()
# Z-score
z_score = (data['close'] - ma) / std
# Generate signals
# Buy when the price is significantly below the mean (Z-score < -threshold)
# Sell when the price is significantly above the mean (Z-score > threshold)
buy_signal = z_score < -self.std_threshold
sell_signal = z_score > self.std_threshold
return buy_signal, sell_signal, z_score
def generate_trade_decision(self, signals):
"""Generate a trading decision"""
buy_signal, sell_signal, z_score = signals
# Select the stocks with the strongest buy signals
buy_candidates = z_score[buy_signal]
if len(buy_candidates) == 0:
return {} # no buying opportunities
# Select the stocks with the lowest Z-scores (largest deviation from the mean)
top_buy = buy_candidates.nsmallest(self.topk)
# Weights proportional to the absolute Z-score
weights = {}
total_weight = abs(top_buy).sum()
for stock in top_buy.index:
weights[stock] = abs(z_score[stock]) / total_weight
return weights
Pairs Trading Strategy¶
class PairsTradingStrategy(BaseStrategy):
"""Pairs trading strategy"""
def __init__(self, lookback_period=252, entry_threshold=2.0, exit_threshold=0.5, **kwargs):
super().__init__(**kwargs)
self.lookback_period = lookback_period
self.entry_threshold = entry_threshold
self.exit_threshold = exit_threshold
self.pairs = []
def find_cointegrated_pairs(self, price_data, pvalue_threshold=0.05):
"""Find cointegrated pairs"""
from statsmodels.tsa.stattools import coint
n_stocks = len(price_data.columns)
pairs = []
for i in range(n_stocks):
for j in range(i+1, n_stocks):
stock1 = price_data.iloc[:, i]
stock2 = price_data.iloc[:, j]
# Cointegration test
score, pvalue, _ = coint(stock1, stock2)
if pvalue < pvalue_threshold:
pairs.append((stock1.name, stock2.name, score, pvalue))
# Sort by p-value
pairs.sort(key=lambda x: x[3])
self.pairs = pairs
return pairs
def calculate_spread(self, stock1_prices, stock2_prices):
"""Compute the spread"""
# Linear-regression spread
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(stock1_prices.values.reshape(-1, 1), stock2_prices.values)
# Spread = stock2 - beta * stock1
spread = stock2_prices - model.coef_[0] * stock1_prices
return spread, model.coef_[0]
def generate_trade_decision(self, price_data):
"""Generate a trading decision"""
if not self.pairs:
self.find_cointegrated_pairs(price_data)
decisions = {}
for stock1, stock2, score, pvalue in self.pairs[:10]: # take the top 10 pairs
if stock1 not in price_data.columns or stock2 not in price_data.columns:
continue
# Compute the spread
spread, beta = self.calculate_spread(price_data[stock1], price_data[stock2])
# Z-score of the spread
spread_mean = spread.rolling(self.lookback_period).mean()
spread_std = spread.rolling(self.lookback_period).std()
z_score = (spread - spread_mean) / spread_std
current_z = z_score.iloc[-1]
# Generate trading signals
if current_z > self.entry_threshold:
# Spread too wide: short stock2, long stock1
decisions[stock1] = 1.0
decisions[stock2] = -1.0
elif current_z < -self.entry_threshold:
# Spread too narrow: long stock2, short stock1
decisions[stock1] = -1.0
decisions[stock2] = 1.0
return decisions
5.2.4 Arbitrage Strategies¶
Statistical Arbitrage Strategy¶
class StatisticalArbitrageStrategy(BaseStrategy):
"""Statistical arbitrage strategy"""
def __init__(self, lookback_period=252, entry_threshold=2.0, **kwargs):
super().__init__(**kwargs)
self.lookback_period = lookback_period
self.entry_threshold = entry_threshold
def calculate_statistical_signals(self, data):
"""Compute statistical arbitrage signals"""
signals = {}
for stock in data.columns:
prices = data[stock]
# Moving average and standard deviation
ma = prices.rolling(self.lookback_period).mean()
std = prices.rolling(self.lookback_period).std()
# Z-score
z_score = (prices - ma) / std
# Generate signals
current_z = z_score.iloc[-1]
if current_z > self.entry_threshold:
signals[stock] = -1 # short signal
elif current_z < -self.entry_threshold:
signals[stock] = 1 # long signal
else:
signals[stock] = 0 # no signal
return signals
def generate_trade_decision(self, signals):
"""Generate a trading decision"""
# Separate long and short signals
long_signals = {stock: signal for stock, signal in signals.items() if signal == 1}
short_signals = {stock: signal for stock, signal in signals.items() if signal == -1}
decisions = {}
# Allocate long weights
if long_signals:
long_weight = 0.5 / len(long_signals)
for stock in long_signals:
decisions[stock] = long_weight
# Allocate short weights
if short_signals:
short_weight = -0.5 / len(short_signals)
for stock in short_signals:
decisions[stock] = short_weight
return decisions
5.3 Advanced Strategy Techniques¶
5.3.1 The Nested Decision Framework¶
Nested Decision Principles¶
The nested decision framework lets a strategy make decisions at multiple levels, from top-down asset allocation down to individual stock selection.
class NestedDecisionFramework:
"""Nested decision framework"""
def __init__(self, asset_allocation_strategy, sector_allocation_strategy, stock_selection_strategy):
self.asset_allocation_strategy = asset_allocation_strategy
self.sector_allocation_strategy = sector_allocation_strategy
self.stock_selection_strategy = stock_selection_strategy
def generate_nested_decision(self, market_data, sector_data, stock_data):
"""Generate a nested decision"""
# Layer 1: top-level asset allocation
asset_allocation = self.asset_allocation_strategy.allocate(market_data)
# Layer 2: sector allocation
sector_allocation = {}
for asset_class, asset_weight in asset_allocation.items():
if asset_class == 'equity':
sector_weights = self.sector_allocation_strategy.allocate(sector_data)
# Adjust sector weights
adjusted_sector_weights = {sector: weight * asset_weight
for sector, weight in sector_weights.items()}
sector_allocation.update(adjusted_sector_weights)
# Layer 3: stock selection
final_weights = {}
for sector, sector_weight in sector_allocation.items():
sector_stocks = stock_data[stock_data['sector'] == sector]
if len(sector_stocks) > 0:
stock_weights = self.stock_selection_strategy.select(sector_stocks)
# Adjust stock weights
adjusted_stock_weights = {stock: weight * sector_weight
for stock, weight in stock_weights.items()}
final_weights.update(adjusted_stock_weights)
return final_weights
Dynamic Asset Allocation¶
class DynamicAssetAllocation:
"""Dynamic asset allocation strategy"""
def __init__(self, risk_free_rate=0.02, target_volatility=0.15):
self.risk_free_rate = risk_free_rate
self.target_volatility = target_volatility
def calculate_optimal_allocation(self, returns_data):
"""Compute the optimal asset allocation"""
# Expected returns and the covariance matrix
expected_returns = returns_data.mean()
cov_matrix = returns_data.cov()
# Markowitz optimization
from scipy.optimize import minimize
def objective(weights):
portfolio_return = np.sum(weights * expected_returns)
portfolio_vol = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
sharpe_ratio = (portfolio_return - self.risk_free_rate) / portfolio_vol
return -sharpe_ratio # maximize the Sharpe ratio
# Constraints
constraints = [
{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}, # weights sum to 1
]
bounds = [(0, 1) for _ in range(len(expected_returns))] # weights in [0, 1]
# Initial weights
initial_weights = np.array([1/len(expected_returns)] * len(expected_returns))
# Optimize
result = minimize(objective, initial_weights, method='SLSQP',
bounds=bounds, constraints=constraints)
return dict(zip(returns_data.columns, result.x))
5.3.2 High-Frequency Trading Strategies¶
A High-Frequency Strategy Framework¶
class HighFrequencyStrategy(BaseStrategy):
"""High-frequency trading strategy"""
def __init__(self, tick_data_handler, order_manager, **kwargs):
super().__init__(**kwargs)
self.tick_data_handler = tick_data_handler
self.order_manager = order_manager
self.positions = {}
self.pending_orders = []
def process_tick_data(self, tick_data):
"""Process tick data"""
# Update market data
self.update_market_data(tick_data)
# Generate trading signals
signals = self.generate_signals(tick_data)
# Execute trades
self.execute_trades(signals)
def update_market_data(self, tick_data):
"""Update market data"""
# Update prices, volumes, order books, etc.
pass
def generate_signals(self, tick_data):
"""Generate trading signals"""
signals = {}
# Order-book-based signals
orderbook_signals = self.analyze_orderbook(tick_data)
# Price-momentum-based signals
momentum_signals = self.analyze_momentum(tick_data)
# Statistical-arbitrage-based signals
stat_arb_signals = self.analyze_statistical_arbitrage(tick_data)
# Combined signals
for stock in tick_data.keys():
signals[stock] = self.combine_signals(
orderbook_signals.get(stock, 0),
momentum_signals.get(stock, 0),
stat_arb_signals.get(stock, 0)
)
return signals
def analyze_orderbook(self, tick_data):
"""Analyze the order book"""
signals = {}
for stock, data in tick_data.items():
if 'orderbook' in data:
orderbook = data['orderbook']
# Buying and selling pressure
bid_pressure = sum(orderbook['bids'].values())
ask_pressure = sum(orderbook['asks'].values())
# Pressure ratio
pressure_ratio = bid_pressure / ask_pressure if ask_pressure > 0 else 1
# Generate signals
if pressure_ratio > 1.2:
signals[stock] = 1 # buy signal
elif pressure_ratio < 0.8:
signals[stock] = -1 # sell signal
else:
signals[stock] = 0 # no signal
return signals
def analyze_momentum(self, tick_data):
"""Analyze price momentum"""
signals = {}
for stock, data in tick_data.items():
if 'price_history' in data:
prices = data['price_history']
# Short-term momentum
short_momentum = (prices[-1] - prices[-10]) / prices[-10] if len(prices) >= 10 else 0
# Generate signals
if short_momentum > 0.001: # 0.1% momentum
signals[stock] = 1
elif short_momentum < -0.001:
signals[stock] = -1
else:
signals[stock] = 0
return signals
def execute_trades(self, signals):
"""Execute trades"""
for stock, signal in signals.items():
if signal != 0:
# Compute the trade size
position = self.positions.get(stock, 0)
target_position = signal * self.trade_unit
if target_position != position:
# Create the order
order = {
'stock': stock,
'side': 'buy' if target_position > position else 'sell',
'quantity': abs(target_position - position),
'price': self.get_market_price(stock),
'timestamp': pd.Timestamp.now()
}
# Submit the order
self.order_manager.submit_order(order)
5.3.3 Dynamic Asset Allocation¶
Risk Parity Strategy¶
class RiskParityStrategy(BaseStrategy):
"""Risk parity strategy"""
def __init__(self, target_volatility=0.10, rebalance_frequency=30, **kwargs):
super().__init__(**kwargs)
self.target_volatility = target_volatility
self.rebalance_frequency = rebalance_frequency
self.last_rebalance = None
def calculate_risk_contributions(self, returns_data):
"""Compute risk contributions"""
# Covariance matrix
cov_matrix = returns_data.cov()
# Risk contribution of each asset
n_assets = len(returns_data.columns)
risk_contributions = {}
for i, asset in enumerate(returns_data.columns):
# Marginal risk contribution
marginal_risk = cov_matrix.iloc[i, :].values
# Risk contribution = weight * marginal risk contribution
risk_contributions[asset] = marginal_risk
return risk_contributions
def optimize_risk_parity(self, returns_data):
"""Optimize risk-parity weights"""
from scipy.optimize import minimize
def objective(weights):
# Portfolio risk
cov_matrix = returns_data.cov()
portfolio_risk = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
# Risk contribution of each asset
risk_contributions = np.dot(cov_matrix, weights) * weights / portfolio_risk
# Risk parity goal: equal risk contributions from all assets
target_contribution = portfolio_risk / len(weights)
risk_parity_error = np.sum((risk_contributions - target_contribution) ** 2)
return risk_parity_error
# Constraints
constraints = [
{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}, # weights sum to 1
]
bounds = [(0, 1) for _ in range(len(returns_data.columns))]
# Initial weights
initial_weights = np.array([1/len(returns_data.columns)] * len(returns_data.columns))
# Optimize
result = minimize(objective, initial_weights, method='SLSQP',
bounds=bounds, constraints=constraints)
return dict(zip(returns_data.columns, result.x))
def generate_trade_decision(self, returns_data):
"""Generate a trading decision"""
# Check whether rebalancing is needed
if self.should_rebalance():
# Compute risk-parity weights
weights = self.optimize_risk_parity(returns_data)
self.last_rebalance = pd.Timestamp.now()
return weights
else:
# Keep the current weights
return self.current_weights
def should_rebalance(self):
"""Check whether rebalancing is needed"""
if self.last_rebalance is None:
return True
days_since_rebalance = (pd.Timestamp.now() - self.last_rebalance).days
return days_since_rebalance >= self.rebalance_frequency
Target-Risk Strategy¶
class TargetRiskStrategy(BaseStrategy):
"""Target-risk strategy"""
def __init__(self, target_volatility=0.15, risk_free_rate=0.02, **kwargs):
super().__init__(**kwargs)
self.target_volatility = target_volatility
self.risk_free_rate = risk_free_rate
def calculate_optimal_weights(self, returns_data):
"""Compute optimal weights"""
# Expected returns and the covariance matrix
expected_returns = returns_data.mean()
cov_matrix = returns_data.cov()
# Maximum Sharpe ratio optimization
from scipy.optimize import minimize
def objective(weights):
portfolio_return = np.sum(weights * expected_returns)
portfolio_vol = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
# Goal: maximize the Sharpe ratio while controlling risk
sharpe_ratio = (portfolio_return - self.risk_free_rate) / portfolio_vol
risk_penalty = max(0, portfolio_vol - self.target_volatility) ** 2
return -(sharpe_ratio - risk_penalty)
# Constraints
constraints = [
{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}, # weights sum to 1
]
bounds = [(0, 1) for _ in range(len(expected_returns))]
# Initial weights
initial_weights = np.array([1/len(expected_returns)] * len(expected_returns))
# Optimize
result = minimize(objective, initial_weights, method='SLSQP',
bounds=bounds, constraints=constraints)
return dict(zip(returns_data.columns, result.x))
def generate_trade_decision(self, returns_data):
"""Generate a trading decision"""
# Compute optimal weights
weights = self.calculate_optimal_weights(returns_data)
# Apply the risk-degree adjustment
adjusted_weights = {stock: weight * self.risk_degree
for stock, weight in weights.items()}
return adjusted_weights
Chapter Summary¶
This chapter covered investment strategy design in Qlib in detail:
- The strategy framework: base class design, interface conventions, parameter configuration
- Common strategies: multi-factor, momentum, mean-reversion, and arbitrage strategies
- Advanced techniques: the nested decision framework, high-frequency trading, dynamic asset allocation
Exercises¶
Exercise 1: Strategy implementation¶
- Implement a simple multi-factor strategy
- Develop a variant of a momentum strategy
- Build a mean-reversion strategy
Exercise 2: Strategy optimization¶
- Test strategy performance with different parameters
- Implement strategy combination methods
- Analyze strategy stability
Exercise 3: Advanced strategies¶
- Implement the nested decision framework
- Develop a risk parity strategy
- Design a dynamic asset allocation strategy
Further Reading¶
- Strategy design theory
- Quantitative Investment Strategies and Techniques (《量化投资策略与技术》)
-
Active Portfolio Management (《主动投资组合管理》)
-
Multi-factor models
- Multi-Factor Investment Strategies (《多因子投资策略》)
-
Factor Investing: Theory and Practice (《因子投资:理论与实践》)
-
High-frequency trading
- High-Frequency Trading Algorithms (《高频交易算法》)
- Market Microstructure (《市场微观结构》)