LSTM Workflow Configuration Analysis¶
File Overview¶
This YAML configuration file defines a quantitative investment workflow based on an LSTM model, using the Alpha158 feature set to train and predict on the CSI300 stock universe.
Detailed Configuration Analysis¶
Path¶
- examples/benchmarks/LSTM/workflow_config_lstm_Alpha158.yaml
1. Qlib Initialization Configuration (Lines 1-3)¶
qlib_init:
provider_uri: "~/.qlib/qlib_data/cn_data"
region: cn
- qlib_init: Initializes the Qlib system
- provider_uri: Data storage path, pointing to the China stock data directory
- region: Region set to "cn" (China), which affects the trading calendar and market rules
2. Market Configuration (Lines 4-5)¶
market: &market csi300
benchmark: &benchmark SH000300
- market: Defines the stock universe as CSI300 constituents (using the YAML anchor
&marketfor later reference) - benchmark: The benchmark index is the CSI 300 Index (SH000300)
3. Data Processing Configuration (Lines 6-32)¶
Basic Time Configuration¶
data_handler_config: &data_handler_config
start_time: 2008-01-01
end_time: 2020-08-01
fit_start_time: 2008-01-01
fit_end_time: 2014-12-31
instruments: *market
- start_time/end_time: Overall time range of the data (2008 to August 2020)
- fit_start_time/fit_end_time: Fitting time range for the data handler (statistics computed using only 2008-2014 data)
- instruments: References the CSI300 stock universe defined earlier
Inference-time Data Processors¶
infer_processors:
- class: FilterCol
kwargs:
fields_group: feature
col_list: ["RESI5", "WVMA5", "RSQR5", ...]
- FilterCol: Filters specific feature columns, removing the specified 20 Alpha158 features (likely redundant or noisy features)
- fields_group: feature: Only processes the feature fields, leaving labels untouched
- class: RobustZScoreNorm
kwargs:
fields_group: feature
clip_outlier: true
- RobustZScoreNorm: Robust Z-score normalization, using the median and MAD instead of the mean and standard deviation
- clip_outlier: true: Clips outliers (typically within ±3 times the MAD)
- class: Fillna
kwargs:
fields_group: feature
- Fillna: Fills missing values using default strategies such as forward fill
Learning-time Data Processors¶
learn_processors:
- class: DropnaLabel
- class: CSRankNorm
kwargs:
fields_group: label
- DropnaLabel: Removes samples whose label is NaN
- CSRankNorm: Cross-sectional rank normalization, converting labels into rank quantiles (ranking the labels of all stocks at each point in time)
Label Definition¶
label: ["Ref($close, -2) / Ref($close, -1) - 1"]
- Computes the 1-period forward return: tomorrow_close / today_close - 1
- This is a forward-looking label that predicts the next trading day's return
4. Portfolio Analysis Configuration (Lines 34-52)¶
port_analysis_config: &port_analysis_config
strategy:
class: TopkDropoutStrategy
module_path: qlib.contrib.strategy
kwargs:
signal: <PRED>
topk: 50
n_drop: 5
- TopkDropoutStrategy: Selects the K stocks with the highest predicted signals, randomly dropping some to increase diversity
- signal:
: Uses the model's predictions as the signal - topk: 50: Selects the 50 stocks with the highest predicted values
- n_drop: 5: Randomly drops 5 stocks from the top 50, ending up holding 45 stocks
backtest:
start_time: 2017-01-01
end_time: 2020-08-01
account: 100000000
benchmark: *benchmark
exchange_kwargs:
limit_threshold: 0.095
deal_price: close
open_cost: 0.0005
close_cost: 0.0015
min_cost: 5
- Backtest period: January 2017 to August 2020 (out-of-sample testing)
- account: Initial capital of 100 million yuan
- limit_threshold: 0.095: 9.5% price limit threshold
- deal_price: close: Trades executed at the closing price
- open_cost: 0.0005: 0.05% opening (buy) commission
- close_cost: 0.0015: 0.15% closing (sell) commission
- min_cost: 5: Minimum commission of 5 yuan
5. Task Configuration (Lines 53-97)¶
Model Configuration¶
model:
class: LSTM
module_path: qlib.contrib.model.pytorch_lstm_ts
kwargs:
d_feat: 20
hidden_size: 64
num_layers: 2
dropout: 0.0
n_epochs: 200
lr: 1e-3
early_stop: 10
batch_size: 800
metric: loss
loss: mse
n_jobs: 20
GPU: 0
Detailed Explanation of Core LSTM Hyperparameters:
- d_feat: 20:
- The input feature dimension is 20, here referring to selecting the top 20 most important features from Alpha158
- This is not the number of time steps, but the number of features at each point in time
-
The feature selection strategy may be based on importance ranking or correlation analysis
-
hidden_size: 64:
- The LSTM hidden state dimension is 64
- Controls the model's representational capacity; larger values can capture more complex patterns
- Typical values: 32-512, requiring a balance between data complexity and computational resources
-
Too large may lead to overfitting; too small may result in insufficient representational capacity
-
num_layers: 2:
- Stacks 2 LSTM layers, forming a deep network
- Deeper networks can learn more complex temporal dependencies
- In financial time-series modeling, 2-3 layers are usually the best choice
-
Too deep may cause vanishing gradients and training difficulties
-
dropout: 0.0:
- No dropout regularization is used
- Possibly because the data volume is large enough (12 years of CSI300 data) that no additional regularization is needed
- Or possibly because other regularization techniques are already in place (early stopping)
-
Recommended values: 0.1-0.5, especially on small datasets
-
n_epochs: 200:
- Maximum of 200 training epochs
- Used in combination with early_stop; the actual number of training epochs is usually fewer
- Training on financial data often requires many epochs to converge
-
Too many may overfit; too few may underfit
-
lr: 1e-3:
- Learning rate of 0.001, a classic starting learning rate
- The default learning rate of the Adam optimizer, suitable for most deep learning tasks
- Financial time-series data is relatively sensitive to the learning rate
-
Consider a learning rate decay strategy to improve performance
-
early_stop: 10:
- Early stopping mechanism: training stops if validation performance shows no improvement for 10 epochs
- An important means of preventing overfitting
- 10 epochs is a fairly conservative setting, ensuring the model is sufficiently trained
-
Works together with monitoring loss changes on the validation set
-
batch_size: 800:
- Batch size of 800, a relatively large batch
- Large batches benefit the stability of gradient estimation
- Financial data has a large number of samples, so larger batches can be used
-
Requires sufficient GPU memory and affects training speed
-
metric: loss and loss: mse:
- Both the evaluation metric and loss function use mean squared error (MSE)
- Suitable for regression tasks, measuring the deviation between predicted and actual returns
-
MSE is sensitive to outliers; consider more robust losses such as Huber Loss
-
n_jobs: 20:
- Uses 20 parallel processes for data loading
- Speeds up data preprocessing and batch generation
- Should be set according to CPU core count and memory
-
Too many may cause insufficient memory or context-switching overhead
-
GPU: 0:
- Uses GPU 0 for training
- A necessary configuration for deep learning training
- In multi-GPU environments, a specific device ID must be specified
Hyperparameter Combination Analysis: - Conservative and robust: Medium network size (64 units + 2 layers), standard learning rate, large-batch training - Anti-overfitting strategy: Early stopping mechanism; no dropout, possibly relying on the natural regularization of a large data volume - Computational efficiency: Highly parallel data loading, GPU acceleration, suitable for production environments
Dataset Configuration¶
dataset:
class: TSDatasetH
module_path: qlib.data.dataset
kwargs:
handler:
class: Alpha158
module_path: qlib.contrib.data.handler
kwargs: *data_handler_config
segments:
train: [2008-01-01, 2014-12-31]
valid: [2015-01-01, 2016-12-31]
test: [2017-01-01, 2020-08-01]
step_len: 20
- TSDatasetH: Time-series dataset, supporting sequential models such as LSTM
- Alpha158: Uses the Alpha158 feature engineering handler
- Data splits:
- Training set: 2008-2014 (7 years)
- Validation set: 2015-2016 (2 years)
- Test set: January 2017 to August 2020 (3.7 years)
- step_len: 20: LSTM time window length of 20 trading days
Record Configuration¶
record:
- class: SignalRecord
- class: SigAnaRecord
kwargs:
ana_long_short: False
ann_scaler: 252
- class: PortAnaRecord
kwargs:
config: *port_analysis_config
- SignalRecord: Records the model's prediction signals
- SigAnaRecord: Signal analysis record
- ana_long_short: False: Does not analyze long-short signals
- ann_scaler: 252: Annualization factor of 252 (number of trading days in a year)
- PortAnaRecord: Portfolio analysis record, using the portfolio analysis configuration defined above
Workflow Summary¶
- Data preparation: Obtain 2008-2020 data from the CSI300 stock universe, using Alpha158 feature engineering
- Data preprocessing: Feature filtering, normalization, missing-value handling, and label rank normalization
- Time-series modeling: 2-layer LSTM network, 20-day time window, predicting the next day's return
- Strategy backtest: Top-50 stock selection strategy, out-of-sample backtest over 2017-2020
- Result recording: Record prediction signals, analysis results, and portfolio performance
This configuration is suitable for medium-frequency quantitative trading strategies, combining technical analysis features with deep learning time-series modeling.
XGBoost Workflow Configuration Analysis¶
File Overview¶
This YAML configuration file defines a quantitative investment workflow based on an XGBoost model, using the Alpha158 feature set to train and predict on the CSI300 stock universe. Compared with the LSTM configuration, the XGBoost configuration is more concise, with the main differences in the model type and hyperparameter settings.
Detailed Configuration Analysis¶
Path¶
- examples/benchmarks/XGBoost/workflow_config_xgboost_Alpha158.yaml
1. Qlib Initialization Configuration (Lines 1-3)¶
qlib_init:
provider_uri: "~/.qlib/qlib_data/cn_data"
region: cn
- qlib_init: Initializes the Qlib system
- provider_uri: Data storage path, pointing to the China stock data directory
- region: Region set to "cn" (China), which affects the trading calendar and market rules
2. Market Configuration (Lines 4-5)¶
market: &market csi300
benchmark: &benchmark SH000300
- market: Defines the stock universe as CSI300 constituents (using the YAML anchor
&marketfor later reference) - benchmark: The benchmark index is the CSI 300 Index (SH000300)
3. Data Processing Configuration (Lines 6-11)¶
data_handler_config: &data_handler_config
start_time: 2008-01-01
end_time: 2020-08-01
fit_start_time: 2008-01-01
fit_end_time: 2014-12-31
instruments: *market
- start_time/end_time: Overall time range of the data (2008 to August 2020)
- fit_start_time/fit_end_time: Fitting time range for the data handler (statistics computed using only 2008-2014 data)
- instruments: References the CSI300 stock universe defined earlier
Note: The XGBoost configuration does not explicitly define data processors (infer_processors and learn_processors), which means Alpha158's default preprocessing pipeline is used.
4. Portfolio Analysis Configuration (Lines 12-30)¶
port_analysis_config: &port_analysis_config
strategy:
class: TopkDropoutStrategy
module_path: qlib.contrib.strategy
kwargs:
signal: <PRED>
topk: 50
n_drop: 5
- TopkDropoutStrategy: Selects the K stocks with the highest predicted signals, randomly dropping some to increase diversity
- signal:
: Uses the model's predictions as the signal - topk: 50: Selects the 50 stocks with the highest predicted values
- n_drop: 5: Randomly drops 5 stocks from the top 50, ending up holding 45 stocks
backtest:
start_time: 2017-01-01
end_time: 2020-08-01
account: 100000000
benchmark: *benchmark
exchange_kwargs:
limit_threshold: 0.095
deal_price: close
open_cost: 0.0005
close_cost: 0.0015
min_cost: 5
- Backtest period: January 2017 to August 2020 (out-of-sample testing)
- account: Initial capital of 100 million yuan
- limit_threshold: 0.095: 9.5% price limit threshold
- deal_price: close: Trades executed at the closing price
- open_cost: 0.0005: 0.05% opening (buy) commission
- close_cost: 0.0015: 0.15% closing (sell) commission
- min_cost: 5: Minimum commission of 5 yuan
5. Task Configuration (Lines 31-69)¶
XGBoost Model Configuration (Lines 32-42)¶
model:
class: XGBModel
module_path: qlib.contrib.model.xgboost
kwargs:
eval_metric: rmse
colsample_bytree: 0.8879
eta: 0.0421
max_depth: 8
n_estimators: 647
subsample: 0.8789
nthread: 20
Detailed Explanation of Core Hyperparameters:
- eval_metric: rmse:
- The evaluation metric is Root Mean Square Error
-
Suitable for regression tasks, measuring the deviation between predicted and actual values
-
colsample_bytree: 0.8879:
- The fraction of features randomly sampled per tree is 88.79%
- Prevents overfitting and improves the model's generalization ability
-
Value range: (0, 1], typical values 0.5-1.0
-
eta: 0.0421:
- The learning rate is 0.0421, relatively small
- Controls each tree's contribution to the final prediction
- A smaller learning rate usually requires more trees (n_estimators)
-
Value range: (0, 1], typical values 0.01-0.3
-
max_depth: 8:
- The maximum tree depth is 8 levels
- Controls model complexity and prevents overfitting
- Deeper trees can capture more complex feature interactions
-
Typical values 3-10; 6-10 is common for financial data
-
n_estimators: 647:
- Builds 647 decision trees
- A larger number of trees combined with a smaller learning rate
-
The optimal value is usually determined via cross-validation or early stopping
-
subsample: 0.8789:
- The fraction of samples randomly sampled per tree is 87.89%
- Prevents overfitting, similar to bootstrap sampling in random forests
-
Value range: (0, 1], typical values 0.5-1.0
-
nthread: 20:
- Uses 20 threads for parallel training
- Speeds up training; should be set according to CPU core count
Hyperparameter Combination Analysis: - Conservative configuration: Smaller learning rate (0.0421) combined with more trees (647), pursuing stability - Anti-overfitting strategy: Uses feature sampling (0.8879) and sample sampling (0.8789) - Model complexity: Medium depth (8) balancing fitting ability and generalization - Computational resources: High parallelism (20 threads), suitable for training on large-scale data
Dataset Configuration (Lines 43-54)¶
dataset:
class: DatasetH
module_path: qlib.data.dataset
kwargs:
handler:
class: Alpha158
module_path: qlib.contrib.data.handler
kwargs: *data_handler_config
segments:
train: [2008-01-01, 2014-12-31]
valid: [2015-01-01, 2016-12-31]
test: [2017-01-01, 2020-08-01]
- DatasetH: Standard tabular dataset, suitable for traditional ML models such as XGBoost (in contrast to LSTM's TSDatasetH)
- Alpha158: Uses the Alpha158 feature engineering handler, generating 158 technical indicator features
- Data splits:
- Training set: 2008-2014 (7 years), used for model training
- Validation set: 2015-2016 (2 years), used for hyperparameter tuning and early stopping
- Test set: January 2017 to August 2020 (3.7 years), used for final performance evaluation
Key differences:
- XGBoost uses DatasetH (tabular data)
- LSTM uses TSDatasetH (time-series data, with the step_len parameter)
Record Configuration (Lines 55-69)¶
record:
- class: SignalRecord
module_path: qlib.workflow.record_temp
kwargs:
model: <MODEL>
dataset: <DATASET>
- class: SigAnaRecord
module_path: qlib.workflow.record_temp
kwargs:
ana_long_short: False
ann_scaler: 252
- class: PortAnaRecord
module_path: qlib.workflow.record_temp
kwargs:
config: *port_analysis_config
- SignalRecord: Records the model's prediction signals and related metadata
- SigAnaRecord: Signal analysis record
- ana_long_short: False: No long-short analysis, only considering a long-only strategy
- ann_scaler: 252: Annualization factor of 252 (number of trading days in a year), used to compute annualized returns and Sharpe ratio
- PortAnaRecord: Portfolio analysis record, computing backtest performance metrics
XGBoost vs LSTM Configuration Comparison¶
| Configuration Item | XGBoost | LSTM |
|---|---|---|
| Dataset type | DatasetH (tabular) | TSDatasetH (time series) |
| Time window | None | step_len: 20 |
| Data preprocessing | Default Alpha158 processing | Custom processor chain |
| Model complexity | Medium (647 trees) | Higher (2-layer LSTM) |
| Training approach | Batch training | Sequential training |
| Number of hyperparameters | 6 core parameters | 10 core parameters |
Hyperparameter Tuning Recommendations¶
Parameters to Tune First¶
- n_estimators + eta: Balance between learning rate and number of trees
- max_depth: Model complexity control
- subsample + colsample_bytree: Regularization strength
Tuning Strategy¶
# Recommended hyperparameter search space
param_grid = {
'n_estimators': [300, 500, 800, 1000],
'eta': [0.01, 0.05, 0.1, 0.2],
'max_depth': [6, 8, 10, 12],
'subsample': [0.7, 0.8, 0.9],
'colsample_bytree': [0.7, 0.8, 0.9]
}
Performance Optimization¶
- CPU parallelism: Adjust nthread according to your hardware
- Memory optimization: For large datasets, consider tree_method: 'hist'
- Early stopping: Use early_stopping_rounds with the validation set
Workflow Summary¶
- Data preparation: Obtain 2008-2020 data from the CSI300 stock universe, using Alpha158 feature engineering
- Model training: XGBoost gradient-boosted decision trees, 647 trees, smaller learning rate
- Strategy backtest: Top-50 stock selection strategy, out-of-sample backtest over 2017-2020
- Result recording: Record prediction signals, analysis results, and portfolio performance
This configuration is suitable for quantitative strategies based on traditional machine learning methods. XGBoost's advantages are fast training speed, good interpretability, and strong handling of missing values.