Skip to content

Chapter 3: Supervised Learning Models

Notes - This chapter contains both real model entry points from the repository and illustrative network-structure code written to explain the underlying ideas. - Any long code block defining a custom nn.Module should by default be read as a teaching illustration; to use the in-repo implementations, prefer the ready-made model classes under qlib.contrib.model.

Learning Objectives

After studying this chapter, you will be able to: - Understand the basic principles of supervised learning in quantitative investment - Master the application of traditional machine learning models in quantitative investing - Become familiar with the characteristics and usage of deep learning models - Learn to use Qlib's built-in/optional model implementations - Understand the principles and applications of advanced modeling techniques

3.1 Traditional Machine Learning Models

3.1.1 LightGBM: Principles and Practice

Introduction to LightGBM

LightGBM (Light Gradient Boosting Machine) is an efficient gradient boosting framework developed by Microsoft, with excellent performance in quantitative investing.

Key characteristics: - Efficiency: histogram-based algorithm, fast training - Memory friendly: low memory footprint, supports large datasets - Accuracy: excellent results on many benchmarks - Interpretability: provides feature importance analysis

Model Principles

1. Gradient Boosted Decision Trees (GBDT)

# Basic idea of GBDT
class GBDT:
    def __init__(self, n_estimators=100, learning_rate=0.1):
        self.n_estimators = n_estimators
        self.learning_rate = learning_rate
        self.trees = []

    def fit(self, X, y):
        # Initialize predictions
        predictions = np.zeros(len(y))

        for i in range(self.n_estimators):
            # Compute residuals
            residuals = y - predictions

            # Train a decision tree
            tree = DecisionTreeRegressor(max_depth=6)
            tree.fit(X, residuals)

            # Update predictions
            predictions += self.learning_rate * tree.predict(X)
            self.trees.append(tree)

    def predict(self, X):
        predictions = np.zeros(len(X))
        for tree in self.trees:
            predictions += self.learning_rate * tree.predict(X)
        return predictions

2. LightGBM optimization techniques - Histogram algorithm: discretizes continuous features, reducing memory usage - Leaf-wise growth: splits leaf nodes first, reducing overfitting - Categorical feature support: handles categorical features natively, no one-hot encoding needed

LightGBM in Qlib

1. Basic usage

from qlib.contrib.model.gbdt import LGBModel
from qlib.contrib.data.handler import Alpha158

# Prepare the data
handler = Alpha158(
    instruments='csi300',
    start_time='2020-01-01',
    end_time='2020-12-31',
    freq='day'
)

# Fetch the data
data = handler.fetch(
    segments={
        'train': ('2020-01-01', '2020-06-30'),
        'valid': ('2020-07-01', '2020-09-30'),
        'test': ('2020-10-01', '2020-12-31')
    }
)

# Create the model
model = LGBModel(
    loss='mse',
    colsample_bytree=0.8879,
    learning_rate=0.2,
    subsample=0.8789,
    n_estimators=100,
    max_depth=8,
    num_leaves=210,
    min_child_samples=20
)

# Train the model
model.fit(data['train']['feature'], data['train']['label']['LABEL0'])

2. Model configuration tuning

# Tuned configuration
model_config = {
    'loss': 'mse',                    # loss function
    'colsample_bytree': 0.8879,      # feature sampling ratio
    'learning_rate': 0.2,            # learning rate
    'subsample': 0.8789,             # sample sampling ratio
    'n_estimators': 100,             # number of trees
    'max_depth': 8,                  # maximum depth
    'num_leaves': 210,               # number of leaves
    'min_child_samples': 20,         # minimum samples per leaf
    'reg_alpha': 0.001,              # L1 regularization
    'reg_lambda': 0.001,             # L2 regularization
    'random_state': 42               # random seed
}

model = LGBModel(**model_config)

3. Feature importance analysis

# Get feature importance
feature_importance = model.feature_importance()

# Visualize feature importance
import matplotlib.pyplot as plt

plt.figure(figsize=(12, 8))
feature_importance.sort_values(ascending=True).plot(kind='barh')
plt.title('Feature Importance')
plt.xlabel('Importance')
plt.tight_layout()
plt.show()

3.1.2 Applying XGBoost

Introduction to XGBoost

XGBoost (eXtreme Gradient Boosting) is an optimized distributed gradient boosting library, with excellent results in machine learning competitions.

