A Complete Guide to Building Qlib Alpha158 and Alpha360 Factors¶
This guide synthesizes the official Qlib documentation, source-code analysis, and hands-on practice into a complete walkthrough for building the Alpha158 and Alpha360 factor sets.
📋 Table of Contents¶
- Overview
- Core Concepts
- Alpha158 in Depth
- Alpha360 in Depth
- Data Preparation
- Construction Methods
- Source-Code Walkthrough
- Practical Examples
- Performance Optimization
- FAQ
- References
Overview¶
What Are Alpha Factors?¶
Alpha factors are feature variables used in quantitative investing to predict stock returns. Qlib provides two classic factor sets:
- Alpha158: 158 engineered technical indicators, suited to traditional machine-learning models
- Alpha360: 360 raw price series, suited to deep-learning models
Design Philosophy Compared¶
| Property | Alpha158 | Alpha360 |
|---|---|---|
| Number of factors | 158 | 360 |
| Feature type | Engineered technical indicators | Raw price series |
| Feature design | Hand-crafted from financial domain knowledge | Raw data retained for the model to learn from |
| Suitable models | LightGBM, XGBoost, linear regression | LSTM, Transformer, GRU |
| Interpretability | High (each factor has a clear meaning) | Low (the model must extract features itself) |
| Temporal information | Aggregated statistics (e.g., 5/10/20-day moving averages) | Full 60-day time series |
| Computational cost | Low | High (needs more memory) |
| Spatial structure | Features largely independent | Strong spatial structure along the time axis |
Core Concepts¶
1. Data Requirements¶
Required raw fields (OHLCV)¶
# 5 required fields
fields = {
'open': open price,
'high': high price,
'low': low price,
'close': close price,
'volume': trading volume
}
Recommended field¶
# Strongly recommended
'vwap': Volume Weighted Average Price
# If your data source has no VWAP, approximate it with:
vwap = (high + low + close) / 3
# Or, slightly more precisely:
vwap = (high + low + close + open) / 4
2. Normalization Strategy¶
Qlib uses relative normalization to remove scale effects:
# Price factors: divide by the current close price
normalized_price = price_feature / $close
# Volume factors: divide by the current volume (small epsilon to avoid division by zero)
normalized_volume = volume_feature / ($volume + 1e-12)
Benefits: - Removes price-scale differences across stocks - Makes factors comparable - Facilitates cross-sectional and cross-temporal model training
3. Label Definition¶
Alpha158 and Alpha360 share the same label definition:
# Default label: return from T+1 to T+2
LABEL0 = "Ref($close, -2)/Ref($close, -1) - 1"
# Explanation:
# - Ref($close, -2): close price 2 days ahead
# - Ref($close, -1): close price 1 day ahead
# - label = (T+2 close / T+1 close) - 1
Why not the T to T+1 return?
China's A-share market follows a T+1 trading rule: after observing the close on day T, the earliest you can buy is day T+1, and you cannot sell until day T+2. Predicting the T+1 to T+2 return therefore matches the real trading scenario.
4. The Qlib Expression Engine¶
Qlib defines factor computations via string expressions:
# Basic fields
$close, $open, $high, $low, $volume, $vwap
# Time-series operations
Ref($close, 5) # close price 5 days ago
Mean($close, 20) # 20-day moving average
Std($close, 20) # 20-day standard deviation
# Math operations
Greater(a, b) # max(a, b)
Less(a, b) # min(a, b)
Abs(x) # absolute value
# Rolling-window statistics
Slope($close, 20) # 20-day price slope (linear regression)
Rsquare($close, 20) # R² of 20-day linear regression
Corr($close, $volume, 20) # 20-day price-volume correlation
Alpha158 in Depth¶
Factor Composition Overview¶
Alpha158 contains 158 factors in 4 groups:
| Group | Count | Description |
|---|---|---|
| Candlestick pattern features | 9 | Single-day OHLC pattern indicators |
| Price features | 4 | Same-day relative prices |
| Volume features | 0 | (already covered by rolling indicators) |
| Rolling-window indicators | 145 | 5 windows × 29 operators |
| Total | 158 |
1. Candlestick Pattern Features (9)¶
These features are computed from a single day's OHLC data and describe the candlestick shape:
| Factor | Formula | Financial meaning |
|---|---|---|
| KMID | ($close-$open)/$open |
Candlestick body midpoint, i.e., intraday return |
| KLEN | ($high-$low)/$open |
Total candlestick length, i.e., intraday range |
| KMID2 | ($close-$open)/($high-$low+1e-12) |
Body share of the range, reflecting bull-vs-bear strength |
| KUP | ($high-Greater($open, $close))/$open |
Upper-shadow ratio, reflecting overhead pressure |
| KUP2 | ($high-Greater($open, $close))/($high-$low+1e-12) |
Upper shadow as a share of the total range |
| KLOW | (Less($open, $close)-$low)/$open |
Lower-shadow ratio, reflecting underlying support |
| KLOW2 | (Less($open, $close)-$low)/($high-$low+1e-12) |
Lower shadow as a share of the total range |
| KSFT | (2*$close-$high-$low)/$open |
Close price position relative to the range midpoint |
| KSFT2 | (2*$close-$high-$low)/($high-$low+1e-12) |
Close price position within the range |
Python example:
import pandas as pd
def calc_kbar_features(df):
"""Compute candlestick pattern features."""
features = pd.DataFrame(index=df.index)
features['KMID'] = (df['close'] - df['open']) / df['open']
features['KLEN'] = (df['high'] - df['low']) / df['open']
features['KMID2'] = (df['close'] - df['open']) / (df['high'] - df['low'] + 1e-12)
features['KUP'] = (df['high'] - df[['open', 'close']].max(axis=1)) / df['open']
features['KUP2'] = (df['high'] - df[['open', 'close']].max(axis=1)) / (df['high'] - df['low'] + 1e-12)
features['KLOW'] = (df[['open', 'close']].min(axis=1) - df['low']) / df['open']
features['KLOW2'] = (df[['open', 'close']].min(axis=1) - df['low']) / (df['high'] - df['low'] + 1e-12)
features['KSFT'] = (2*df['close'] - df['high'] - df['low']) / df['open']
features['KSFT2'] = (2*df['close'] - df['high'] - df['low']) / (df['high'] - df['low'] + 1e-12)
return features
2. Price Features (4)¶
Same-day relative prices, normalized as ratios to the close price:
| Factor | Formula | Meaning |
|---|---|---|
| OPEN0 | $open/$close |
Open price relative to close |
| HIGH0 | $high/$close |
High price relative to close |
| LOW0 | $low/$close |
Low price relative to close |
| VWAP0 | $vwap/$close |
VWAP relative to close |
3. Rolling-Window Technical Indicators (145)¶
Rolling-window configuration¶
Five time windows are used by default: [5, 10, 20, 30, 60] days
The 29 technical indicators¶
Group A: Price trend & momentum (6 × 5 windows = 30)¶
| Indicator | Formula | Meaning | Generated factors |
|---|---|---|---|
| ROC | Ref($close, d)/$close |
Rate of Change | ROC5, ROC10, ROC20, ROC30, ROC60 |
| MA | Mean($close, d)/$close |
Simple moving average | MA5, MA10, MA20, MA30, MA60 |
| STD | Std($close, d)/$close |
Price standard deviation (volatility) | STD5, STD10, STD20, STD30, STD60 |
| BETA | Slope($close, d)/$close |
Price trend slope | BETA5, BETA10, BETA20, BETA30, BETA60 |
| RSQR | Rsquare($close, d) |
Linear-regression R² (trend strength) | RSQR5, RSQR10, RSQR20, RSQR30, RSQR60 |
| RESI | Resi($close, d)/$close |
Linear-regression residual | RESI5, RESI10, RESI20, RESI30, RESI60 |
Group B: Price position indicators (6 × 5 windows = 30)¶
| Indicator | Formula | Meaning | Generated factors |
|---|---|---|---|
| MAX | Max($high, d)/$close |
Highest price | MAX5, MAX10, MAX20, MAX30, MAX60 |
| MIN | Min($low, d)/$close |
Lowest price | MIN5, MIN10, MIN20, MIN30, MIN60 |
| QTLU | Quantile($close, d, 0.8)/$close |
80th percentile | QTLU5, QTLU10, QTLU20, QTLU30, QTLU60 |
| QTLD | Quantile($close, d, 0.2)/$close |
20th percentile | QTLD5, QTLD10, QTLD20, QTLD30, QTLD60 |
| RANK | Rank($close, d) |
Price rank percentile | RANK5, RANK10, RANK20, RANK30, RANK60 |
| RSV | ($close-Min($low, d))/(Max($high, d)-Min($low, d)+1e-12) |
Raw stochastic value | RSV5, RSV10, RSV20, RSV30, RSV60 |
Group C: Time-series position (3 × 5 windows = 15)¶
| Indicator | Formula | Meaning (Aroon indicator family) |
|---|---|---|
| IMAX | IdxMax($high, d)/d |
Time position of the highest price |
| IMIN | IdxMin($low, d)/d |
Time position of the lowest price |
| IMXD | (IdxMax($high, d)-IdxMin($low, d))/d |
Time gap between high and low points |
Group D: Price-volume association (2 × 5 windows = 10)¶
| Indicator | Formula | Meaning |
|---|---|---|
| CORR | Corr($close, Log($volume+1), d) |
Price-volume correlation |
| CORD | Corr($close/Ref($close,1), Log($volume/Ref($volume,1)+1), d) |
Correlation of price change vs. volume change |
Group E: Up/down statistics (3 × 5 windows = 15)¶
| Indicator | Formula | Meaning |
|---|---|---|
| CNTP | Mean($close>Ref($close, 1), d) |
Fraction of up days |
| CNTN | Mean($close<Ref($close, 1), d) |
Fraction of down days |
| CNTD | CNTP - CNTN |
Difference of up/down day fractions |
Group F: RSI-style indicators (3 × 5 windows = 15)¶
| Indicator | Formula | Meaning |
|---|---|---|
| SUMP | Sum(Greater($close-Ref($close, 1), 0), d)/(Sum(Abs($close-Ref($close, 1)), d)+1e-12) |
Share of total gains |
| SUMN | Sum(Greater(Ref($close, 1)-$close, 0), d)/(Sum(Abs($close-Ref($close, 1)), d)+1e-12) |
Share of total losses |
| SUMD | SUMP - SUMN |
Gain-minus-loss ratio |
Group G: Volume technical indicators (6 × 5 windows = 30)¶
| Indicator | Formula | Meaning |
|---|---|---|
| VMA | Mean($volume, d)/($volume+1e-12) |
Volume moving average |
| VSTD | Std($volume, d)/($volume+1e-12) |
Volume standard deviation |
| WVMA | Std(Abs($close/Ref($close, 1)-1)*$volume, d)/(Mean(Abs($close/Ref($close, 1)-1)*$volume, d)+1e-12) |
Volume-weighted volatility |
| VSUMP | Sum(Greater($volume-Ref($volume, 1), 0), d)/(Sum(Abs($volume-Ref($volume, 1)), d)+1e-12) |
Share of volume increases |
| VSUMN | Sum(Greater(Ref($volume, 1)-$volume, 0), d)/(Sum(Abs($volume-Ref($volume, 1)), d)+1e-12) |
Share of volume decreases |
| VSUMD | VSUMP - VSUMN |
Volume change difference ratio |
Factor count check¶
Candlestick features: 9
Price features: 4
Rolling indicators: 29 × 5 windows = 145
Total: 9 + 4 + 145 = 158 factors
Alpha360 in Depth¶
Design Philosophy¶
The core ideas behind Alpha360: - Preserve raw information: provide the full OHLCV series of the past 60 days - Uniform normalization: normalize by the current price / volume - Fit deep learning: the complete time series suits CNN/RNN/Transformer models
Factor Composition¶
Alpha360 contains 6 series types, each with 60 time steps, for a total of 360:
| Series type | Factor range | Count | Normalization |
|---|---|---|---|
| Close series | CLOSE59 ~ CLOSE0 | 60 | divide by current close |
| Open series | OPEN59 ~ OPEN0 | 60 | divide by current close |
| High series | HIGH59 ~ HIGH0 | 60 | divide by current close |
| Low series | LOW59 ~ LOW0 | 60 | divide by current close |
| VWAP series | VWAP59 ~ VWAP0 | 60 | divide by current close |
| Volume series | VOLUME59 ~ VOLUME0 | 60 | divide by current volume |
Detailed Formulas¶
1. Close series (60)¶
# CLOSE series: from 59 days ago to now
CLOSE59 = Ref($close, 59) / $close # close 59 days ago / current close
CLOSE58 = Ref($close, 58) / $close # close 58 days ago / current close
...
CLOSE1 = Ref($close, 1) / $close # yesterday's close / current close
CLOSE0 = $close / $close = 1.0 # current close (always 1 after normalization)
2. Open series (60)¶
OPEN59 = Ref($open, 59) / $close
OPEN58 = Ref($open, 58) / $close
...
OPEN0 = $open / $close
3. High series (60)¶
HIGH59 = Ref($high, 59) / $close
HIGH58 = Ref($high, 58) / $close
...
HIGH0 = $high / $close
4. Low series (60)¶
LOW59 = Ref($low, 59) / $close
LOW58 = Ref($low, 58) / $close
...
LOW0 = $low / $close
5. VWAP series (60)¶
VWAP59 = Ref($vwap, 59) / $close
VWAP58 = Ref($vwap, 58) / $close
...
VWAP0 = $vwap / $close
6. Volume series (60)¶
# Note: add 1e-12 to the denominator when normalizing volume to avoid division by zero
VOLUME59 = Ref($volume, 59) / ($volume + 1e-12)
VOLUME58 = Ref($volume, 58) / ($volume + 1e-12)
...
VOLUME0 = $volume / ($volume + 1e-12) = 1.0
Data Shape¶
For a single stock on a given day, the Alpha360 features look like:
# Feature matrix shape: (6, 60)
[
[CLOSE59, CLOSE58, ..., CLOSE1, CLOSE0], # 60
[OPEN59, OPEN58, ..., OPEN1, OPEN0], # 60
[HIGH59, HIGH58, ..., HIGH1, HIGH0], # 60
[LOW59, LOW58, ..., LOW1, LOW0], # 60
[VWAP59, VWAP58, ..., VWAP1, VWAP0], # 60
[VOLUME59, VOLUME58, ..., VOLUME1, VOLUME0] # 60
]
# Flattened: a 360-dimensional vector
Data Preparation¶
Method 1: Use Official Qlib Data¶
Download Chinese market data¶
# Daily data
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn
# Minute bars
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_1min --region cn --interval 1min
Download US market data¶
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/us_data --region us
Initialize Qlib¶
import qlib
from qlib.constant import REG_CN, REG_US
# Chinese market
qlib.init(provider_uri='~/.qlib/qlib_data/cn_data', region=REG_CN)
# US market
qlib.init(provider_uri='~/.qlib/qlib_data/us_data', region=REG_US)
Method 2: Use Your Own Data¶
Format requirements¶
CSV format (recommended)¶
symbol,date,open,high,low,close,volume,vwap
SH600000,2024-01-01,10.5,10.8,10.3,10.6,1000000,10.55
SH600000,2024-01-02,10.6,10.9,10.5,10.8,1200000,10.75
SH600004,2024-01-01,13.2,13.5,13.1,13.3,800000,13.25
Key requirements:
- Required columns: open, high, low, close, volume
- Recommended column: vwap (compute it if missing)
- Optional columns: symbol (stock code), date
- Data must be sorted by time in ascending order
Parquet format¶
import pandas as pd
df = pd.read_parquet('stock_data.parquet')
required_cols = ['date', 'symbol', 'open', 'high', 'low', 'close', 'volume']
assert all(col in df.columns for col in required_cols)
Convert to Qlib format¶
# Convert CSV data
python scripts/dump_bin.py dump_all \
--data_path ~/.qlib/my_csv_data \
--qlib_dir ~/.qlib/qlib_data/custom \
--include_fields open,close,high,low,volume,vwap \
--symbol_field_name symbol \
--date_field_name date \
--file_suffix .csv
# Convert Parquet data
python scripts/dump_bin.py dump_all \
--data_path ~/.qlib/my_parquet_data \
--qlib_dir ~/.qlib/qlib_data/custom \
--include_fields open,close,high,low,volume,vwap \
--file_suffix .parquet
Computing VWAP (if missing)¶
import pandas as pd
def calculate_vwap(df):
"""Compute VWAP (volume-weighted average price)."""
# Option 1: simple average (most common)
df['vwap'] = (df['high'] + df['low'] + df['close']) / 3
# Option 2: include the open price
df['vwap'] = (df['high'] + df['low'] + df['close'] + df['open']) / 4
# Option 3: with intraday bars (most accurate)
# vwap = sum(price * volume) / sum(volume)
return df
Method 3: Use a DataFrame Directly¶
If your data is already a pandas DataFrame, you can use it directly:
import pandas as pd
from qlib.data.dataset.handler import DataHandlerLP
from qlib.data.dataset.loader import StaticDataLoader
df = pd.read_csv('your_data.csv', parse_dates=['date'])
df = df.set_index(['date', 'symbol'])
loader = StaticDataLoader(config=df)
# Or use DataHandlerLP.from_df
from qlib.data.dataset.handler import DataHandlerLP
dh = DataHandlerLP.from_df(df)
Construction Methods¶
Method 1: DataLoader Expressions (most flexible)¶
This method gives you the raw expressions of all factors, which you can then compute as needed:
import qlib
from qlib.data import D
from qlib.contrib.data.loader import Alpha158DL, Alpha360DL
qlib.init(provider_uri='~/.qlib/qlib_data/cn_data', region='cn')
# ========== Alpha158 ==========
fields_158, names_158 = Alpha158DL.get_feature_config()
print(f"Alpha158 factor count: {len(names_158)}") # 158
print(f"First 10 factor names: {names_158[:10]}")
print(f"First 3 expressions: {fields_158[:3]}")
# Compute factors with the Qlib expression engine
factors_158 = D.features(
instruments=['SH600000', 'SH600004'],
fields=fields_158,
start_time='2024-01-01',
end_time='2024-12-31',
freq='day'
)
factors_158.columns = names_158
print(factors_158.head())
# ========== Alpha360 ==========
fields_360, names_360 = Alpha360DL.get_feature_config()
print(f"Alpha360 factor count: {len(names_360)}") # 360
factors_360 = D.features(
instruments=['SH600000'],
fields=fields_360,
start_time='2024-01-01',
end_time='2024-12-31',
freq='day'
)
factors_360.columns = names_360
print(factors_360.head())
Method 2: Handlers (simplest; recommended for production)¶
A Handler wraps the whole pipeline — data loading, factor computation, and preprocessing:
import qlib
from qlib.contrib.data.handler import Alpha158, Alpha360
from qlib.data.dataset import DatasetH
qlib.init(provider_uri='~/.qlib/qlib_data/cn_data', region='cn')
# ========== Alpha158 Handler ==========
handler_158 = Alpha158(
instruments='csi300', # universe: 'csi300', 'csi500', or a custom list
start_time='2020-01-01',
end_time='2024-12-31',
freq='day',
infer_processors=[ # processing at inference time
{"class": "ProcessInf"}, # handle infinities
{"class": "ZScoreNorm"}, # z-score standardization
{"class": "Fillna"} # fill NaNs
],
learn_processors=[ # extra processing at training time
{"class": "DropnaLabel"}, # drop samples with NaN labels
{"class": "CSZScoreNorm", "kwargs": {"fields_group": "label"}} # label standardization
],
fit_start_time='2020-01-01',
fit_end_time='2022-12-31'
)
dataset_158 = DatasetH(
handler=handler_158,
segments={
'train': ('2020-01-01', '2022-12-31'),
'valid': ('2023-01-01', '2023-12-31'),
'test': ('2024-01-01', '2024-12-31')
}
)
train_data = dataset_158.prepare('train')
print(f"Training data shape: {train_data.shape}") # (samples, 159) = 158 features + 1 label
feature_cols = [col for col in train_data.columns if 'LABEL' not in str(col)]
label_cols = [col for col in train_data.columns if 'LABEL' in str(col)]
X_train = train_data[feature_cols]
y_train = train_data[label_cols]
print(f"Feature count: {len(feature_cols)}") # 158
print(f"Label count: {len(label_cols)}") # 1
# ========== Alpha360 Handler ==========
handler_360 = Alpha360(
instruments='csi300',
start_time='2020-01-01',
end_time='2024-12-31',
freq='day'
)
dataset_360 = DatasetH(
handler=handler_360,
segments={'train': ('2020-01-01', '2022-12-31')}
)
train_data_360 = dataset_360.prepare('train')
print(f"Alpha360 training data shape: {train_data_360.shape}") # (samples, 361)
Method 3: Custom Handler Configuration¶
Subclass the Handler to customize your factor configuration:
from qlib.contrib.data.handler import Alpha158
from qlib.contrib.data.loader import Alpha158DL
class MyCustomAlpha(Alpha158):
"""A custom Alpha factor set."""
def get_feature_config(self):
conf = {
# Candlestick features: 9
"kbar": {},
# Price features: custom windows and fields
"price": {
"windows": [0, 1, 2, 3, 4],
"feature": ["OPEN", "HIGH", "LOW", "CLOSE", "VWAP"]
},
# 5 fields × 5 windows = 25 features
# Volume features
"volume": {
"windows": [0, 1, 2]
},
# 3 features
# Rolling features: custom windows and indicators
"rolling": {
"windows": [5, 10, 20],
"include": ['ROC', 'MA', 'STD', 'MAX', 'MIN']
}
# 5 indicators × 3 windows = 15 features
}
return Alpha158DL.get_feature_config(conf)
def get_label_config(self):
# Predict the 5-day return
return ["Ref($close, -5)/$close - 1"], ["LABEL_5D"]
custom_handler = MyCustomAlpha(
instruments=['SH600000', 'SH600004'],
start_time='2024-01-01',
end_time='2024-12-31'
)
# Total: 9 (kbar) + 25 (price) + 3 (volume) + 15 (rolling) = 52
print(f"Custom factor count: {len(custom_handler.fetch(col_set='feature').columns)}")
Method 4: Manual Computation (fully self-contained)¶
Implement the factors yourself without any Qlib dependency:
import pandas as pd
import numpy as np
def calculate_alpha158_manual(df):
"""
Manually compute Alpha158 factors.
Args:
df: DataFrame with columns ['open', 'high', 'low', 'close', 'volume', 'vwap']
Returns:
DataFrame with 158 factors
"""
features = pd.DataFrame(index=df.index)
# ========== 1. Candlestick features (9) ==========
features['KMID'] = (df['close'] - df['open']) / df['open']
features['KLEN'] = (df['high'] - df['low']) / df['open']
features['KMID2'] = (df['close'] - df['open']) / (df['high'] - df['low'] + 1e-12)
features['KUP'] = (df['high'] - df[['open', 'close']].max(axis=1)) / df['open']
features['KUP2'] = (df['high'] - df[['open', 'close']].max(axis=1)) / (df['high'] - df['low'] + 1e-12)
features['KLOW'] = (df[['open', 'close']].min(axis=1) - df['low']) / df['open']
features['KLOW2'] = (df[['open', 'close']].min(axis=1) - df['low']) / (df['high'] - df['low'] + 1e-12)
features['KSFT'] = (2*df['close'] - df['high'] - df['low']) / df['open']
features['KSFT2'] = (2*df['close'] - df['high'] - df['low']) / (df['high'] - df['low'] + 1e-12)
# ========== 2. Price features (4) ==========
features['OPEN0'] = df['open'] / df['close']
features['HIGH0'] = df['high'] / df['close']
features['LOW0'] = df['low'] / df['close']
features['VWAP0'] = df['vwap'] / df['close']
# ========== 3. Rolling features (145) ==========
windows = [5, 10, 20, 30, 60]
for d in windows:
# ROC: rate of change
features[f'ROC{d}'] = df['close'].shift(d) / df['close']
# MA: moving average
features[f'MA{d}'] = df['close'].rolling(d).mean() / df['close']
# STD: standard deviation
features[f'STD{d}'] = df['close'].rolling(d).std() / df['close']
# BETA: price slope
def slope(series):
x = np.arange(len(series))
if len(series) < 2:
return np.nan
return np.polyfit(x, series, 1)[0]
features[f'BETA{d}'] = df['close'].rolling(d).apply(slope, raw=True) / df['close']
# RSQR: R²
def rsquare(series):
if len(series) < 2:
return np.nan
x = np.arange(len(series))
coeffs = np.polyfit(x, series, 1)
yhat = np.polyval(coeffs, x)
ybar = np.mean(series)
ssreg = np.sum((yhat - ybar) ** 2)
sstot = np.sum((series - ybar) ** 2)
return ssreg / (sstot + 1e-12)
features[f'RSQR{d}'] = df['close'].rolling(d).apply(rsquare, raw=True)
# MAX/MIN: highest/lowest price
features[f'MAX{d}'] = df['high'].rolling(d).max() / df['close']
features[f'MIN{d}'] = df['low'].rolling(d).min() / df['close']
# QTLU/QTLD: quantiles
features[f'QTLU{d}'] = df['close'].rolling(d).quantile(0.8) / df['close']
features[f'QTLD{d}'] = df['close'].rolling(d).quantile(0.2) / df['close']
# RANK: percentile rank
features[f'RANK{d}'] = df['close'].rolling(d).apply(
lambda x: pd.Series(x).rank(pct=True).iloc[-1] if len(x) > 0 else np.nan,
raw=True
)
# RSV: raw stochastic value
rsv_min = df['low'].rolling(d).min()
rsv_max = df['high'].rolling(d).max()
features[f'RSV{d}'] = (df['close'] - rsv_min) / (rsv_max - rsv_min + 1e-12)
# CORR: price-volume correlation
features[f'CORR{d}'] = df['close'].rolling(d).corr(np.log(df['volume'] + 1))
# VMA: volume moving average
features[f'VMA{d}'] = df['volume'].rolling(d).mean() / (df['volume'] + 1e-12)
# VSTD: volume standard deviation
features[f'VSTD{d}'] = df['volume'].rolling(d).std() / (df['volume'] + 1e-12)
return features
df = pd.read_csv('stock_data.csv', parse_dates=['date'])
df = df.sort_values('date')
alpha158_features = calculate_alpha158_manual(df)
print(f"Computed factor count: {alpha158_features.shape[1]}")
print(alpha158_features.head())
Source-Code Walkthrough¶
File layout¶
qlib/contrib/data/
├── handler.py # Alpha158 and Alpha360 Handler classes
├── loader.py # Alpha158DL and Alpha360DL DataLoader classes
├── processor.py # data preprocessing classes
└── dataset.py # dataset management classes
Core loader.py code¶
Alpha158DL.get_feature_config()¶
Location: qlib/contrib/data/loader.py:72-310
@staticmethod
def get_feature_config(config={
"kbar": {},
"price": {"windows": [0], "feature": ["OPEN", "HIGH", "LOW", "VWAP"]},
"rolling": {}
}):
"""
Generate Alpha158 factor expressions from a configuration.
Args:
config: dict, the factor configuration
- kbar: candlestick features (9 fixed factors)
- price: price feature config
- windows: list of time windows
- feature: list of price fields
- volume: volume feature config
- windows: list of time windows
- rolling: rolling feature config
- windows: window sizes, default [5,10,20,30,60]
- include: indicators to include, None means all
- exclude: indicators to exclude
Returns:
(fields, names): tuple
- fields: list of factor expressions
- names: list of factor names
"""
fields = []
names = []
# Candlestick features (9)
if "kbar" in config:
fields += [
"($close-$open)/$open",
"($high-$low)/$open",
# ... (9 expressions in total)
]
names += ["KMID", "KLEN", "KMID2", ...]
# Price features
if "price" in config:
windows = config["price"].get("windows", range(5))
feature = config["price"].get("feature", ["OPEN", "HIGH", "LOW", "CLOSE", "VWAP"])
for field in feature:
field = field.lower()
fields += [
"Ref($%s, %d)/$close" % (field, d) if d != 0 else "$%s/$close" % field
for d in windows
]
names += [field.upper() + str(d) for d in windows]
# Rolling features
if "rolling" in config:
windows = config["rolling"].get("windows", [5, 10, 20, 30, 60])
include = config["rolling"].get("include", None)
exclude = config["rolling"].get("exclude", [])
def use(x):
return x not in exclude and (include is None or x in include)
# 29 indicators including ROC, MA, STD, etc.
if use("ROC"):
fields += ["Ref($close, %d)/$close" % d for d in windows]
names += ["ROC%d" % d for d in windows]
if use("MA"):
fields += ["Mean($close, %d)/$close" % d for d in windows]
names += ["MA%d" % d for d in windows]
# ... the other 27 indicators
return fields, names
Alpha360DL.get_feature_config()¶
Location: qlib/contrib/data/loader.py:16-58
@staticmethod
def get_feature_config():
"""
Generate Alpha360 factor expressions.
Alpha360 design:
- Provide raw price data for the past 60 days
- All prices normalized by the current close
- All volumes normalized by the current volume
- CLOSE0 and VOLUME0 are always 1 after normalization
Returns:
(fields, names): tuple with expressions and names for 360 factors
"""
fields = []
names = []
# 1. CLOSE series (60): CLOSE59 -> CLOSE0
for i in range(59, 0, -1):
fields += ["Ref($close, %d)/$close" % i]
names += ["CLOSE%d" % i]
fields += ["$close/$close"] # CLOSE0 = 1
names += ["CLOSE0"]
# 2. OPEN series (60): OPEN59 -> OPEN0
for i in range(59, 0, -1):
fields += ["Ref($open, %d)/$close" % i]
names += ["OPEN%d" % i]
fields += ["$open/$close"]
names += ["OPEN0"]
# 3. HIGH series (60): HIGH59 -> HIGH0
for i in range(59, 0, -1):
fields += ["Ref($high, %d)/$close" % i]
names += ["HIGH%d" % i]
fields += ["$high/$close"]
names += ["HIGH0"]
# 4. LOW series (60): LOW59 -> LOW0
for i in range(59, 0, -1):
fields += ["Ref($low, %d)/$close" % i]
names += ["LOW%d" % i]
fields += ["$low/$close"]
names += ["LOW0"]
# 5. VWAP series (60): VWAP59 -> VWAP0
for i in range(59, 0, -1):
fields += ["Ref($vwap, %d)/$close" % i]
names += ["VWAP%d" % i]
fields += ["$vwap/$close"]
names += ["VWAP0"]
# 6. VOLUME series (60): VOLUME59 -> VOLUME0
# Note: +1e-12 to avoid division by zero
for i in range(59, 0, -1):
fields += ["Ref($volume, %d)/($volume+1e-12)" % i]
names += ["VOLUME%d" % i]
fields += ["$volume/($volume+1e-12)"] # VOLUME0 = 1
names += ["VOLUME0"]
return fields, names
Core handler.py code¶
The Alpha158 class¶
Location: qlib/contrib/data/handler.py:98-153
class Alpha158(DataHandlerLP):
"""
Alpha158 data handler.
Inherits from DataHandlerLP and provides:
- Data loading (via Alpha158DL)
- Data preprocessing (via Processors)
- Feature/label separation
"""
def __init__(
self,
instruments="csi500", # universe
start_time=None, # data start time
end_time=None, # data end time
freq="day", # frequency: day/1min/5min etc.
infer_processors=[], # inference-time processors (none by default)
learn_processors=_DEFAULT_LEARN_PROCESSORS, # training-time processors
fit_start_time=None, # processor fit start time
fit_end_time=None, # processor fit end time
process_type=DataHandlerLP.PTYPE_A, # process type: append
filter_pipe=None, # filters
inst_processors=None, # instrument-level processors
**kwargs
):
data_loader = {
"class": "QlibDataLoader",
"kwargs": {
"config": {
"feature": self.get_feature_config(), # 158 features
"label": kwargs.pop("label", self.get_label_config()), # 1 label
},
"filter_pipe": filter_pipe,
"freq": freq,
"inst_processors": inst_processors,
},
}
super().__init__(
instruments=instruments,
start_time=start_time,
end_time=end_time,
data_loader=data_loader,
infer_processors=infer_processors,
learn_processors=learn_processors,
process_type=process_type,
**kwargs
)
def get_feature_config(self):
conf = {
"kbar": {}, # candlestick features
"price": { # price features
"windows": [0],
"feature": ["OPEN", "HIGH", "LOW", "VWAP"],
},
"rolling": {} # default rolling config
}
return Alpha158DL.get_feature_config(conf)
def get_label_config(self):
# Predict the T+1 to T+2 return
return ["Ref($close, -2)/Ref($close, -1) - 1"], ["LABEL0"]
The Alpha360 class¶
Location: qlib/contrib/data/handler.py:48-91
class Alpha360(DataHandlerLP):
"""
Alpha360 data handler.
Compared with Alpha158:
- Loads 360 series features via Alpha360DL
- Has more default infer_processors (ProcessInf, ZScoreNorm, Fillna)
"""
def __init__(
self,
instruments="csi500",
start_time=None,
end_time=None,
freq="day",
infer_processors=_DEFAULT_INFER_PROCESSORS, # 3 processors by default
learn_processors=_DEFAULT_LEARN_PROCESSORS,
fit_start_time=None,
fit_end_time=None,
filter_pipe=None,
inst_processors=None,
**kwargs
):
data_loader = {
"class": "QlibDataLoader",
"kwargs": {
"config": {
"feature": Alpha360DL.get_feature_config(), # 360 features
"label": kwargs.pop("label", self.get_label_config()),
},
"filter_pipe": filter_pipe,
"freq": freq,
"inst_processors": inst_processors,
},
}
super().__init__(
instruments=instruments,
start_time=start_time,
end_time=end_time,
data_loader=data_loader,
learn_processors=learn_processors,
infer_processors=infer_processors,
**kwargs
)
def get_label_config(self):
"""Label config (same as Alpha158)."""
return ["Ref($close, -2)/Ref($close, -1) - 1"], ["LABEL0"]
Default processor configuration¶
Location: qlib/contrib/data/handler.py:37-45
# Default Alpha360 inference processors
_DEFAULT_INFER_PROCESSORS = [
{"class": "ProcessInf", "kwargs": {}}, # handle infinities
{"class": "ZScoreNorm", "kwargs": {}}, # z-score standardization
{"class": "Fillna", "kwargs": {}}, # fill NaNs
]
# Default Alpha158/360 learn processors
_DEFAULT_LEARN_PROCESSORS = [
{"class": "DropnaLabel"}, # drop samples with NaN labels
{"class": "CSZScoreNorm", "kwargs": {"fields_group": "label"}}, # cross-sectional label standardization
]
Practical Examples¶
Example 1: Full ML Training Pipeline (LightGBM + Alpha158)¶
import qlib
from qlib.contrib.data.handler import Alpha158
from qlib.data.dataset import DatasetH
import lightgbm as lgb
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np
import pandas as pd
# 1. Initialize Qlib
qlib.init(provider_uri='~/.qlib/qlib_data/cn_data', region='cn')
# 2. Create the Alpha158 handler
handler = Alpha158(
instruments='csi300',
start_time='2018-01-01',
end_time='2023-12-31',
freq='day',
infer_processors=[],
fit_start_time='2018-01-01',
fit_end_time='2020-12-31'
)
# 3. Create the dataset
dataset = DatasetH(
handler=handler,
segments={
'train': ('2018-01-01', '2020-12-31'),
'valid': ('2021-01-01', '2021-12-31'),
'test': ('2022-01-01', '2023-12-31')
}
)
# 4. Prepare the data
train_data = dataset.prepare('train')
valid_data = dataset.prepare('valid')
test_data = dataset.prepare('test')
print(f"Train shape: {train_data.shape}")
print(f"Valid shape: {valid_data.shape}")
print(f"Test shape: {test_data.shape}")
# 5. Split features and labels
def split_features_labels(data):
feature_cols = [col for col in data.columns if 'LABEL' not in str(col)]
label_cols = [col for col in data.columns if 'LABEL' in str(col)]
return data[feature_cols], data[label_cols].values.ravel()
X_train, y_train = split_features_labels(train_data)
X_valid, y_valid = split_features_labels(valid_data)
X_test, y_test = split_features_labels(test_data)
# 6. Handle missing values
X_train = X_train.fillna(X_train.mean()).fillna(0)
X_valid = X_valid.fillna(X_train.mean()).fillna(0)
X_test = X_test.fillna(X_train.mean()).fillna(0)
# 7. Train LightGBM
lgb_params = {
'objective': 'regression',
'metric': 'mse',
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'verbose': -1
}
train_set = lgb.Dataset(X_train, y_train)
valid_set = lgb.Dataset(X_valid, y_valid, reference=train_set)
model = lgb.train(
lgb_params,
train_set,
num_boost_round=1000,
valid_sets=[train_set, valid_set],
valid_names=['train', 'valid'],
callbacks=[
lgb.early_stopping(stopping_rounds=50),
lgb.log_evaluation(period=100)
]
)
# 8. Predict and evaluate
y_pred_train = model.predict(X_train)
y_pred_valid = model.predict(X_valid)
y_pred_test = model.predict(X_test)
print("\n=== Model Evaluation ===")
print(f"Train - MSE: {mean_squared_error(y_train, y_pred_train):.6f}, R²: {r2_score(y_train, y_pred_train):.4f}")
print(f"Valid - MSE: {mean_squared_error(y_valid, y_pred_valid):.6f}, R²: {r2_score(y_valid, y_pred_valid):.4f}")
print(f"Test - MSE: {mean_squared_error(y_test, y_pred_test):.6f}, R²: {r2_score(y_test, y_pred_test):.4f}")
# 9. Feature importance
feature_importance = pd.DataFrame({
'feature': X_train.columns,
'importance': model.feature_importance(importance_type='gain')
}).sort_values('importance', ascending=False)
print("\n=== Top 20 Features ===")
print(feature_importance.head(20))
Example 2: Deep-Learning Pipeline (LSTM + Alpha360)¶
import qlib
from qlib.contrib.data.handler import Alpha360
from qlib.data.dataset import DatasetH
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score
# 1. Initialize
qlib.init(provider_uri='~/.qlib/qlib_data/cn_data', region='cn')
# 2. Create the Alpha360 handler
handler = Alpha360(
instruments='csi300',
start_time='2018-01-01',
end_time='2023-12-31',
freq='day',
fit_start_time='2018-01-01',
fit_end_time='2020-12-31'
)
# 3. Create the dataset
dataset = DatasetH(
handler=handler,
segments={
'train': ('2018-01-01', '2020-12-31'),
'valid': ('2021-01-01', '2021-12-31'),
'test': ('2022-01-01', '2023-12-31')
}
)
# 4. Prepare data
train_data = dataset.prepare('train')
valid_data = dataset.prepare('valid')
test_data = dataset.prepare('test')
# 5. Preprocess
def prepare_lstm_data(data):
"""Reshape Alpha360 data into LSTM input format."""
feature_cols = [col for col in data.columns if 'LABEL' not in str(col)]
label_cols = [col for col in data.columns if 'LABEL' in str(col)]
X = data[feature_cols].values # (samples, 360)
y = data[label_cols].values.ravel() # (samples,)
# Reshape to (samples, 60, 6) - 60 time steps × 6 features (OHLCV + VWAP)
X_reshaped = X.reshape(-1, 6, 60).transpose(0, 2, 1)
return X_reshaped, y
X_train, y_train = prepare_lstm_data(train_data)
X_valid, y_valid = prepare_lstm_data(valid_data)
X_test, y_test = prepare_lstm_data(test_data)
print(f"LSTM input shapes - train: {X_train.shape}, valid: {X_valid.shape}, test: {X_test.shape}")
# 6. PyTorch data loaders
train_dataset = TensorDataset(torch.FloatTensor(X_train), torch.FloatTensor(y_train))
valid_dataset = TensorDataset(torch.FloatTensor(X_valid), torch.FloatTensor(y_valid))
test_dataset = TensorDataset(torch.FloatTensor(X_test), torch.FloatTensor(y_test))
train_loader = DataLoader(train_dataset, batch_size=256, shuffle=True)
valid_loader = DataLoader(valid_dataset, batch_size=256, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=256, shuffle=False)
# 7. Define the LSTM model
class StockLSTM(nn.Module):
def __init__(self, input_size=6, hidden_size=64, num_layers=2, dropout=0.2):
super(StockLSTM, self).__init__()
self.lstm = nn.LSTM(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
dropout=dropout if num_layers > 1 else 0,
batch_first=True
)
self.fc = nn.Sequential(
nn.Linear(hidden_size, 32),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(32, 1)
)
def forward(self, x):
# x: (batch, seq_len=60, features=6)
lstm_out, (h_n, c_n) = self.lstm(x)
last_output = lstm_out[:, -1, :] # (batch, hidden_size)
pred = self.fc(last_output)
return pred.squeeze()
# 8. Train
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = StockLSTM().to(device)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
num_epochs = 50
best_valid_loss = float('inf')
for epoch in range(num_epochs):
model.train()
train_loss = 0
for X_batch, y_batch in train_loader:
X_batch, y_batch = X_batch.to(device), y_batch.to(device)
optimizer.zero_grad()
outputs = model(X_batch)
loss = criterion(outputs, y_batch)
loss.backward()
optimizer.step()
train_loss += loss.item()
model.eval()
valid_loss = 0
with torch.no_grad():
for X_batch, y_batch in valid_loader:
X_batch, y_batch = X_batch.to(device), y_batch.to(device)
outputs = model(X_batch)
loss = criterion(outputs, y_batch)
valid_loss += loss.item()
train_loss /= len(train_loader)
valid_loss /= len(valid_loader)
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model.state_dict(), 'best_lstm_model.pth')
if (epoch + 1) % 10 == 0:
print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.6f}, Valid Loss: {valid_loss:.6f}')
# 9. Test
model.load_state_dict(torch.load('best_lstm_model.pth'))
model.eval()
test_preds = []
test_targets = []
with torch.no_grad():
for X_batch, y_batch in test_loader:
X_batch = X_batch.to(device)
outputs = model(X_batch)
test_preds.extend(outputs.cpu().numpy())
test_targets.extend(y_batch.numpy())
test_preds = np.array(test_preds)
test_targets = np.array(test_targets)
test_mse = mean_squared_error(test_targets, test_preds)
test_r2 = r2_score(test_targets, test_preds)
print(f"\n=== Test Evaluation ===")
print(f"MSE: {test_mse:.6f}, R²: {test_r2:.4f}")
Example 3: Run a Workflow with qrun¶
Create my_alpha158_workflow.yaml:
qlib_init:
provider_uri: "~/.qlib/qlib_data/cn_data"
region: cn
market: &market csi300
data_handler_config: &data_handler_config
start_time: 2018-01-01
end_time: 2023-12-31
fit_start_time: 2018-01-01
fit_end_time: 2020-12-31
instruments: *market
infer_processors: []
learn_processors:
- class: DropnaLabel
- class: CSZScoreNorm
kwargs:
fields_group: label
task:
model:
class: LGBModel
module_path: qlib.contrib.model.gbdt
kwargs:
loss: mse
colsample_bytree: 0.8879
learning_rate: 0.0421
subsample: 0.8789
lambda_l1: 205.6999
lambda_l2: 580.9768
max_depth: 8
num_leaves: 210
num_threads: 20
dataset:
class: DatasetH
module_path: qlib.data.dataset
kwargs:
handler:
class: Alpha158
module_path: qlib.contrib.data.handler
kwargs: *data_handler_config
segments:
train: [2018-01-01, 2020-12-31]
valid: [2021-01-01, 2021-12-31]
test: [2022-01-01, 2023-12-31]
record:
- class: SignalRecord
module_path: qlib.workflow.record_temp
kwargs: {}
Run the workflow:
cd examples
qrun my_alpha158_workflow.yaml
Inspect the results:
import qlib
from qlib.workflow import R
qlib.init()
exp = R.get_exp(experiment_name="your_experiment_name")
recorder = exp.list_recorders()[0]
pred = recorder.load_object("pred.pkl")
print(pred.head())
metrics = recorder.list_metrics()
print(metrics)
Example 4: Batch Backtests over Multiple Stocks¶
import qlib
from qlib.contrib.data.handler import Alpha158
from qlib.data.dataset import DatasetH
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
import numpy as np
qlib.init(provider_uri='~/.qlib/qlib_data/cn_data', region='cn')
stocks = ['SH600000', 'SH600004', 'SH600005', 'SH600006', 'SH600007']
results = []
for stock in stocks:
print(f"\nProcessing: {stock}")
try:
handler = Alpha158(
instruments=[stock],
start_time='2020-01-01',
end_time='2023-12-31',
freq='day'
)
dataset = DatasetH(
handler=handler,
segments={
'train': ('2020-01-01', '2022-06-30'),
'test': ('2022-07-01', '2023-12-31')
}
)
train_data = dataset.prepare('train')
test_data = dataset.prepare('test')
feature_cols = [col for col in train_data.columns if 'LABEL' not in str(col)]
X_train = train_data[feature_cols].fillna(0)
y_train = train_data['LABEL0']
X_test = test_data[feature_cols].fillna(0)
y_test = test_data['LABEL0']
model = RandomForestRegressor(n_estimators=100, max_depth=10, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
direction_acc = np.mean((y_test > 0) == (y_pred > 0))
results.append({
'stock': stock,
'mse': mse,
'direction_accuracy': direction_acc,
'samples': len(y_test)
})
print(f" MSE: {mse:.6f}, Direction accuracy: {direction_acc:.4f}")
except Exception as e:
print(f" Error: {e}")
continue
results_df = pd.DataFrame(results)
print("\n=== Summary ===")
print(results_df)
print(f"\nMean MSE: {results_df['mse'].mean():.6f}")
print(f"Mean direction accuracy: {results_df['direction_accuracy'].mean():.4f}")
Performance Optimization¶
1. Data Caching¶
Qlib provides a multi-level cache to speed up data access:
import qlib
from qlib.config import C
qlib.init(
provider_uri='~/.qlib/qlib_data/cn_data',
region='cn',
expression_cache=True, # enable the expression cache
dataset_cache=True, # enable the dataset cache
mem_cache_size_limit=10 # in-memory cache limit (GB)
)
print(f"Expression cache path: {C.get_cache_dir()}")
2. Handler Caching¶
Persist a handler to disk after the first run and reuse it later:
from qlib.contrib.data.handler import Alpha158
handler = Alpha158(
instruments='csi300',
start_time='2018-01-01',
end_time='2023-12-31'
)
handler.setup_data(enable_cache=True)
handler.to_pickle('alpha158_handler.pkl', dump_all=True)
# Load later
from qlib.data.dataset.handler import DataHandlerLP
handler = DataHandlerLP.from_pickle('alpha158_handler.pkl')
3. Parallel Processing¶
Use multiprocessing to accelerate factor computation:
import qlib
from qlib.data import D
from qlib.contrib.data.loader import Alpha158DL
from joblib import Parallel, delayed
import pandas as pd
qlib.init()
stocks = ['SH600000', 'SH600004', 'SH600005', 'SH600006', 'SH600007']
fields, names = Alpha158DL.get_feature_config()
def compute_stock_factors(stock):
"""Compute factors for one stock."""
factors = D.features(
instruments=[stock],
fields=fields,
start_time='2024-01-01',
end_time='2024-12-31',
freq='day'
)
factors.columns = names
return factors
results = Parallel(n_jobs=4)(
delayed(compute_stock_factors)(stock)
for stock in stocks
)
all_factors = pd.concat(results)
print(all_factors.shape)
4. Optimizing for High-Frequency Data¶
For high-frequency data (e.g., 1-minute bars):
# Use smaller windows
handler = Alpha158(
instruments='csi300',
start_time='2024-01-01',
end_time='2024-01-31', # load only one month
freq='1min'
)
# Or reduce the factor count via a custom config
class Alpha158MinFreq(Alpha158):
def get_feature_config(self):
conf = {
"kbar": {},
"price": {"windows": [0], "feature": ["OPEN", "HIGH", "LOW", "CLOSE"]},
"rolling": {
"windows": [5, 10, 20], # shorter windows
"include": ['ROC', 'MA', 'STD'] # fewer indicators
}
}
from qlib.contrib.data.loader import Alpha158DL
return Alpha158DL.get_feature_config(conf)
5. Memory Optimization¶
# 1. Use drop_raw to reduce memory usage
handler = Alpha158(
instruments='csi300',
start_time='2018-01-01',
end_time='2023-12-31',
drop_raw=True # drop raw data after processing
)
# 2. Process large datasets in batches
def process_in_batches(instruments, batch_size=100):
for i in range(0, len(instruments), batch_size):
batch = instruments[i:i+batch_size]
handler = Alpha158(instruments=batch, ...)
yield handler.fetch()
# 3. Use more efficient dtypes
import pandas as pd
data = dataset.prepare('train')
data = data.astype('float32') # downcast to float32
FAQ¶
Q1: Alpha158 or Alpha360 — which one?¶
Answer: Choose based on your model type:
- Use Alpha158:
- Traditional ML models (LightGBM, XGBoost, RandomForest, linear regression)
- You need feature interpretability
- Limited compute resources
-
Training speed matters
-
Use Alpha360:
- Deep-learning models (LSTM, GRU, Transformer, CNN)
- You want the model to learn temporal patterns automatically
- You have ample compute resources
- You have lots of data (deep learning needs more)
Q2: Can I use my own data instead of the Qlib format?¶
Answer: Absolutely. Three ways:
-
Method 1: Convert to Qlib format (recommended)
python scripts/dump_bin.py dump_all --data_path your_csv_dir --qlib_dir output_dir -
Method 2: Use DataHandlerLP.from_df
from qlib.data.dataset.handler import DataHandlerLP handler = DataHandlerLP.from_df(your_dataframe) -
Method 3: Compute factors manually
# Pure pandas; see the "Method 4: Manual Computation" section above
Q3: How do I handle NaNs in the data?¶
Answer: Qlib provides several approaches:
# Method 1: let Processors handle it
handler = Alpha158(
...,
infer_processors=[
{"class": "ProcessInf"}, # handle infinities
{"class": "Fillna"} # fill NaNs with 0
]
)
# Method 2: handle it manually
data = dataset.prepare('train')
data = data.fillna(data.mean()) # fill with the mean
data = data.fillna(method='ffill') # forward fill
data = data.dropna() # drop rows containing NaNs
# Method 3: a more robust approach
def robust_fillna(X_train, X_test):
X_train_filled = X_train.fillna(X_train.mean()).fillna(0)
X_test_filled = X_test.fillna(X_train.mean()).fillna(0)
return X_train_filled, X_test_filled
Q4: How do I add custom factors?¶
Answer: Subclass Alpha158 or Alpha360 and override the config methods:
from qlib.contrib.data.handler import Alpha158
from qlib.contrib.data.loader import Alpha158DL
class MyCustomAlpha(Alpha158):
def get_feature_config(self):
# 1. Get the standard Alpha158 config
fields, names = Alpha158DL.get_feature_config()
# 2. Add custom factors
custom_fields = [
"$high/$low", # intraday amplitude
"Mean($volume, 5) / $volume", # 5-day volume ratio
"($close - $open) / ($high - $low + 1e-12)" # body ratio
]
custom_names = ['HIGH_LOW_RATIO', 'VOLUME_RATIO_5', 'BODY_RATIO']
# 3. Merge
fields.extend(custom_fields)
names.extend(custom_names)
return fields, names
handler = MyCustomAlpha(instruments='csi300', ...)
Q5: Do I need all 158 Alpha158 factors? Can I use a subset?¶
Answer: Yes, you can. Two ways:
# Option 1: customize the config (generate fewer up front)
class MyAlpha(Alpha158):
def get_feature_config(self):
conf = {
"kbar": {}, # keep candlestick features
"price": {"windows": [0], "feature": ["CLOSE"]},
"rolling": {
"windows": [5, 10, 20], # only 3 windows
"include": ['ROC', 'MA'] # only 2 indicators
}
}
from qlib.contrib.data.loader import Alpha158DL
return Alpha158DL.get_feature_config(conf)
# Option 2: filter after generation
handler = Alpha158(...)
data = dataset.prepare('train')
selected_features = ['KMID', 'ROC5', 'MA10', 'STD20', 'LABEL0']
data = data[selected_features]
Q6: How do I predict the 5-day return instead of the 1-day return?¶
Answer: Override get_label_config:
class Alpha158With5DayLabel(Alpha158):
def get_label_config(self):
# Predict the T+5 to T+6 return
return ["Ref($close, -6)/Ref($close, -5) - 1"], ["LABEL_5D"]
# Or predict the T to T+5 return
# return ["Ref($close, -5)/$close - 1"], ["LABEL_5D"]
Q7: How do I handle data gaps caused by trading suspensions?¶
Answer: The Qlib convention is to set all OHLCV fields to NaN during a suspension:
# Method 1: forward fill
handler = Alpha158(
...,
infer_processors=[
{"class": "Fillna", "kwargs": {"method": "ffill"}}
]
)
# Method 2: drop suspended samples
data = dataset.prepare('train')
data = data.dropna(subset=['LABEL0'])
# Method 3: use a dedicated filter
data_handler_config = {
...,
"filter_pipe": [
{
"class": "ExpressionDFilter",
"kwargs": {
"rule_expression": "$volume > 0", # filter out zero volume
"filter_start_time": "2020-01-01",
"filter_end_time": "2023-12-31"
}
}
]
}
Q8: How do I reshape the 360-dim Alpha360 data for an LSTM?¶
Answer: Alpha360 is 6 series × 60 time steps = 360 dims:
import numpy as np
X = data[feature_cols].values # (samples, 360)
# Reshape to (samples, 60, 6) - 60 time steps × 6 features (CLOSE/OPEN/HIGH/LOW/VWAP/VOLUME)
# Option 1: direct reshape
X_lstm = X.reshape(-1, 6, 60).transpose(0, 2, 1)
# Option 2: group by feature type
close_features = [f'CLOSE{i}' for i in range(59, -1, -1)]
open_features = [f'OPEN{i}' for i in range(59, -1, -1)]
# ... other features
X_close = data[close_features].values # (samples, 60)
X_open = data[open_features].values
# ... stack into (samples, 60, 6)
X_lstm = np.stack([X_close, X_open, X_high, X_low, X_vwap, X_volume], axis=2)
print(f"LSTM input shape: {X_lstm.shape}") # (samples, 60, 6)
Q9: Can I use Alpha158/360 on cryptocurrencies?¶
Answer: Qlib already supports crypto; see qlib/contrib/crypto/:
from qlib.contrib.crypto.handlers.alpha158_crypto import CryptoAlpha158
handler = CryptoAlpha158(
instruments=['BTCUSDT', 'ETHUSDT'],
start_time='2024-01-01',
end_time='2024-12-31',
freq='1h' # supports 1m, 5m, 15m, 1h, 1d, etc.
)
# Otherwise identical to the stock Alpha158
Q10: How do I inspect the actual computed value of a factor?¶
Answer: Compute it standalone with D.features:
import qlib
from qlib.data import D
qlib.init()
roc5 = D.features(
instruments=['SH600000'],
fields=['Ref($close, 5)/$close'],
start_time='2024-01-01',
end_time='2024-01-31',
freq='day'
)
print(roc5)
close = D.features(
instruments=['SH600000'],
fields=['$close'],
start_time='2024-01-01',
end_time='2024-01-31',
freq='day'
)
print(close)
# Manual verification
import pandas as pd
comparison = pd.DataFrame({
'close': close.values.ravel(),
'roc5': roc5.values.ravel()
})
comparison['close_5d_ago'] = comparison['close'].shift(5)
comparison['roc5_manual'] = comparison['close_5d_ago'] / comparison['close']
print(comparison)
References¶
Official documentation¶
- Qlib documentation - full API reference and tutorials
- Data Layer docs - data layer details
- Model docs - model training guide
- Workflow docs - workflow management
GitHub resources¶
- Qlib repository - source code and issues
- Qlib Benchmarks - benchmarks for 50+ models
- Qlib Examples - official example code
Academic paper¶
- Qlib: An AI-oriented Quantitative Investment Platform - the Qlib system paper
Technical indicator references¶
Source-code locations¶
- qlib/contrib/data/handler.py - Alpha158/360 Handler implementation
- qlib/contrib/data/loader.py - Alpha158DL/Alpha360DL implementation
- qlib/data/dataset/handler.py - DataHandlerLP base class
- qlib/data/dataset/processor.py - data processors
Summary¶
This guide covered the complete construction of Qlib's Alpha158 and Alpha360 factors:
Key takeaways¶
- Data requirements: only OHLCV base data is needed (VWAP recommended)
- Two factor sets:
- Alpha158: 158 engineered indicators for traditional ML
- Alpha360: 360 raw series for deep learning
- Four construction methods: DataLoader, Handler, custom Handler, manual computation
- Flexible extension: subclass Handlers to customize the factor config
- Performance: caching, parallelism, batching, and other strategies
Best practices¶
- ✅ Use the Handler method (simplest; recommended for production)
- ✅ Enable data caching for faster access
- ✅ Handle NaNs and suspension gaps properly
- ✅ Choose Alpha158 or Alpha360 based on the model type
- ✅ Reference existing implementations when adding custom factors
Next steps¶
- Explore other Qlib features: backtesting, portfolio optimization, reinforcement learning
- Try different models: examples/benchmarks
- Join the community: open issues, contribute code
Version: v1.0 Last updated: 2025-01-28 Author: Compiled from the official Qlib documentation and source code Contact: Qlib GitHub Issues