Factor Engineering¶
Learning Objectives¶
Through this chapter, you will gain a deep understanding of:
- The fundamental theory and classification system of factors
- How to use Qlib's built-in factor libraries
- Developing and implementing custom factors
- Factor effectiveness evaluation and screening strategies
- Factor combination optimization and risk control
5.1 Factor Fundamentals¶
5.1.1 What Is a Factor¶
A factor is a variable that can explain asset returns, and it is the core of quantitative investing. In a multi-factor model, stock returns can be expressed as:
R_i = α_i + β_i1 × F_1 + β_i2 × F_2 + ... + β_ik × F_k + ε_i
where: - R_i: the return of stock i - α_i: the idiosyncratic return of stock i - F_j: the return of factor j - β_ij: the exposure of stock i to factor j - ε_i: the residual term
5.1.2 Factor Classification System¶
# Factor classification demo
class FactorClassification:
"""
Comprehensive factor classification system
"""
def __init__(self):
self.factor_categories = {
# Classified by data source
'by_source': {
'price': 'Price-based factors',
'volume': 'Volume-based factors',
'fundamental': 'Fundamental factors',
'technical': 'Technical factors',
'alternative': 'Alternative data factors'
},
# Classified by frequency
'by_frequency': {
'intraday': 'Intraday factors',
'daily': 'Daily-frequency factors',
'weekly': 'Weekly-frequency factors',
'monthly': 'Monthly-frequency factors',
'quarterly': 'Quarterly-frequency factors'
},
# Classified by style
'by_style': {
'momentum': 'Momentum factors',
'reversal': 'Reversal factors',
'volatility': 'Volatility factors',
'quality': 'Quality factors',
'value': 'Value factors',
'growth': 'Growth factors',
'size': 'Size factors'
},
# Classified by construction method
'by_method': {
'statistical': 'Statistical factors',
'mathematical': 'Mathematical factors',
'machine_learning': 'Machine learning factors',
'fundamental_analysis': 'Fundamental analysis factors'
}
}
def display_classification(self):
"""
Display the factor classification
"""
print("Factor Classification System")
print("=" * 60)
for category, factors in self.factor_categories.items():
print(f"\n📊 {category}:")
for factor_type, description in factors.items():
print(f" • {factor_type}: {description}")
def get_factor_characteristics(self):
"""
Get the characteristics of different factor types
"""
characteristics = {
'momentum': {
'description': 'Captures price trend continuation',
'typical_horizon': '1-12 months',
'market_conditions': 'Trending markets',
'examples': ['20-day return', 'RSI', 'Price momentum']
},
'reversal': {
'description': 'Captures mean-reversion tendencies',
'typical_horizon': '1-5 days',
'market_conditions': 'Range-bound markets',
'examples': ['Short-term reversal', 'Bollinger Bands', 'Z-score']
},
'volatility': {
'description': 'Measures price volatility',
'typical_horizon': '20-60 days',
'market_conditions': 'All market conditions',
'examples': ['Historical volatility', 'GARCH', 'VIX']
},
'value': {
'description': 'Identifies undervalued securities',
'typical_horizon': '6-24 months',
'market_conditions': 'Long-term oriented',
'examples': ['P/E ratio', 'P/B ratio', 'EV/EBITDA']
}
}
return characteristics
# Usage example
factor_classifier = FactorClassification()
factor_classifier.display_classification()
characteristics = factor_classifier.get_factor_characteristics()
5.1.3 Factor Effectiveness Theory¶
# Factor effectiveness evaluation framework
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
class FactorEffectivenessEvaluator:
"""
Comprehensive factor effectiveness evaluation
"""
def __init__(self):
self.evaluation_metrics = [
'ic', # Information coefficient
'ic_ir', # IC information ratio
'rank_ic', # Rank information coefficient
'turnover', # Factor turnover
'autocorr', # Factor autocorrelation
'max_drawdown', # Max drawdown
'sharpe_ratio' # Sharpe ratio
]
def calculate_ic(self, factor_values, future_returns, method='pearson'):
"""
Calculate the information coefficient
Parameters:
- factor_values: factor values
- future_returns: future returns
- method: correlation method
"""
# Remove NaN values
valid_mask = ~(np.isnan(factor_values) | np.isnan(future_returns))
clean_factor = factor_values[valid_mask]
clean_returns = future_returns[valid_mask]
if len(clean_factor) < 2:
return np.nan
if method == 'pearson':
ic, p_value = stats.pearsonr(clean_factor, clean_returns)
elif method == 'spearman':
ic, p_value = stats.spearmanr(clean_factor, clean_returns)
else:
raise ValueError("Method must be 'pearson' or 'spearman'")
return ic, p_value
def calculate_ic_series(self, factor_df, return_df, periods=[1, 5, 10, 20]):
"""
Calculate IC series for different forward horizons
"""
ic_results = {}
for period in periods:
ic_series = []
dates = factor_df.index.get_level_values(0).unique()
for date in dates[:-period]: # Exclude the last few days
try:
# Get factor values for this date
factor_cross_section = factor_df.xs(date, level=0)
# Get future returns
future_date = dates[dates.get_loc(date) + period]
future_returns = return_df.xs(future_date, level=0)
# Align stocks
common_instruments = factor_cross_section.index.intersection(future_returns.index)
if len(common_instruments) > 10: # Minimum threshold
factor_vals = factor_cross_section.loc[common_instruments]
return_vals = future_returns.loc[common_instruments]
ic, _ = self.calculate_ic(factor_vals.values, return_vals.values)
ic_series.append({'date': date, 'ic': ic})
except (KeyError, IndexError):
continue
ic_results[f'{period}d'] = pd.DataFrame(ic_series).set_index('date')
return ic_results
def quantile_analysis(self, factor_values, future_returns, n_quantiles=5):
"""
Perform factor quantile analysis
"""
# Create quantile groups
factor_quantiles = pd.qcut(factor_values, n_quantiles, labels=False, duplicates='drop')
# Compute returns by quantile
quantile_returns = {}
for q in range(n_quantiles):
mask = (factor_quantiles == q)
if mask.sum() > 0:
quantile_returns[f'Q{q+1}'] = {
'mean_return': future_returns[mask].mean(),
'std_return': future_returns[mask].std(),
'count': mask.sum()
}
# Compute the spread between the top and bottom quantiles
if 'Q1' in quantile_returns and f'Q{n_quantiles}' in quantile_returns:
spread = quantile_returns[f'Q{n_quantiles}']['mean_return'] - quantile_returns['Q1']['mean_return']
quantile_returns['spread'] = spread
return quantile_returns
def factor_turnover_analysis(self, factor_df, top_pct=0.2):
"""
Analyze factor turnover
"""
dates = factor_df.index.get_level_values(0).unique()
turnover_rates = []
for i in range(1, len(dates)):
prev_date = dates[i-1]
curr_date = dates[i]
try:
# Get the top stocks for each period
prev_top = factor_df.xs(prev_date, level=0).nlargest(int(len(factor_df.xs(prev_date, level=0)) * top_pct))
curr_top = factor_df.xs(curr_date, level=0).nlargest(int(len(factor_df.xs(curr_date, level=0)) * top_pct))
# Compute overlap
overlap = len(set(prev_top.index) & set(curr_top.index))
total = len(prev_top)
turnover = 1 - (overlap / total) if total > 0 else 0
turnover_rates.append({'date': curr_date, 'turnover': turnover})
except KeyError:
continue
return pd.DataFrame(turnover_rates).set_index('date')
def comprehensive_factor_report(self, factor_df, return_df, factor_name="Factor"):
"""
Generate a comprehensive factor analysis report
"""
print(f"📊 Comprehensive Factor Analysis Report: {factor_name}")
print("=" * 70)
# 1. IC analysis
print("\n1. Information coefficient analysis:")
ic_results = self.calculate_ic_series(factor_df, return_df)
for period, ic_df in ic_results.items():
if not ic_df.empty:
mean_ic = ic_df['ic'].mean()
ic_std = ic_df['ic'].std()
ic_ir = mean_ic / ic_std if ic_std > 0 else 0
print(f" {period} forward horizon:")
print(f" Mean IC: {mean_ic:.4f}")
print(f" IC IR: {ic_ir:.4f}")
print(f" IC std: {ic_std:.4f}")
# 2. Quantile analysis
print("\n2. Quantile analysis:")
# Use the latest cross-section for quantile analysis
latest_date = factor_df.index.get_level_values(0)[-1]
latest_factor = factor_df.xs(latest_date, level=0)
latest_return = return_df.xs(latest_date, level=0)
# Align data
common_instruments = latest_factor.index.intersection(latest_return.index)
if len(common_instruments) > 50: # Sufficient sample size
quantile_results = self.quantile_analysis(
latest_factor.loc[common_instruments].values,
latest_return.loc[common_instruments].values
)
for quantile, stats in quantile_results.items():
if quantile != 'spread':
print(f" {quantile}: Mean return = {stats['mean_return']:.4f}, "
f"Count = {stats['count']}")
if 'spread' in quantile_results:
print(f" Top-bottom spread: {quantile_results['spread']:.4f}")
# 3. Turnover analysis
print("\n3. Factor turnover analysis:")
turnover_df = self.factor_turnover_analysis(factor_df)
if not turnover_df.empty:
mean_turnover = turnover_df['turnover'].mean()
print(f" Mean turnover: {mean_turnover:.2%}")
print(f" Turnover std: {turnover_df['turnover'].std():.4f}")
return {
'ic_results': ic_results,
'quantile_results': quantile_results if 'quantile_results' in locals() else None,
'turnover_results': turnover_df
}
# Usage example
# evaluator = FactorEffectivenessEvaluator()
# results = evaluator.comprehensive_factor_report(factor_data, return_data, "Momentum_20d")
5.2 Qlib's Built-in Factor Libraries¶
5.2.1 Alpha158 Factor Set in Detail¶
# Alpha158 factor set exploration
import qlib
from qlib.data import D
from qlib.constant import REG_CN
from qlib.contrib.data.handler import Alpha158
import pandas as pd
import numpy as np
class Alpha158Explorer:
"""
Comprehensive exploration of the Alpha158 factor set
"""
def __init__(self):
# Initialize Qlib
try:
qlib.init(provider_uri="~/.qlib/qlib_data/cn_data", region=REG_CN)
print("✅ Qlib initialized successfully, starting Alpha158 exploration")
except Exception as e:
print(f"❌ Qlib initialization failed: {e}")
raise
def get_alpha158_factors(self):
"""
Get the complete list of Alpha158 factors
"""
# Alpha158 factor categories
factor_categories = {
'price_features': {
'description': 'Price-based features',
'factors': [
'$close', '$open', '$high', '$low', # Basic OHLC
'Ref($close, 1)', 'Ref($close, 5)', 'Ref($close, 10)', # Reference prices
'Mean($close, 5)', 'Mean($close, 10)', 'Mean($close, 20)', # Moving averages
'Std($close, 5)', 'Std($close, 10)', 'Std($close, 20)' # Rolling standard deviations
]
},
'volume_features': {
'description': 'Volume-based features',
'factors': [
'$volume', '$amount', # Basic volume
'Mean($volume, 5)', 'Mean($volume, 10)', 'Mean($volume, 20)', # Volume MAs
'Std($volume, 5)', 'Std($volume, 10)', 'Std($volume, 20)', # Volume standard deviations
'$volume/$volume.mean()' # Volume ratio
]
},
'return_features': {
'description': 'Return-based features',
'factors': [
'$close/$close.shift(1) - 1', # Daily return
'($close/$close.shift(5) - 1)', # 5-day return
'($close/$close.shift(20) - 1)', # 20-day return
'Rsquare($close, 5)', 'Rsquare($close, 10)' # R-squared
]
},
'technical_features': {
'description': 'Technical indicators',
'factors': [
'RESI($close, 15)', 'RESI($close, 30)', # Resistance levels
'MAX($high, 5)', 'MIN($low, 5)', # Period high/low points
'QTLU($close, 0.8, 5)', 'QTLD($close, 0.2, 5)', # Quantiles
'RANK($close, 10)', 'RANK($volume, 10)' # Rankings
]
},
'cross_sectional_features': {
'description': 'Cross-sectional features',
'factors': [
'RANK($close)', 'RANK($volume)', # Cross-sectional rankings
'($close - $close.mean()) / $close.std()', # Z-score
'$close / $close.median()' # Relative to median
]
}
}
return factor_categories
def demonstrate_alpha158_usage(self):
"""
Demonstrate how to use the Alpha158 handler
"""
print("\n📊 Alpha158 Handler Usage Demonstration")
print("=" * 60)
# Configure the Alpha158 handler
handler_config = {
"start_time": "2020-01-01",
"end_time": "2020-03-31",
"fit_start_time": "2020-01-01",
"fit_end_time": "2020-02-29",
"instruments": "csi300"
}
try:
# Initialize the Alpha158 handler
alpha158_handler = Alpha158(**handler_config)
# Fetch the data
print("🔄 Fetching Alpha158 features...")
alpha158_data = alpha158_handler.fetch()
print(f"✅ Alpha158 data loaded successfully")
print(f"📊 Data shape: {alpha158_data.shape}")
print(f"📊 Number of features: {alpha158_data.shape[1]} features")
# Display sample features
print(f"\n📋 Sample features (first 10):")
feature_names = alpha158_data.columns[:10].tolist()
for i, feature in enumerate(feature_names, 1):
print(f" {i:2d}. {feature}")
# Basic statistics
print(f"\n📈 Basic statistics:")
stats = alpha158_data.describe()
print(f" Mean range: [{stats.loc['mean'].min():.4f}, {stats.loc['mean'].max():.4f}]")
print(f" Std range: [{stats.loc['std'].min():.4f}, {stats.loc['std'].max():.4f}]")
# Check missing values
missing_pct = alpha158_data.isnull().sum().sum() / alpha158_data.size * 100
print(f" Missing values: {missing_pct:.2f}%")
return alpha158_data
except Exception as e:
print(f"❌ Alpha158 data loading failed: {e}")
return None
def analyze_factor_groups(self, alpha158_data):
"""
Analyze the different groups of Alpha158 factors
"""
if alpha158_data is None:
return
print("\n🔍 Factor group analysis")
print("=" * 60)
# Group factors by naming pattern
factor_groups = {
'price_based': [], # Price-based factors
'volume_based': [], # Volume-based factors
'return_based': [], # Return-based factors
'technical': [], # Technical indicators
'statistical': [] # Statistical features
}
# Classify factors
for col in alpha158_data.columns:
col_lower = col.lower()
if any(x in col_lower for x in ['close', 'open', 'high', 'low', 'price']):
factor_groups['price_based'].append(col)
elif any(x in col_lower for x in ['volume', 'amount', 'vol']):
factor_groups['volume_based'].append(col)
elif any(x in col_lower for x in ['return', 'ret', 'pct']):
factor_groups['return_based'].append(col)
elif any(x in col_lower for x in ['ma', 'mean', 'std', 'max', 'min', 'rank']):
factor_groups['technical'].append(col)
else:
factor_groups['statistical'].append(col)
# Display group statistics
for group_name, factors in factor_groups.items():
if factors:
group_data = alpha158_data[factors]
print(f"\n📊 {group_name.replace('_', ' ').title()} group:")
print(f" Number of factors: {len(factors)}")
print(f" Sample factors: {factors[:3]}")
# Compute within-group correlation
if len(factors) > 1:
corr_matrix = group_data.corr()
avg_corr = corr_matrix.values[np.triu_indices_from(corr_matrix.values, k=1)].mean()
print(f" Average within-group correlation: {avg_corr:.3f}")
return factor_groups
def factor_importance_analysis(self, alpha158_data, return_data=None):
"""
Analyze factor importance using multiple methods
"""
print("\n🎯 Factor Importance Analysis")
print("=" * 60)
# Method 1: Correlation with returns
if return_data is not None:
print("Method 1: Correlation with returns")
# Compute the correlation for each factor
correlations = {}
for factor in alpha158_data.columns:
try:
# Align data
factor_data = alpha158_data[factor].dropna()
aligned_returns = return_data.loc[factor_data.index]
if len(factor_data) > 10: # Minimum sample size
corr = factor_data.corr(aligned_returns)
correlations[factor] = abs(corr) # Use absolute correlation
except:
continue
# Display the factors with the highest correlations
if correlations:
sorted_corr = sorted(correlations.items(), key=lambda x: x[1], reverse=True)
print(" Top 10 factors by correlation:")
for i, (factor, corr) in enumerate(sorted_corr[:10], 1):
print(f" {i:2d}. {factor}: {corr:.4f}")
# Method 2: Variance analysis
print("\nMethod 2: Variance analysis")
variances = alpha158_data.var().sort_values(ascending=False)
print(" Top 10 factors by variance:")
for i, (factor, var) in enumerate(variances.head(10).items(), 1):
print(f" {i:2d}. {factor}: {var:.4f}")
# Method 3: Missing value analysis
print("\nMethod 3: Data completeness analysis")
completeness = (1 - alpha158_data.isnull().mean()).sort_values(ascending=False)
print(" Top 10 factors by completeness:")
for i, (factor, complete) in enumerate(completeness.head(10).items(), 1):
print(f" {i:2d}. {factor}: {complete:.2%}")
return {
'correlations': correlations if 'correlations' in locals() else {},
'variances': variances,
'completeness': completeness
}
# Usage example
def demonstrate_alpha158_exploration():
"""
Full demonstration of Alpha158 exploration
"""
try:
# Initialize the explorer
explorer = Alpha158Explorer()
# Get factor categories
factor_categories = explorer.get_alpha158_factors()
print("Alpha158 factor categories:")
for category, info in factor_categories.items():
print(f"\n{category}: {info['description']}")
print(f"Sample factors: {info['factors'][:3]}")
# Demonstrate usage
alpha158_data = explorer.demonstrate_alpha158_usage()
if alpha158_data is not None:
# Analyze factor groups
factor_groups = explorer.analyze_factor_groups(alpha158_data)
# Analyze factor importance
importance_results = explorer.factor_importance_analysis(alpha158_data)
print("\n🎉 Alpha158 exploration complete!")
except Exception as e:
print(f"❌ Alpha158 exploration failed: {e}")
# Run the demonstration
# demonstrate_alpha158_exploration()
5.2.2 Alpha360 Factor Set in Detail¶
# Alpha360 factor set exploration
from qlib.contrib.data.handler import Alpha360
class Alpha360Explorer:
"""
Comprehensive exploration of the Alpha360 factor set
"""
def __init__(self):
print("🚀 Alpha360 factor set explorer")
print("=" * 60)
def compare_alpha158_vs_alpha360(self):
"""
Compare the Alpha158 and Alpha360 factor sets
"""
comparison = {
'Alpha158': {
'factor_count': 158,
'description': 'Basic technical factors',
'frequency': 'Daily',
'categories': [
'Price momentum',
'Volume patterns',
'Volatility indicators',
'Moving averages',
'Technical indicators'
],
'advantages': [
'Well tested and stable',
'Low computational cost',
'Good interpretability'
],
'use_cases': [
'General stock selection',
'Long-term strategies',
'Suitable for beginners'
]
},
'Alpha360': {
'factor_count': 360,
'description': 'Enhanced factor set with more features',
'frequency': 'Daily',
'categories': [
'Advanced price patterns',
'Complex volume indicators',
'Cross-sectional features',
'Time-series patterns',
'Statistical transformations'
],
'advantages': [
'Broader coverage',
'Stronger predictive power',
'Advanced feature engineering'
],
'use_cases': [
'Professional quant strategies',
'Short-term trading',
'Advanced users'
]
}
}
print("📊 Alpha158 vs Alpha360 Comparison")
print("=" * 70)
for factor_set, details in comparison.items():
print(f"\n🔍 {factor_set}:")
print(f" Factor count: {details['factor_count']}")
print(f" Description: {details['description']}")
print(f" Frequency: {details['frequency']}")
print(f" Categories:")
for category in details['categories']:
print(f" • {category}")
print(f" Advantages:")
for advantage in details['advantages']:
print(f" • {advantage}")
print(f" Use cases:")
for use_case in details['use_cases']:
print(f" • {use_case}")
return comparison
def demonstrate_alpha360_usage(self):
"""
Demonstrate usage of the Alpha360 handler
"""
print("\n📊 Alpha360 Handler Usage")
print("=" * 60)
# Configure the Alpha360 handler
handler_config = {
"start_time": "2020-01-01",
"end_time": "2020-02-29", # Shorter period for the demo
"fit_start_time": "2020-01-01",
"fit_end_time": "2020-01-31",
"instruments": D.instruments('csi300')[:50] # Subset for the demo
}
try:
print("🔄 Initializing Alpha360 handler...")
alpha360_handler = Alpha360(**handler_config)
print("🔄 Fetching Alpha360 features...")
alpha360_data = alpha360_handler.fetch()
print(f"✅ Alpha360 data loaded successfully")
print(f"📊 Data shape: {alpha360_data.shape}")
print(f"📊 Total features: {alpha360_data.shape[1]} features")
# Analyze feature distribution
self.analyze_alpha360_features(alpha360_data)
return alpha360_data
except Exception as e:
print(f"❌ Alpha360 data loading failed: {e}")
print("💡 Note: Alpha360 requires more computational resources")
return None
def analyze_alpha360_features(self, alpha360_data):
"""
Analyze the characteristics of Alpha360 features
"""
print(f"\n🔍 Alpha360 Feature Analysis")
print("-" * 50)
# Feature naming patterns
feature_patterns = {
'kbar': 0, # K-line (candlestick) patterns
'price': 0, # Price-based
'volume': 0, # Volume-based
'rolling': 0, # Rolling statistics
'rank': 0, # Rank features
'qtlu': 0, # Quantile features
'others': 0 # Other patterns
}
# Classify features by pattern
for col in alpha360_data.columns:
col_lower = col.lower()
classified = False
for pattern in feature_patterns.keys():
if pattern != 'others' and pattern in col_lower:
feature_patterns[pattern] += 1
classified = True
break
if not classified:
feature_patterns['others'] += 1
# Display the pattern distribution
print("📊 Feature pattern distribution:")
for pattern, count in feature_patterns.items():
if count > 0:
percentage = count / len(alpha360_data.columns) * 100
print(f" {pattern.capitalize()}: {count} ({percentage:.1f}%)")
# Statistical summary
print(f"\n📈 Statistical summary:")
stats = alpha360_data.describe()
print(f" Mean range: [{stats.loc['mean'].min():.4f}, {stats.loc['mean'].max():.4f}]")
print(f" Std range: [{stats.loc['std'].min():.4f}, {stats.loc['std'].max():.4f}]")
# Data quality check
missing_by_feature = alpha360_data.isnull().sum()
missing_features = (missing_by_feature > 0).sum()
print(f" Features with missing values: {missing_features}")
if missing_features > 0:
worst_features = missing_by_feature.nlargest(5)
print(f" 5 features with the most missing values:")
for feature, missing_count in worst_features.items():
missing_pct = missing_count / len(alpha360_data) * 100
print(f" {feature}: {missing_count} ({missing_pct:.1f}%)")
# Usage example
def demonstrate_alpha360_exploration():
"""
Full demonstration of Alpha360 exploration
"""
try:
explorer = Alpha360Explorer()
# Compare factor sets
comparison = explorer.compare_alpha158_vs_alpha360()
# Demonstrate Alpha360 usage
alpha360_data = explorer.demonstrate_alpha360_usage()
if alpha360_data is not None:
print(f"\n✅ Alpha360 exploration completed successfully!")
else:
print(f"\n⚠️ Alpha360 data loading failed - this is normal in the demo")
except Exception as e:
print(f"❌ Alpha360 exploration failed: {e}")
# Run the demonstration
# demonstrate_alpha360_exploration()
5.3 Custom Factor Development¶
5.3.1 Factor Expression Syntax¶
# Custom factor development framework
import pandas as pd
import numpy as np
from qlib.data import D
import warnings
warnings.filterwarnings('ignore')
class CustomFactorLibrary:
"""
Custom factor development and testing library
"""
def __init__(self):
self.factor_registry = {}
self.factor_descriptions = {}
print("🔧 Custom Factor Development Library")
print("=" * 60)
def register_factor(self, name, expression, description, category='custom'):
"""
Register a custom factor
"""
self.factor_registry[name] = {
'expression': expression,
'description': description,
'category': category
}
self.factor_descriptions[name] = description
print(f"✅ Registered factor: {name}")
def momentum_factors(self):
"""
Develop momentum-based factors
"""
print("\n📈 Momentum Factor Development")
print("-" * 50)
momentum_factors = {
# Classic momentum factors
'momentum_5d': {
'expression': '($close / Ref($close, 5) - 1)',
'description': '5-day price momentum',
'interpretation': 'Positive value indicates upward momentum'
},
'momentum_20d': {
'expression': '($close / Ref($close, 20) - 1)',
'description': '20-day price momentum',
'interpretation': 'Medium-term momentum indicator'
},
# Volume-adjusted momentum
'vol_adj_momentum': {
'expression': '($close / Ref($close, 10) - 1) * Log($volume / Mean($volume, 20))',
'description': 'Volume-adjusted momentum',
'interpretation': 'Momentum weighted by relative volume'
},
# Momentum acceleration
'momentum_acceleration': {
'expression': '(($close / Ref($close, 5) - 1) - ($close / Ref($close, 10) - 1))',
'description': 'Momentum acceleration',
'interpretation': 'Rate of change of momentum'
},
# Risk-adjusted momentum
'risk_adj_momentum': {
'expression': '($close / Ref($close, 20) - 1) / Std($close / Ref($close, 1) - 1, 20)',
'description': 'Risk-adjusted momentum',
'interpretation': 'Momentum divided by volatility'
}
}
# Register momentum factors
for name, info in momentum_factors.items():
self.register_factor(name, info['expression'], info['description'], 'momentum')
return momentum_factors
def reversal_factors(self):
"""
Develop mean-reversion factors
"""
print("\n🔄 Mean-Reversion Factor Development")
print("-" * 50)
reversal_factors = {
# Short-term reversal
'reversal_1d': {
'expression': '-($close / Ref($close, 1) - 1)',
'description': '1-day reversal factor',
'interpretation': 'Negative of the daily return'
},
# Bollinger band mean reversion
'bollinger_reversal': {
'expression': '-(($close - Mean($close, 20)) / Std($close, 20))',
'description': 'Bollinger band reversal',
'interpretation': 'Distance from the moving average'
},
# RSI-based reversal
'rsi_reversal': {
'expression': '-(RSI($close, 14) - 50) / 50',
'description': 'RSI-based reversal factor',
'interpretation': 'Normalized degree of RSI deviation from 50'
},
# Volume-price reversal
'volume_price_reversal': {
'expression': '-($close / Ref($close, 1) - 1) * ($volume / Mean($volume, 10))',
'description': 'Volume-weighted price reversal',
'interpretation': 'Return weighted by relative volume'
},
# Overnight reversal
'overnight_reversal': {
'expression': '-($open / Ref($close, 1) - 1)',
'description': 'Overnight gap reversal',
'interpretation': 'Negative of the overnight return'
}
}
# Register reversal factors
for name, info in reversal_factors.items():
self.register_factor(name, info['expression'], info['description'], 'reversal')
return reversal_factors
def volatility_factors(self):
"""
Develop volatility-based factors
"""
print("\n📊 Volatility Factor Development")
print("-" * 50)
volatility_factors = {
# Historical volatility
'volatility_20d': {
'expression': 'Std($close / Ref($close, 1) - 1, 20)',
'description': '20-day historical volatility',
'interpretation': 'Standard deviation of daily returns'
},
# Realized volatility
'realized_vol': {
'expression': 'Std(Log($high / $low), 10)',
'description': 'Realized volatility based on high/low prices',
'interpretation': 'Intraday range volatility'
},
# Volatility ratio
'vol_ratio': {
'expression': 'Std($close / Ref($close, 1) - 1, 5) / Std($close / Ref($close, 1) - 1, 20)',
'description': 'Short-term to long-term volatility ratio',
'interpretation': 'Recent volatility change'
},
# Volatility clustering
'vol_clustering': {
'expression': 'Corr(Abs($close / Ref($close, 1) - 1), Abs(Ref($close / Ref($close, 1) - 1, 1)), 10)',
'description': 'Volatility clustering measure',
'interpretation': 'Autocorrelation of absolute returns'
},
# Downside volatility
'downside_vol': {
'expression': 'Std(If($close / Ref($close, 1) - 1 < 0, $close / Ref($close, 1) - 1, 0), 20)',
'description': 'Downside volatility',
'interpretation': 'Volatility of negative returns only'
}
}
# Register volatility factors
for name, info in volatility_factors.items():
self.register_factor(name, info['expression'], info['description'], 'volatility')
return volatility_factors
def quality_factors(self):
"""
Develop quality-based factors
"""
print("\n⭐ Quality Factor Development")
print("-" * 50)
quality_factors = {
# Price stability
'price_stability': {
'expression': '1 / (1 + Std($close / Ref($close, 1) - 1, 60))',
'description': 'Price stability measure',
'interpretation': 'Higher value indicates more stable prices'
},
# Trend consistency
'trend_consistency': {
'expression': 'Mean(If($close > Ref($close, 1), 1, -1), 20)',
'description': 'Trend consistency',
'interpretation': 'Consistency of daily price changes'
},
# Volume quality
'volume_quality': {
'expression': '1 - Std($volume, 20) / Mean($volume, 20)',
'description': 'Volume consistency measure',
'interpretation': 'Lower coefficient of variation indicates better quality'
},
# Information quality
'info_quality': {
'expression': 'Corr($volume, Abs($close / Ref($close, 1) - 1), 20)',
'description': 'Volume-volatility correlation',
'interpretation': 'Price discovery quality'
},
# Momentum quality
'momentum_quality': {
'expression': '($close / Ref($close, 20) - 1) / Count($close > Ref($close, 1), 20) * 20',
'description': 'Momentum per up day',
'interpretation': 'Efficiency of upward movements'
}
}
# Register quality factors
for name, info in quality_factors.items():
self.register_factor(name, info['expression'], info['description'], 'quality')
return quality_factors
def composite_factors(self):
"""
Develop composite factors that combine multiple signals
"""
print("\n🔗 Composite Factor Development")
print("-" * 50)
composite_factors = {
# Momentum-volume composite
'momentum_volume_composite': {
'expression': '($close / Ref($close, 10) - 1) * Rank($volume / Mean($volume, 20))',
'description': 'Momentum weighted by volume rank',
'interpretation': 'Volume-supported momentum'
},
# Multi-timeframe momentum
'multi_tf_momentum': {
'expression': '0.5 * ($close / Ref($close, 5) - 1) + 0.3 * ($close / Ref($close, 20) - 1) + 0.2 * ($close / Ref($close, 60) - 1)',
'description': 'Multi-timeframe momentum composite',
'interpretation': 'Weighted average of different momentum horizons'
},
# Volatility-adjusted returns
'vol_adj_returns': {
'expression': '($close / Ref($close, 20) - 1) / (Std($close / Ref($close, 1) - 1, 20) + 0.01)',
'description': 'Volatility-adjusted returns',
'interpretation': 'Risk-adjusted performance measure'
},
# Price-volume divergence
'price_volume_divergence': {
'expression': 'Corr($close / Ref($close, 1) - 1, $volume / Ref($volume, 1) - 1, 10)',
'description': 'Price-volume relationship',
'interpretation': 'Consistency of price and volume changes'
},
# Market strength indicator
'market_strength': {
'expression': '($close - $low) / ($high - $low) * ($volume / Mean($volume, 10))',
'description': 'Intraday strength with volume',
'interpretation': 'Position within the daily range weighted by volume'
}
}
# Register composite factors
for name, info in composite_factors.items():
self.register_factor(name, info['expression'], info['description'], 'composite')
return composite_factors
def build_factor_library(self):
"""
Build the complete custom factor library
"""
print("🏗️ Building the Custom Factor Library")
print("=" * 60)
# Build all factor categories
momentum_factors = self.momentum_factors()
reversal_factors = self.reversal_factors()
volatility_factors = self.volatility_factors()
quality_factors = self.quality_factors()
composite_factors = self.composite_factors()
# Summary
total_factors = len(self.factor_registry)
categories = {}
for name, info in self.factor_registry.items():
category = info['category']
if category not in categories:
categories[category] = 0
categories[category] += 1
print(f"\n📊 Factor Library Summary:")
print(f" Total factors: {total_factors}")
print(f" Categories:")
for category, count in categories.items():
print(f" {category.capitalize()}: {count} factors")
return self.factor_registry
def test_factor_expression(self, expression, sample_data=None):
"""
Test the validity of a factor expression
"""
print(f"\n🧪 Testing factor expression:")
print(f"Expression: {expression}")
try:
if sample_data is None:
# Create sample test data
dates = pd.date_range('2020-01-01', periods=50, freq='D')
instruments = ['STOCK001', 'STOCK002', 'STOCK003']
multi_index = pd.MultiIndex.from_product(
[dates, instruments],
names=['datetime', 'instrument']
)
# Generate sample OHLCV data
np.random.seed(42)
n = len(multi_index)
sample_data = pd.DataFrame({
'$open': np.random.uniform(90, 110, n),
'$high': np.random.uniform(95, 115, n),
'$low': np.random.uniform(85, 105, n),
'$close': np.random.uniform(90, 110, n),
'$volume': np.random.lognormal(10, 1, n)
}, index=multi_index)
# Ensure OHLC consistency
sample_data['$high'] = np.maximum(sample_data['$high'],
np.maximum(sample_data['$open'], sample_data['$close']))
sample_data['$low'] = np.minimum(sample_data['$low'],
np.minimum(sample_data['$open'], sample_data['$close']))
# This is a simplified test - in practice you would use Qlib's expression engine
print("✅ Expression syntax looks valid")
print("💡 Note: Full validation requires Qlib's expression engine")
return True
except Exception as e:
print(f"❌ Expression test failed: {e}")
return False
# Usage example
def demonstrate_custom_factor_development():
"""
Full demonstration of custom factor development
"""
try:
# Initialize the custom factor library
factor_lib = CustomFactorLibrary()
# Build the factor library
factor_registry = factor_lib.build_factor_library()
# Test some factor expressions
print(f"\n🧪 Testing sample factor expressions:")
test_expressions = [
'($close / Ref($close, 5) - 1)', # Simple momentum
'Std($close / Ref($close, 1) - 1, 20)', # Volatility
'1 / (1 + Std($close / Ref($close, 1) - 1, 60))' # Stability
]
for expr in test_expressions:
factor_lib.test_factor_expression(expr)
print(f"\n🎉 Custom factor development demonstration complete!")
return factor_registry
except Exception as e:
print(f"❌ Custom factor development failed: {e}")
# Run the demonstration
# factor_registry = demonstrate_custom_factor_development()
5.3.2 Custom Factor Implementation Examples¶
# Advanced custom factor implementation
from qlib.data.ops import *
import talib # Technical analysis library (if available)
class AdvancedFactorLibrary:
"""
Advanced custom factor implementation with real computations
"""
def __init__(self):
print("🚀 Advanced Custom Factor Library")
print("=" * 60)
def technical_indicator_factors(self, data):
"""
Implement technical indicator factors
"""
print("\n📈 Technical Indicator Factors")
print("-" * 50)
factors = {}
try:
# Extract OHLCV data
close = data['$close'].unstack('instrument')
high = data['$high'].unstack('instrument')
low = data['$low'].unstack('instrument')
volume = data['$volume'].unstack('instrument')
# RSI - Relative Strength Index
factors['RSI_14'] = close.apply(lambda x: self.calculate_rsi(x, 14))
# MACD - Moving Average Convergence Divergence
factors['MACD'], factors['MACD_signal'], factors['MACD_hist'] = self.calculate_macd(close)
# Bollinger Bands
factors['BB_upper'], factors['BB_middle'], factors['BB_lower'] = self.calculate_bollinger_bands(close)
factors['BB_position'] = (close - factors['BB_lower']) / (factors['BB_upper'] - factors['BB_lower'])
# Williams %R
factors['Williams_R'] = self.calculate_williams_r(high, low, close)
# Stochastic Oscillator
factors['Stoch_K'], factors['Stoch_D'] = self.calculate_stochastic(high, low, close)
# Average True Range
factors['ATR_14'] = self.calculate_atr(high, low, close, 14)
# Commodity Channel Index
factors['CCI_20'] = self.calculate_cci(high, low, close, 20)
print(f"✅ Generated {len(factors)} technical indicator factors")
except Exception as e:
print(f"❌ Technical indicator calculation failed: {e}")
factors = {}
return factors
def calculate_rsi(self, price, period=14):
"""
Calculate the Relative Strength Index
"""
delta = price.diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=period).mean()
avg_loss = loss.rolling(window=period).mean()
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return rsi
def calculate_macd(self, price, fast=12, slow=26, signal=9):
"""
Calculate MACD (Moving Average Convergence Divergence)
"""
ema_fast = price.ewm(span=fast).mean()
ema_slow = price.ewm(span=slow).mean()
macd = ema_fast - ema_slow
macd_signal = macd.ewm(span=signal).mean()
macd_histogram = macd - macd_signal
return macd, macd_signal, macd_histogram
def calculate_bollinger_bands(self, price, period=20, std_dev=2):
"""
Calculate Bollinger Bands
"""
middle = price.rolling(window=period).mean()
std = price.rolling(window=period).std()
upper = middle + (std * std_dev)
lower = middle - (std * std_dev)
return upper, middle, lower
def calculate_williams_r(self, high, low, close, period=14):
"""
Calculate Williams %R
"""
highest_high = high.rolling(window=period).max()
lowest_low = low.rolling(window=period).min()
williams_r = (highest_high - close) / (highest_high - lowest_low) * -100
return williams_r
def calculate_stochastic(self, high, low, close, k_period=14, d_period=3):
"""
Calculate the Stochastic Oscillator
"""
lowest_low = low.rolling(window=k_period).min()
highest_high = high.rolling(window=k_period).max()
k_percent = ((close - lowest_low) / (highest_high - lowest_low)) * 100
d_percent = k_percent.rolling(window=d_period).mean()
return k_percent, d_percent
def calculate_atr(self, high, low, close, period=14):
"""
Calculate the Average True Range
"""
high_low = high - low
high_close_prev = np.abs(high - close.shift(1))
low_close_prev = np.abs(low - close.shift(1))
true_range = np.maximum(high_low, np.maximum(high_close_prev, low_close_prev))
atr = true_range.rolling(window=period).mean()
return atr
def calculate_cci(self, high, low, close, period=20):
"""
Calculate the Commodity Channel Index
"""
tp = (high + low + close) / 3 # Typical price
ma = tp.rolling(window=period).mean()
md = tp.rolling(window=period).apply(lambda x: np.mean(np.abs(x - x.mean())))
cci = (tp - ma) / (0.015 * md)
return cci
def statistical_factors(self, data):
"""
Implement statistical factors
"""
print("\n📊 Statistical Factors")
print("-" * 50)
factors = {}
try:
close = data['$close'].unstack('instrument')
volume = data['$volume'].unstack('instrument')
# Rolling correlation of price and volume
factors['price_volume_corr'] = close.rolling(20).corr(volume)
# Price momentum over different horizons
for period in [5, 10, 20, 60]:
factors[f'momentum_{period}d'] = close / close.shift(period) - 1
# Volatility factors
returns = close.pct_change()
for period in [10, 20, 60]:
factors[f'volatility_{period}d'] = returns.rolling(period).std()
# Skewness and kurtosis
factors['skewness_20d'] = returns.rolling(20).skew()
factors['kurtosis_20d'] = returns.rolling(20).kurt()
# Price dispersion
factors['price_dispersion'] = close.rolling(20).std() / close.rolling(20).mean()
# Volume rate of change
factors['volume_roc'] = volume / volume.shift(20) - 1
# Beta calculation (relative to market)
market_return = returns.mean(axis=1) # Simple market proxy
factors['beta_60d'] = returns.rolling(60).apply(
lambda x: np.cov(x, market_return[-len(x):])[0, 1] / np.var(market_return[-len(x):])
if len(x) == 60 else np.nan
)
print(f"✅ Generated {len(factors)} statistical factors")
except Exception as e:
print(f"❌ Statistical factor calculation failed: {e}")
factors = {}
return factors
def risk_factors(self, data):
"""
Implement risk-based factors
"""
print("\n⚠️ Risk Factors")
print("-" * 50)
factors = {}
try:
close = data['$close'].unstack('instrument')
returns = close.pct_change()
# Value at Risk
factors['VaR_5pct'] = returns.rolling(60).quantile(0.05)
factors['VaR_1pct'] = returns.rolling(60).quantile(0.01)
# Conditional Value at Risk (expected shortfall)
factors['CVaR_5pct'] = returns.rolling(60).apply(
lambda x: x[x <= x.quantile(0.05)].mean()
)
# Max drawdown
factors['max_drawdown_60d'] = self.calculate_max_drawdown(close)
# Downside deviation
factors['downside_deviation'] = returns.rolling(30).apply(
lambda x: np.sqrt(np.mean(np.minimum(x, 0)**2))
)
# Upside/downside capture ratios
market_return = returns.mean(axis=1)
factors['upside_capture'] = self.calculate_capture_ratio(returns, market_return, 'up')
factors['downside_capture'] = self.calculate_capture_ratio(returns, market_return, 'down')
# Tail ratio
factors['tail_ratio'] = (-returns.rolling(60).quantile(0.05)) / returns.rolling(60).quantile(0.95)
print(f"✅ Generated {len(factors)} risk factors")
except Exception as e:
print(f"❌ Risk factor calculation failed: {e}")
factors = {}
return factors
def calculate_max_drawdown(self, price_series):
"""
Calculate max drawdown
"""
cumulative = (1 + price_series.pct_change()).cumprod()
running_max = cumulative.expanding().max()
drawdown = (cumulative - running_max) / running_max
max_drawdown = drawdown.rolling(60).min()
return max_drawdown
def calculate_capture_ratio(self, returns, market_returns, direction='up'):
"""
Calculate the upside/downside capture ratio
"""
if direction == 'up':
mask = market_returns > 0
else:
mask = market_returns < 0
capture_ratio = returns.rolling(60).apply(
lambda x: (x[mask[-len(x):]].mean() / market_returns[mask][-len(x):].mean())
if len(x) == 60 and mask[-len(x):].sum() > 0 else np.nan
)
return capture_ratio
def generate_factor_report(self, factors_dict):
"""
Generate a comprehensive factor report
"""
print(f"\n📋 Factor Generation Report")
print("=" * 60)
total_factors = sum(len(factors) for factors in factors_dict.values())
print(f"Total factors generated: {total_factors}")
for category, factors in factors_dict.items():
if factors:
print(f"\n📊 {category.replace('_', ' ').title()} category:")
print(f" Number of factors: {len(factors)}")
# Sample factor names
sample_names = list(factors.keys())[:5]
print(f" Sample factors: {sample_names}")
# Check data quality
sample_factor = next(iter(factors.values()))
if hasattr(sample_factor, 'isnull'):
missing_pct = sample_factor.isnull().sum().sum() / sample_factor.size * 100
print(f" Average missing values: {missing_pct:.1f}%")
# Usage example
def demonstrate_advanced_factor_implementation():
"""
Demonstrate advanced factor implementation
"""
try:
# Initialize the advanced factor library
advanced_lib = AdvancedFactorLibrary()
# Load sample data
print("🔄 Loading sample data for factor computation...")
# In practice, you would load real data from Qlib
# sample_data = D.features(instruments, fields, start_time, end_time)
# For the demo, create synthetic data
dates = pd.date_range('2020-01-01', periods=100, freq='D')
instruments = ['STOCK001', 'STOCK002', 'STOCK003', 'STOCK004', 'STOCK005']
multi_index = pd.MultiIndex.from_product(
[dates, instruments],
names=['datetime', 'instrument']
)
np.random.seed(42)
n = len(multi_index)
sample_data = pd.DataFrame({
'$open': np.random.uniform(90, 110, n),
'$high': np.random.uniform(95, 115, n),
'$low': np.random.uniform(85, 105, n),
'$close': np.random.uniform(90, 110, n),
'$volume': np.random.lognormal(10, 1, n)
}, index=multi_index)
# Ensure OHLC consistency
sample_data['$high'] = np.maximum(sample_data['$high'],
np.maximum(sample_data['$open'], sample_data['$close']))
sample_data['$low'] = np.minimum(sample_data['$low'],
np.minimum(sample_data['$open'], sample_data['$close']))
print(f"✅ Sample data loaded: {sample_data.shape}")
# Generate different types of factors
all_factors = {}
# Technical indicators
all_factors['technical'] = advanced_lib.technical_indicator_factors(sample_data)
# Statistical factors
all_factors['statistical'] = advanced_lib.statistical_factors(sample_data)
# Risk factors
all_factors['risk'] = advanced_lib.risk_factors(sample_data)
# Generate the report
advanced_lib.generate_factor_report(all_factors)
print(f"\n🎉 Advanced factor implementation complete!")
return all_factors
except Exception as e:
print(f"❌ Advanced factor implementation failed: {e}")
return None
# Run the demonstration
# advanced_factors = demonstrate_advanced_factor_implementation()
Chapter Summary¶
This chapter provided a detailed introduction to the core concepts and practical methods of factor engineering:
- Factor fundamentals:
- Definition and classification system of factors
- Factor effectiveness evaluation framework
-
Characteristics and use cases of different factor types
-
Qlib's built-in factor libraries:
- Detailed analysis of the Alpha158 factor set
- Advanced features of the Alpha360 factor set
-
Usage methods and best practices for built-in factors
-
Custom factor development:
- Factor expression syntax and rules
- Implementation of multiple types of custom factors
-
Computation of advanced technical indicators and statistical factors
-
Factor effectiveness evaluation:
- IC analysis and quantile analysis methods
- Factor stability and turnover evaluation
- Comprehensive factor quality report generation
Mastering factor engineering is key to success in quantitative investing, providing a powerful feature foundation for subsequent model training and strategy development.
Exercises¶
-
Factor classification practice: Analyze 10 given factors, classify them along different dimensions, and explain the economic meaning of each factor
-
Custom factor development: Develop 3 original factors, including one momentum type, one reversal type, and one quality type, and validate their effectiveness
-
Factor effectiveness analysis: Use IC analysis, quantile analysis, and other methods to evaluate the predictive power and stability of factors
-
Factor combination optimization: Select the optimal 10-factor combination from 50 candidate factors, considering correlation and effectiveness