Key characteristics: - Regularization: built-in L1 and L2 regularization to prevent overfitting - Parallel computation: multi-threaded parallel training supported - Missing value handling: handles missing values automatically - Cross validation: built-in cross-validation

Model Implementation

1. Basic implementation

from qlib.contrib.model.xgboost import XGBModel

# Create an XGBoost model
model = XGBModel(
    max_depth=6,
    learning_rate=0.1,
    n_estimators=100,
    objective='reg:squarederror',
    subsample=0.8,
    colsample_bytree=0.8,
    random_state=42
)

# Train the model
model.fit(
    data['train']['feature'],
    data['train']['label']['LABEL0'],
    eval_set=[(data['valid']['feature'], data['valid']['label']['LABEL0'])],
    early_stopping_rounds=10,
    verbose=False
)

2. Hyperparameter optimization

from sklearn.model_selection import GridSearchCV

# Define the parameter grid
param_grid = {
    'max_depth': [3, 6, 9],
    'learning_rate': [0.01, 0.1, 0.2],
    'n_estimators': [50, 100, 200],
    'subsample': [0.8, 0.9, 1.0],
    'colsample_bytree': [0.8, 0.9, 1.0]
}

# Grid search
grid_search = GridSearchCV(
    XGBModel(),
    param_grid,
    cv=5,
    scoring='neg_mean_squared_error',
    n_jobs=-1
)

grid_search.fit(data['train']['feature'], data['train']['label']['LABEL0'])
print("Best parameters:", grid_search.best_params_)

3.1.3 Using CatBoost

Introduction to CatBoost

CatBoost is a gradient boosting library developed by Yandex, particularly good at handling categorical features.

Key characteristics: - Categorical feature handling: native support for categorical features - Overfitting control: built-in overfitting detection - Prediction quality: excellent results on many benchmarks - Ease of use: relatively few parameters, easy to tune

Model Implementation

1. Basic usage

from qlib.contrib.model.catboost_model import CatBoostModel

# Create a CatBoost model
model = CatBoostModel(
    iterations=100,
    learning_rate=0.1,
    depth=6,
    l2_leaf_reg=3,
    loss_function='RMSE',
    random_seed=42
)

# Train the model
model.fit(
    data['train']['feature'],
    data['train']['label']['LABEL0'],
    eval_set=(data['valid']['feature'], data['valid']['label']['LABEL0']),
    verbose=False
)

2. Handling categorical features

# Identify categorical features
categorical_features = data['train']['feature'].select_dtypes(include=['object']).columns

# Specify categorical features when creating the model
model = CatBoostModel(
    iterations=100,
    learning_rate=0.1,
    depth=6,
    cat_features=categorical_features.tolist()
)

3.1.4 Linear Models and Ensemble Methods

Linear Regression Models

1. Basic linear regression

from sklearn.linear_model import LinearRegression
from qlib.contrib.model.linear import LinearModel

# Create a linear model
model = LinearModel(
    fit_intercept=True,
    normalize=False
)

# Train the model
model.fit(data['train']['feature'], data['train']['label']['LABEL0'])

# Predict
predictions = model.predict(data['test']['feature'])

2. Regularized linear models

from sklearn.linear_model import Ridge, Lasso, ElasticNet

# Ridge regression (L2 regularization)
ridge_model = Ridge(alpha=1.0)

# Lasso regression (L1 regularization)
lasso_model = Lasso(alpha=0.1)

# ElasticNet (L1 + L2 regularization)
elastic_model = ElasticNet(alpha=0.1, l1_ratio=0.5)

Ensemble Methods

1. Random Forest

from sklearn.ensemble import RandomForestRegressor

# Create a random forest model
rf_model = RandomForestRegressor(
    n_estimators=100,
    max_depth=10,
    min_samples_split=5,
    min_samples_leaf=2,
    random_state=42
)

# Train the model
rf_model.fit(data['train']['feature'], data['train']['label']['LABEL0'])

2. Voting regressor

from sklearn.ensemble import VotingRegressor

# Create several base models
models = [
    ('lgb', LGBModel()),
    ('xgb', XGBModel()),
    ('cat', CatBoostModel())
]

# Create the voting regressor
voting_regressor = VotingRegressor(estimators=models)

# Train the model
voting_regressor.fit(data['train']['feature'], data['train']['label']['LABEL0'])

3.2 Deep Learning Models

Note: the Qlib repository already provides implementations such as DNNModelPytorch, LSTM, GRU, ALSTM, TCN, and TransformerModel. The code blocks below mainly explain network structures and should not be read as the complete calling convention of the repository's ready-made wrappers.

3.2.1 MLP Neural Network Models

Introduction to MLP

The multilayer perceptron (MLP) is the most basic deep learning model and is widely used in quantitative investing as well.

Key characteristics: - Nonlinear modeling: introduces nonlinearity through activation functions - Feature learning: learns feature representations automatically - Flexibility: network structure can be adjusted freely - Interpretability: relatively easy to understand

Model Implementation

1. Basic MLP model

import torch
import torch.nn as nn
# For the corresponding ready-made wrapper in Qlib, see qlib.contrib.model.pytorch_nn.DNNModelPytorch

# Define the MLP network structure
class MLP(nn.Module):
    def __init__(self, input_size, hidden_size=128, num_layers=3):
        super(MLP, self).__init__()

        layers = []
        layers.append(nn.Linear(input_size, hidden_size))
        layers.append(nn.ReLU())
        layers.append(nn.Dropout(0.2))

        for _ in range(num_layers - 2):
            layers.append(nn.Linear(hidden_size, hidden_size))
            layers.append(nn.ReLU())
            layers.append(nn.Dropout(0.2))

        layers.append(nn.Linear(hidden_size, 1))

        self.network = nn.Sequential(*layers)

    def forward(self, x):
        return self.network(x)

# What is shown here is the network structure itself; when plugging into the Qlib
# training pipeline, one would typically use DNNModelPytorch or wrap the DatasetH
# training logic manually.

2. Advanced MLP configuration

# To map this onto the in-repo implementation, convert the network parameters into
# DNNModelPytorch's `pt_model_kwargs`, `lr`, `batch_size`, and similar configuration.

3.2.2 LSTM/GRU Sequence Models

Introduction to Sequence Models

LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) are recurrent neural networks designed specifically for sequence data.

Key characteristics: - Memory mechanism: captures long-term dependencies - Gating mechanism: controls information flow - Sequence modeling: well suited to time-series data - Gradient control: effectively mitigates vanishing gradients

LSTM Implementation

1. Basic LSTM model

import torch
import torch.nn as nn
# For the corresponding ready-made implementation in Qlib, see qlib.contrib.model.pytorch_lstm.LSTM

class LSTM(nn.Module):
    def __init__(self, input_size, hidden_size=128, num_layers=2, dropout=0.2):
        super(LSTM, self).__init__()

        self.hidden_size = hidden_size
        self.num_layers = num_layers

        self.lstm = nn.LSTM(
            input_size=input_size,
            hidden_size=hidden_size,
            num_layers=num_layers,
            dropout=dropout,
            batch_first=True
        )

        self.fc = nn.Linear(hidden_size, 1)

    def forward(self, x):
        # x shape: (batch_size, seq_len, input_size)
        lstm_out, _ = self.lstm(x)

        # Take the output of the last time step
        last_output = lstm_out[:, -1, :]

        # Fully connected layer
        output = self.fc(last_output)
        return output

# When plugging into the real Qlib training pipeline, one usually instantiates
# qlib.contrib.model.pytorch_lstm.LSTM directly.

2. GRU implementation

class GRU(nn.Module):
    def __init__(self, input_size, hidden_size=128, num_layers=2, dropout=0.2):
        super(GRU, self).__init__()

        self.hidden_size = hidden_size
        self.num_layers = num_layers

        self.gru = nn.GRU(
            input_size=input_size,
            hidden_size=hidden_size,
            num_layers=num_layers,
            dropout=dropout,
            batch_first=True
        )

        self.fc = nn.Linear(hidden_size, 1)

    def forward(self, x):
        # x shape: (batch_size, seq_len, input_size)
        gru_out, _ = self.gru(x)

        # Take the output of the last time step
        last_output = gru_out[:, -1, :]

        # Fully connected layer
        output = self.fc(last_output)
        return output

# When plugging into the real Qlib training pipeline, one usually instantiates
# qlib.contrib.model.pytorch_gru.GRU directly.

3.2.3 Applying Transformers

Introduction to Transformers

The Transformer is an attention-based deep learning model that achieved huge success in NLP and has recently been applied to quantitative investing as well.

Key characteristics: - Attention mechanism: focuses on the important time steps - Parallel computation: supports parallel training - Long-range dependencies: handles long sequences well - Scalability: easy to scale and optimize

Model Implementation

1. Basic Transformer model

import torch
import torch.nn as nn
import math

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, max_len=5000):
        super(PositionalEncoding, self).__init__()

        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))

        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0).transpose(0, 1)

        self.register_buffer('pe', pe)

    def forward(self, x):
        return x + self.pe[:x.size(0), :]

class Transformer(nn.Module):
    def __init__(self, input_size, d_model=128, nhead=8, num_layers=6, dropout=0.1):
        super(Transformer, self).__init__()

        self.input_projection = nn.Linear(input_size, d_model)
        self.pos_encoder = PositionalEncoding(d_model)

        encoder_layer = nn.TransformerEncoderLayer(
            d_model=d_model,
            nhead=nhead,
            dim_feedforward=d_model * 4,
            dropout=dropout
        )

        self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers)
        self.fc = nn.Linear(d_model, 1)

    def forward(self, x):
        # x shape: (batch_size, seq_len, input_size)
        x = self.input_projection(x)  # (batch_size, seq_len, d_model)
        x = x.transpose(0, 1)  # (seq_len, batch_size, d_model)
        x = self.pos_encoder(x)
        x = self.transformer_encoder(x)
        x = x.transpose(0, 1)  # (batch_size, seq_len, d_model)

        # Take the output of the last time step
        last_output = x[:, -1, :]
        output = self.fc(last_output)
        return output

# For plugging into the real Qlib training pipeline, see qlib.contrib.model.pytorch_transformer.TransformerModel.

3.2.4 Graph Attention Networks (GATs)

Introduction to Graph Neural Networks

Graph Attention Networks (GATs) are a kind of graph neural network that can model complex relationships between stocks.

Key characteristics: - Graph-structured modeling: models inter-stock relationships - Attention mechanism: dynamically learns the importance between stocks - Relationship modeling: accounts for mutual influence between stocks - Interpretability: can explain inter-stock relationships

Model Implementation

1. Graph attention layer

import torch
import torch.nn as nn
import torch.nn.functional as F

class GraphAttentionLayer(nn.Module):
    def __init__(self, in_features, out_features, dropout=0.1, alpha=0.2):
        super(GraphAttentionLayer, self).__init__()

        self.in_features = in_features
        self.out_features = out_features
        self.dropout = dropout
        self.alpha = alpha

        self.W = nn.Linear(in_features, out_features, bias=False)
        self.a = nn.Linear(2 * out_features, 1, bias=False)

        self.leakyrelu = nn.LeakyReLU(self.alpha)

    def forward(self, input, adj):
        # input: (N, in_features)
        # adj: (N, N)

        Wh = self.W(input)  # (N, out_features)

        # Compute attention coefficients
        a_input = torch.cat([Wh.repeat_interleave(Wh.size(0), dim=0), 
                            Wh.repeat(Wh.size(0), 1)], dim=1)
        a_input = a_input.view(Wh.size(0), Wh.size(0), 2 * self.out_features)
        e = self.leakyrelu(self.a(a_input).squeeze(2))

        # Masking
        zero_vec = -9e15 * torch.ones_like(e)
        attention = torch.where(adj > 0, e, zero_vec)
        attention = F.softmax(attention, dim=1)
        attention = F.dropout(attention, self.dropout, training=self.training)

        h_prime = torch.matmul(attention, Wh)
        return h_prime

class GAT(nn.Module):
    def __init__(self, input_size, hidden_size=64, num_heads=8, dropout=0.1):
        super(GAT, self).__init__()

        self.dropout = dropout
        self.attention_layers = nn.ModuleList([
            GraphAttentionLayer(input_size, hidden_size, dropout, alpha=0.2)
            for _ in range(num_heads)
        ])

        self.out_att = GraphAttentionLayer(hidden_size * num_heads, 1, dropout, alpha=0.2)

    def forward(self, x, adj):
        # x: (N, input_size)
        # adj: (N, N)

        # Multi-head attention
        x = F.dropout(x, self.dropout, training=self.training)
        x = torch.cat([att(x, adj) for att in self.attention_layers], dim=1)
        x = F.elu(x)

        # Output layer
        x = F.dropout(x, self.dropout, training=self.training)
        x = self.out_att(x, adj)

        return x

# Plugging graph models in usually requires additionally preparing graph-structure data;
# see the GATs and related implementations in the repository.

3.3 Advanced Modeling Techniques

3.3.1 Attention-Based Models (SFM, ALSTM)

Introduction to Attention Mechanisms

Attention mechanisms allow a model to focus on the important parts of an input sequence, identifying key time points and features in quantitative investing.

Key characteristics: - Dynamic weights: assigns weights dynamically based on the input - Interpretability: can explain what the model attends to - Long-range dependencies: handles long sequences - Flexibility: applicable to many kinds of models

SFM Implementation

SFM (State Frequency Memory) is an attention model designed specifically for time-series forecasting.

class SFM(nn.Module):
    def __init__(self, input_size, hidden_size=128, num_frequencies=10):
        super(SFM, self).__init__()

        self.hidden_size = hidden_size
        self.num_frequencies = num_frequencies

        # State memory module
        self.state_memory = nn.Linear(input_size, hidden_size)

        # Frequency memory module
        self.frequency_memory = nn.Linear(input_size, num_frequencies)

        # Attention mechanism
        self.attention = nn.MultiheadAttention(hidden_size, num_heads=8)

        # Output layer
        self.output_layer = nn.Linear(hidden_size, 1)

    def forward(self, x):
        # x shape: (batch_size, seq_len, input_size)
        batch_size, seq_len, _ = x.size()

        # State memory
        state_memory = self.state_memory(x)  # (batch_size, seq_len, hidden_size)

        # Frequency memory
        frequency_memory = self.frequency_memory(x)  # (batch_size, seq_len, num_frequencies)

        # Attention
        state_memory = state_memory.transpose(0, 1)  # (seq_len, batch_size, hidden_size)
        attended_output, _ = self.attention(state_memory, state_memory, state_memory)
        attended_output = attended_output.transpose(0, 1)  # (batch_size, seq_len, hidden_size)

        # Combine frequency information
        frequency_weights = F.softmax(frequency_memory, dim=-1)
        weighted_output = attended_output * frequency_weights.unsqueeze(-1).expand_as(attended_output)

        # Output layer
        output = self.output_layer(weighted_output[:, -1, :])  # take the last time step
        return output

ALSTM Implementation

ALSTM (Attention LSTM) combines an LSTM with an attention mechanism.

class ALSTM(nn.Module):
    def __init__(self, input_size, hidden_size=128, num_layers=2, dropout=0.2):
        super(ALSTM, self).__init__()

        self.hidden_size = hidden_size
        self.num_layers = num_layers

        # LSTM layers
        self.lstm = nn.LSTM(
            input_size=input_size,
            hidden_size=hidden_size,
            num_layers=num_layers,
            dropout=dropout,
            batch_first=True
        )

        # Attention layer
        self.attention = nn.MultiheadAttention(hidden_size, num_heads=8)

        # Output layer
        self.fc = nn.Linear(hidden_size, 1)

    def forward(self, x):
        # x shape: (batch_size, seq_len, input_size)

        # LSTM processing
        lstm_out, _ = self.lstm(x)  # (batch_size, seq_len, hidden_size)

        # Attention mechanism
        lstm_out = lstm_out.transpose(0, 1)  # (seq_len, batch_size, hidden_size)
        attended_output, _ = self.attention(lstm_out, lstm_out, lstm_out)
        attended_output = attended_output.transpose(0, 1)  # (batch_size, seq_len, hidden_size)

        # Output
        last_output = attended_output[:, -1, :]  # take the last time step
        output = self.fc(last_output)
        return output

3.3.2 Temporal Convolutional Networks (TCN)

Introduction to TCN

The Temporal Convolutional Network (TCN) processes time series with causal convolutions, offering parallel computation and long-range dependency modeling.

Key characteristics: - Causal convolutions: ensures no future information is used - Parallel computation: supports parallel training - Long-range dependencies: handles long sequences via dilated convolutions - Residual connections: mitigates vanishing gradients

Model Implementation

class TemporalBlock(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, stride, dilation, padding, dropout=0.2):
        super(TemporalBlock, self).__init__()

        self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size,
                               stride=stride, padding=padding, dilation=dilation)
        self.relu1 = nn.ReLU()
        self.dropout1 = nn.Dropout(dropout)

        self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size,
                               stride=stride, padding=padding, dilation=dilation)
        self.relu2 = nn.ReLU()
        self.dropout2 = nn.Dropout(dropout)

        self.net = nn.Sequential(self.conv1, self.relu1, self.dropout1,
                                self.conv2, self.relu2, self.dropout2)

        self.downsample = nn.Conv1d(in_channels, out_channels, 1) if in_channels != out_channels else None
        self.relu = nn.ReLU()

    def forward(self, x):
        out = self.net(x)
        res = x if self.downsample is None else self.downsample(x)
        return self.relu(out + res)

class TCN(nn.Module):
    def __init__(self, input_size, num_channels, kernel_size=2, dropout=0.2):
        super(TCN, self).__init__()

        layers = []
        num_levels = len(num_channels)

        for i in range(num_levels):
            dilation_size = 2 ** i
            in_channels = input_size if i == 0 else num_channels[i-1]
            out_channels = num_channels[i]

            layers.append(
                TemporalBlock(in_channels, out_channels, kernel_size, stride=1,
                            dilation=dilation_size, padding=(kernel_size-1) * dilation_size,
                            dropout=dropout)
            )

        self.network = nn.Sequential(*layers)
        self.fc = nn.Linear(num_channels[-1], 1)

    def forward(self, x):
        # x shape: (batch_size, seq_len, input_size)
        x = x.transpose(1, 2)  # (batch_size, input_size, seq_len)
        x = self.network(x)
        x = x.transpose(1, 2)  # (batch_size, seq_len, num_channels[-1])

        # Take the last time step
        last_output = x[:, -1, :]
        output = self.fc(last_output)
        return output

# For plugging into the real Qlib training pipeline, see qlib.contrib.model.pytorch_tcn.TCN.

3.3.3 Adaptive Models (ADARNN, ADD)

Introduction to Adaptive Models

Adaptive models adjust their parameters automatically as the data distribution changes — particularly useful in quantitative investing.

Key characteristics: - Dynamic adaptation: adapts to changing markets - Online learning: supports incremental learning - Concept drift handling: copes with distribution shifts - Robustness: more robust to abnormal data

ADARNN Implementation

ADARNN (Adaptive RNN) is a recurrent neural network with adaptive adjustment.

class ADARNN(nn.Module):
    def __init__(self, input_size, hidden_size=128, num_layers=2, dropout=0.2):
        super(ADARNN, self).__init__()

        self.hidden_size = hidden_size
        self.num_layers = num_layers

        # Adaptive LSTM layers
        self.lstm_layers = nn.ModuleList([
            nn.LSTM(input_size if i == 0 else hidden_size, hidden_size, 1, dropout=dropout)
            for i in range(num_layers)
        ])

        # Adaptive gating mechanism
        self.adaptive_gates = nn.ModuleList([
            nn.Linear(hidden_size, hidden_size)
            for _ in range(num_layers)
        ])

        # Output layer
        self.fc = nn.Linear(hidden_size, 1)

    def forward(self, x):
        # x shape: (batch_size, seq_len, input_size)
        batch_size, seq_len, _ = x.size()

        # Initialize hidden states
        h = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(x.device)
        c = torch.zeros(self.num_layers, batch_size, self.hidden_size).to(x.device)

        outputs = []

        for t in range(seq_len):
            layer_input = x[:, t, :].unsqueeze(1)  # (batch_size, 1, input_size)

            for layer_idx in range(self.num_layers):
                # LSTM processing
                lstm_out, (h[layer_idx], c[layer_idx]) = self.lstm_layers[layer_idx](
                    layer_input, (h[layer_idx], c[layer_idx])
                )

                # Adaptive gating
                gate = torch.sigmoid(self.adaptive_gates[layer_idx](lstm_out))
                lstm_out = lstm_out * gate

                layer_input = lstm_out

            outputs.append(lstm_out.squeeze(1))

        # Stack outputs across all time steps
        outputs = torch.stack(outputs, dim=1)  # (batch_size, seq_len, hidden_size)

        # Output layer
        last_output = outputs[:, -1, :]  # take the last time step
        output = self.fc(last_output)
        return output

ADD Implementation

ADD (Adaptive Deep Network) is an adaptive deep network.

class ADD(nn.Module):
    def __init__(self, input_size, hidden_size=128, num_layers=3, dropout=0.2):
        super(ADD, self).__init__()

        layers = []
        layers.append(nn.Linear(input_size, hidden_size))
        layers.append(nn.ReLU())
        layers.append(nn.Dropout(dropout))

        for _ in range(num_layers - 2):
            layers.append(nn.Linear(hidden_size, hidden_size))
            layers.append(nn.ReLU())
            layers.append(nn.Dropout(dropout))

        layers.append(nn.Linear(hidden_size, 1))

        self.network = nn.Sequential(*layers)

        # Adaptive parameters
        self.adaptive_weight = nn.Parameter(torch.ones(1))
        self.adaptive_bias = nn.Parameter(torch.zeros(1))

    def forward(self, x):
        # Base network output
        base_output = self.network(x)

        # Adaptive adjustment
        adaptive_output = base_output * self.adaptive_weight + self.adaptive_bias

        return adaptive_output

3.3.4 Multi-Task Learning Models

Introduction to Multi-Task Learning

Multi-task learning learns several related tasks at once — in quantitative investing it can predict multiple targets simultaneously.

Key characteristics: - Knowledge sharing: tasks share knowledge - Regularization effect: reduces overfitting - Efficiency: learns multiple tasks at once - Generalization: improves generalization

Model Implementation

class MultiTaskModel(nn.Module):
    def __init__(self, input_size, hidden_size=128, num_tasks=3):
        super(MultiTaskModel, self).__init__()

        # Shared feature extraction layers
        self.shared_layers = nn.Sequential(
            nn.Linear(input_size, hidden_size),
            nn.ReLU(),
            nn.Dropout(0.2),
            nn.Linear(hidden_size, hidden_size),
            nn.ReLU(),
            nn.Dropout(0.2)
        )

        # Task-specific layers
        self.task_specific_layers = nn.ModuleList([
            nn.Sequential(
                nn.Linear(hidden_size, hidden_size // 2),
                nn.ReLU(),
                nn.Dropout(0.2),
                nn.Linear(hidden_size // 2, 1)
            )
            for _ in range(num_tasks)
        ])

    def forward(self, x):
        # Shared feature extraction
        shared_features = self.shared_layers(x)

        # Task-specific predictions
        task_outputs = []
        for task_layer in self.task_specific_layers:
            task_output = task_layer(shared_features)
            task_outputs.append(task_output)

        return task_outputs

# Create the multi-task model
model = MultiTaskModel(
    input_size=data['train']['feature'].shape[1],
    hidden_size=128,
    num_tasks=3  # predict 3 different targets
)

# Multi-task loss function
def multi_task_loss(predictions, targets, weights=None):
    """Multi-task loss function"""
    if weights is None:
        weights = [1.0] * len(predictions)

    total_loss = 0
    for pred, target, weight in zip(predictions, targets, weights):
        loss = F.mse_loss(pred, target)
        total_loss += weight * loss

    return total_loss

Chapter Summary

This chapter covered the supervised learning models available in and around Qlib:

  1. Traditional machine learning models: gradient boosting models such as LightGBM, XGBoost, and CatBoost
  2. Deep learning models: neural models such as MLP, LSTM/GRU, Transformer, and GATs
  3. Advanced techniques: attention mechanisms, temporal convolutional networks, adaptive models, multi-task learning

Exercises

Exercise 1: Model comparison

  1. Train different models on the Alpha158 dataset
  2. Compare performance metrics across models
  3. Analyze each model's characteristics and suitable scenarios

Exercise 2: Model tuning

  1. Optimize the LightGBM model's hyperparameters
  2. Use grid search and Bayesian optimization
  3. Analyze how parameters affect model performance

Exercise 3: Feature engineering

  1. Design features for deep learning models
  2. Implement a custom feature engineering method
  3. Analyze how features affect model performance

Further Reading

  1. Machine learning theory
  2. Statistical Learning Methods (《统计学习方法》)
  3. Machine Learning (《机器学习》)

  4. Deep learning

  5. Deep Learning (《深度学习》)
  6. Dive into Deep Learning (《动手学深度学习》)

  7. Quantitative investment models

  8. Quantitative Investment Strategies and Techniques (《量化投资策略与技术》)
  9. Machine Learning in Quantitative Investment (《机器学习在量化投资中的应用》)