Skip to content

Chapter 2: A Deep Dive into the Data Layer

Notes - This chapter contains two kinds of code: real Qlib data interfaces from the current repository, and illustrative snippets showing data-processing ideas. - The repository does not provide calls like D.features(..., where=...) or qlib.init(cache_dir=...); the relevant snippets have been rewritten closer to the real API.

Learning Objectives

After studying this chapter, you will be able to: - Understand the design principles of Qlib's data framework - Master data retrieval, cleaning, and preprocessing techniques - Become familiar with the Alpha158 and Alpha360 datasets - Learn to build custom datasets - Master data quality checks and optimization methods

2.1 Data Framework Design

2.1.1 Qlib Data Storage Format

Data Storage Architecture

Qlib uses an efficient data storage format optimized specifically for quantitative investment scenarios.

Storage hierarchy:

qlib_data/
├── cn_data/                    # China market data
│   ├── calendars/              # trading calendars
│   ├── features/               # feature data
│   ├── instruments/            # stock lists
│   └── cache/                  # cached data
└── us_data/                    # US market data
    ├── calendars/
    ├── features/
    ├── instruments/
    └── cache/

Data Format Characteristics

1. Binary storage - Efficient binary format - Fast reads and writes - Reduced storage footprint

2. Columnar storage - Data stored by feature column - Vectorized computation friendly - Efficient data queries

3. Index optimization - Time-index optimization - Instrument-code indexing - Fast data location

Data Access Interface

from qlib.data import D

# Basic data access
data = D.features(
    instruments=['SH600000', 'SH600036'],  # stock codes
    fields=['$close', '$volume', '$open'],  # fields
    start_time='2020-01-01',               # start time
    end_time='2020-12-31',                 # end time
    freq='day'                             # frequency
)

2.1.2 Data Access Interface Design

Core Interfaces

1. Calendar interface

# Get the trading calendar
calendar = D.calendar(
    start_time='2020-01-01',
    end_time='2020-12-31',
    freq='day'
)

# Get trading days
trading_days = D.calendar(
    start_time='2020-01-01',
    end_time='2020-12-31',
    freq='day',
    future=False
)

2. Instrument list interface

# Get the instrument list
instruments = D.instruments('csi300')  # CSI300 constituents
stock_list = D.list_instruments(
    instruments=instruments,
    start_time='2020-01-01',
    end_time='2020-12-31',
    as_list=True
)

3. Feature data interface

# Get feature data
data = D.features(
    instruments=['SH600000'],
    fields=['$close', '$volume', 'Ref($close, 1)'],
    start_time='2020-01-01',
    end_time='2020-12-31',
    freq='day'
)

Advanced Query Features

1. Expression support

# Complex expressions are supported
fields = [
    '$close',                    # closing price
    'Ref($close, 1)',           # previous day's close
    'Mean($close, 20)',         # 20-day moving average
    '$close / Ref($close, 1) - 1',  # daily return
    'Std($close, 20)',          # 20-day standard deviation
]

2. Conditional filtering

# Qlib first fetches features, then filters with pandas
data = D.features(
    instruments=['SH600000'],
    fields=['$close'],
    start_time='2020-01-01',
    end_time='2020-12-31',
    freq='day'
)

filtered = data[data["$close"] > 0]

2.1.3 Data Caching Mechanism

Caching Strategy

1. Multi-level caching - Memory cache: hot data kept in memory - Disk cache: intermediate results cached to disk - Network cache: network-level caching in distributed environments

2. Cache update policy

# Basic initialization
qlib.init(
    mount_path="~/.qlib/qlib_data/cn_data",
    region=REG_CN
)

# Qlib's feature queries support disk caching control via disk_cache
data = D.features(
    instruments=['SH600000'],
    fields=['$close'],
    start_time='2020-01-01',
    end_time='2020-12-31',
    freq='day',
    disk_cache=1  # 0=skip cache, 1=use cache, 2=rebuild cache
)

3. Cache optimization

# Preload data
D.features(
    instruments=['SH600000'],
    fields=['$close'],
    start_time='2020-01-01',
    end_time='2020-12-31',
    freq='day',
    disk_cache=1
)

2.2 Data Retrieval and Processing

2.2.1 Retrieving Stock Data

Data Sources

1. Official data sources - Yahoo Finance: free stock data - Local data: preprocessed binary data - Custom data: user-provided data

2. Data frequencies - Daily data: OHLCV per day - Minute data: 1-minute, 5-minute, and other high-frequency data - Real-time data: live market data

How to Retrieve Data

1. Using official scripts

# Daily data
python scripts/get_data.py qlib_data \
  --target_dir ~/.qlib/qlib_data/cn_data \
  --region cn

# Minute data
python scripts/get_data.py qlib_data \
  --target_dir ~/.qlib/qlib_data/cn_data_1min \
  --region cn \
  --interval 1min

2. Using the module interface

# Daily data
python -m qlib.run.get_data qlib_data \
  --target_dir ~/.qlib/qlib_data/cn_data \
  --region cn

# Minute data
python -m qlib.run.get_data qlib_data \
  --target_dir ~/.qlib/qlib_data/cn_data_1min \
  --region cn \
  --interval 1min

3. Custom data retrieval

# Custom data retrieval script
import pandas as pd
from qlib.data import D

def get_custom_data():
    """Retrieve custom data"""
    # Get the instrument list
    instruments = D.instruments('csi300')

    # Get base data
    data = D.features(
        instruments=instruments,
        fields=['$close', '$volume', '$open', '$high', '$low'],
        start_time='2020-01-01',
        end_time='2020-12-31',
        freq='day'
    )

    return data

2.2.2 Data Cleaning and Preprocessing

Data Quality Issues

1. Common problems - Missing values: data missing at some time points - Outliers: abnormal prices or volumes - Duplicates: repeated records for the same time point - Inconsistency: different data sources disagree

2. Data cleaning methods

import pandas as pd
import numpy as np

def clean_data(data):
    """Data cleaning function"""
    # Handle missing values
    data = data.fillna(method='ffill')  # forward fill
    data = data.fillna(method='bfill')  # backward fill

    # Handle outliers
    # Price outliers
    price_cols = ['$open', '$high', '$low', '$close']
    for col in price_cols:
        if col in data.columns:
            # Filter outliers with a 3-sigma rule
            mean_val = data[col].mean()
            std_val = data[col].std()
            data[col] = data[col].clip(
                lower=mean_val - 3 * std_val,
                upper=mean_val + 3 * std_val
            )

    # Volume outliers
    if '$volume' in data.columns:
        data['$volume'] = data['$volume'].clip(lower=0)

    return data

Preprocessing Techniques

1. Standardization

from sklearn.preprocessing import StandardScaler

def normalize_data(data):
    """Standardize data"""
    scaler = StandardScaler()
    normalized_data = scaler.fit_transform(data)
    return pd.DataFrame(normalized_data, index=data.index, columns=data.columns)

2. Data alignment

def align_data(data_dict):
    """Align data"""
    # Get the index intersection of all data
    common_index = None
    for data in data_dict.values():
        if common_index is None:
            common_index = data.index
        else:
            common_index = common_index.intersection(data.index)

    # Align the data
    aligned_data = {}
    for name, data in data_dict.items():
        aligned_data[name] = data.loc[common_index]

    return aligned_data

2.2.3 Feature Engineering Basics

Technical Indicator Features

1. Moving averages

def calculate_ma(data, window=20):
    """Calculate a moving average"""
    return data.rolling(window=window).mean()

# Usage example
data['MA5'] = calculate_ma(data['$close'], 5)
data['MA20'] = calculate_ma(data['$close'], 20)

2. Relative Strength Index (RSI)

def calculate_rsi(data, window=14):
    """Calculate the RSI indicator"""
    delta = data.diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    return rsi

# Usage example
data['RSI'] = calculate_rsi(data['$close'])

3. Bollinger Bands

def calculate_bollinger_bands(data, window=20, num_std=2):
    """Calculate Bollinger Bands"""
    ma = data.rolling(window=window).mean()
    std = data.rolling(window=window).std()
    upper_band = ma + (std * num_std)
    lower_band = ma - (std * num_std)
    return upper_band, ma, lower_band

# Usage example
upper, middle, lower = calculate_bollinger_bands(data['$close'])
data['BB_upper'] = upper
data['BB_middle'] = middle
data['BB_lower'] = lower

Price Features

1. Return features

def calculate_returns(data):
    """Calculate return features"""
    # Daily return
    data['daily_return'] = data['$close'].pct_change()

    # Log return
    data['log_return'] = np.log(data['$close'] / data['$close'].shift(1))

    # Cumulative return
    data['cumulative_return'] = (1 + data['daily_return']).cumprod() - 1

    return data

2. Volatility features

def calculate_volatility(data, window=20):
    """Calculate volatility features"""
    # Rolling volatility
    data['volatility'] = data['daily_return'].rolling(window=window).std()

    # Annualized volatility
    data['annualized_volatility'] = data['volatility'] * np.sqrt(252)

    return data

Volume Features

1. Volume indicators

def calculate_volume_features(data):
    """Calculate volume features"""
    # Volume moving averages
    data['volume_ma5'] = data['$volume'].rolling(window=5).mean()
    data['volume_ma20'] = data['$volume'].rolling(window=20).mean()

    # Volume ratio
    data['volume_ratio'] = data['$volume'] / data['volume_ma20']

    # Volume rate of change
    data['volume_change'] = data['$volume'].pct_change()

    return data

2.2.4 Data Quality Checks

Data Quality Metrics

1. Completeness check

def check_completeness(data):
    """Check data completeness"""
    # Missing-value statistics
    missing_stats = data.isnull().sum()
    missing_ratio = missing_stats / len(data)

    print("Missing values:")
    for col, ratio in missing_ratio.items():
        if ratio > 0:
            print(f"{col}: {ratio:.2%}")

    return missing_ratio

2. Consistency check

def check_consistency(data):
    """Check data consistency"""
    # Price logic check
    if all(col in data.columns for col in ['$open', '$high', '$low', '$close']):
        # Check OHLC logic
        invalid_high = data['$high'] < data[['$open', '$close']].max(axis=1)
        invalid_low = data['$low'] > data[['$open', '$close']].min(axis=1)

        print(f"Invalid high prices: {invalid_high.sum()} rows")
        print(f"Invalid low prices: {invalid_low.sum()} rows")

    # Volume check
    if '$volume' in data.columns:
        negative_volume = data['$volume'] < 0
        print(f"Negative volume: {negative_volume.sum()} rows")

3. Outlier detection

def detect_outliers(data, method='iqr'):
    """Detect outliers"""
    outliers = {}

    for col in data.select_dtypes(include=[np.number]).columns:
        if method == 'iqr':
            # IQR method
            Q1 = data[col].quantile(0.25)
            Q3 = data[col].quantile(0.75)
            IQR = Q3 - Q1
            lower_bound = Q1 - 1.5 * IQR
            upper_bound = Q3 + 1.5 * IQR

            outliers[col] = (data[col] < lower_bound) | (data[col] > upper_bound)

        elif method == 'zscore':
            # Z-score method
            z_scores = np.abs((data[col] - data[col].mean()) / data[col].std())
            outliers[col] = z_scores > 3

    return outliers

Data Quality Report

def generate_quality_report(data):
    """Generate a data quality report"""
    report = {
        'Basic info': {
            'Data shape': data.shape,
            'Data types': data.dtypes.to_dict(),
            'Memory usage': data.memory_usage(deep=True).sum()
        },
        'Missing values': data.isnull().sum().to_dict(),
        'Duplicates': data.duplicated().sum(),
        'Unique values': {col: data[col].nunique() for col in data.columns}
    }

    # Numeric data statistics
    numeric_cols = data.select_dtypes(include=[np.number]).columns
    if len(numeric_cols) > 0:
        report['Numeric statistics'] = data[numeric_cols].describe().to_dict()

    return report

2.3 Quantitative Datasets

2.3.1 The Alpha158 Dataset in Detail

Dataset Overview

Alpha158 is a classic quantitative dataset provided by Qlib, containing 158 carefully designed features.

Dataset characteristics: - Number of features: 158 - Data frequency: daily - Time range: 2008–2020 - Stock universe: A-share market - Feature types: price, volume, technical indicators, and more

Feature Categories

1. Price features

# Basic price features
price_features = [
    '$open', '$high', '$low', '$close',  # OHLC
    '$vwap', '$adj',                     # volume-weighted average price, adjusted price
]

2. Return features

# Return features
return_features = [
    'Ref($close, 1)',                    # previous day's close
    'Ref($close, 2)',                    # close two days ago
    '$close / Ref($close, 1) - 1',      # daily return
    'Ref($close, 1) / Ref($close, 2) - 1',  # previous day's return
]

3. Technical indicator features

# Moving averages
ma_features = [
    'Mean($close, 5)',   # 5-day moving average
    'Mean($close, 10)',  # 10-day moving average
    'Mean($close, 20)',  # 20-day moving average
    'Mean($close, 60)',  # 60-day moving average
]

# Volatility indicators
volatility_features = [
    'Std($close, 5)',    # 5-day standard deviation
    'Std($close, 10)',   # 10-day standard deviation
    'Std($close, 20)',   # 20-day standard deviation
]

4. Volume features

# Volume features
volume_features = [
    '$volume',                           # volume
    'Mean($volume, 5)',                 # 5-day average volume
    'Mean($volume, 10)',                # 10-day average volume
    '$volume / Mean($volume, 20)',      # volume ratio
]

Using the Dataset

1. Loading Alpha158

from qlib.contrib.data.handler import Alpha158
from qlib.data.dataset import DatasetH

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

# Use DatasetH to manage train/valid/test splits
dataset = DatasetH(
    handler=handler,
    segments={
        'train': ('2020-01-01', '2020-06-30'),
        'valid': ('2020-07-01', '2020-09-30'),
        'test': ('2020-10-01', '2020-12-31')
    }
)

train_data = dataset.prepare("train")

2. Feature engineering

# Feature processing
features = train_data['train']['feature']
labels = train_data['train']['label']

# Feature selection
selected_features = [
    '$close', '$volume', 'Ref($close, 1)',
    'Mean($close, 20)', 'Std($close, 20)',
    '$volume / Mean($volume, 20)'
]

X = features[selected_features]
y = labels['LABEL0']  # future return

2.3.2 The Alpha360 Dataset in Detail

Dataset Overview

Alpha360 is a more advanced dataset with 360 features, built mainly from raw price and volume data.

Dataset characteristics: - Number of features: 360 - Data frequency: daily - Time range: 2008–2020 - Stock universe: A-share market - Feature types: raw price data, technical indicators, statistical features

Feature Construction Principles

Note: the feature lists below explain how Alpha360 is constructed. In the actual repository, Alpha360 is generated internally by qlib.contrib.data.handler.Alpha360 — these expressions are not meant to be executed line by line from a tutorial.

1. Raw data features

# Basic price data
raw_price_features = [
    '$open', '$high', '$low', '$close', '$volume',
    '$vwap', '$adj', '$factor'  # adjustment factor
]

2. Time-series features

# Time-window features
time_window_features = [
    # Price features over the past 1–60 days
    'Ref($close, 1)', 'Ref($close, 2)', ..., 'Ref($close, 60)',
    'Ref($volume, 1)', 'Ref($volume, 2)', ..., 'Ref($volume, 60)',

    # Statistical features
    'Mean($close, 5)', 'Mean($close, 10)', 'Mean($close, 20)',
    'Std($close, 5)', 'Std($close, 10)', 'Std($close, 20)',
]

3. Technical indicator features

# Technical indicators
technical_features = [
    # Moving averages
    'Mean($close, 5)', 'Mean($close, 10)', 'Mean($close, 20)',

    # Relative Strength Index
    'RSI($close, 14)',

    # Bollinger Bands
    'BB_upper($close, 20, 2)', 'BB_lower($close, 20, 2)',

    # MACD
    'MACD($close, 12, 26, 9)',
]

Dataset Advantages

1. Feature richness - More raw data features - More complete time-series features - More comprehensive technical indicators

2. Data quality - Strict data cleaning applied - More standardized feature engineering - Better data consistency

3. Suitability - Suited to deep learning models - Supports complex feature combinations - Facilitates model optimization

2.3.3 Building Custom Datasets

Dataset Construction Workflow

1. Data preparation

import pandas as pd
import numpy as np
from qlib.data import D

def prepare_custom_data():
    """Prepare custom data"""
    # Get the instrument list
    instruments = D.instruments('csi300')

    # Get base data
    data = D.features(
        instruments=instruments,
        fields=['$close', '$volume', '$open', '$high', '$low'],
        start_time='2020-01-01',
        end_time='2020-12-31',
        freq='day'
    )

    return data

2. Feature engineering

def engineer_features(data):
    """Feature engineering"""
    # Compute technical indicators
    data['MA5'] = data['$close'].rolling(window=5).mean()
    data['MA20'] = data['$close'].rolling(window=20).mean()
    data['RSI'] = calculate_rsi(data['$close'])
    data['VOLUME_MA5'] = data['$volume'].rolling(window=5).mean()

    # Compute returns
    data['RETURN'] = data['$close'].pct_change()
    data['RETURN_5'] = data['$close'].pct_change(periods=5)

    # Compute volatility
    data['VOLATILITY'] = data['RETURN'].rolling(window=20).std()

    return data

3. Label generation

def generate_labels(data, forward_days=1):
    """Generate labels"""
    # Future return
    future_return = data['$close'].shift(-forward_days) / data['$close'] - 1

    # Classification labels (1 = up, 0 = down)
    labels = (future_return > 0).astype(int)

    return labels

Dataset Handler

from qlib.data.dataset.handler import DataHandler

class CustomDataHandler(DataHandler):
    """Custom data handler"""

    def __init__(self, instruments, start_time, end_time, freq='day'):
        super().__init__(instruments, start_time, end_time, freq)

    def fetch(self, segments, **kwargs):
        """Fetch data"""
        # Prepare the data
        data = prepare_custom_data()

        # Feature engineering
        data = engineer_features(data)

        # Generate labels
        labels = generate_labels(data)

        # Split the data
        result = {}
        for segment, (start, end) in segments.items():
            mask = (data.index >= start) & (data.index <= end)
            segment_data = data[mask]
            segment_labels = labels[mask]

            result[segment] = {
                'feature': segment_data,
                'label': segment_labels
            }

        return result

2.3.4 Dataset Evaluation Metrics

Data Quality Metrics

1. Completeness metric

def calculate_completeness(data):
    """Calculate data completeness"""
    total_elements = data.size
    non_null_elements = data.count().sum()
    completeness = non_null_elements / total_elements
    return completeness

2. Consistency metric

def calculate_consistency(data):
    """Calculate data consistency"""
    # Check price logic
    if all(col in data.columns for col in ['$open', '$high', '$low', '$close']):
        valid_high = (data['$high'] >= data[['$open', '$close']].max(axis=1)).sum()
        valid_low = (data['$low'] <= data[['$open', '$close']].min(axis=1)).sum()
        total_records = len(data)

        consistency = (valid_high + valid_low) / (2 * total_records)
        return consistency
    return 1.0

3. Timeliness metric

def calculate_timeliness(data, expected_freq='D'):
    """Calculate data timeliness"""
    # Check the data frequency
    time_diff = data.index.to_series().diff()
    expected_diff = pd.Timedelta(expected_freq)

    # Frequency consistency
    freq_consistency = (time_diff == expected_diff).mean()
    return freq_consistency

Feature Quality Metrics

1. Feature correlation

def calculate_feature_correlation(features, labels):
    """Calculate the correlation between features and the label"""
    correlations = {}
    for col in features.columns:
        corr = features[col].corr(labels)
        correlations[col] = corr

    return pd.Series(correlations)

2. Feature importance

from sklearn.ensemble import RandomForestRegressor

def calculate_feature_importance(features, labels):
    """Calculate feature importance"""
    rf = RandomForestRegressor(n_estimators=100, random_state=42)
    rf.fit(features, labels)

    importance = pd.Series(rf.feature_importances_, index=features.columns)
    return importance.sort_values(ascending=False)

3. Feature stability

def calculate_feature_stability(features, time_periods):
    """Calculate feature stability"""
    stability_scores = {}

    for col in features.columns:
        feature_data = features[col]
        stability = []

        for i in range(len(time_periods) - 1):
            period1 = feature_data[time_periods[i]]
            period2 = feature_data[time_periods[i + 1]]

            # Distribution similarity
            similarity = calculate_distribution_similarity(period1, period2)
            stability.append(similarity)

        stability_scores[col] = np.mean(stability)

    return pd.Series(stability_scores)

Chapter Summary

This chapter took a deep dive into the Qlib data layer, including:

  1. Data framework design: Qlib's storage format, access interfaces, and caching mechanisms
  2. Data retrieval and processing: data retrieval, cleaning, preprocessing, and feature engineering techniques
  3. Quantitative datasets: the characteristics and usage of the Alpha158 and Alpha360 datasets
  4. Data quality checks: data quality evaluation and optimization methods

Exercises

Exercise 1: Data retrieval practice

  1. Download and initialize Qlib data
  2. Retrieve base data for CSI300 constituents
  3. Compute a few simple technical indicators

Exercise 2: Feature engineering

  1. Compute moving averages from price data
  2. Compute indicators such as RSI and Bollinger Bands
  3. Build custom features

Exercise 3: Data quality checks

  1. Write a data quality check script
  2. Analyze data completeness and consistency
  3. Generate a data quality report

Further Reading

  1. Data processing techniques
  2. Python for Data Science (《Python数据科学手册》)
  3. Feature Engineering: From Basics to Practice (《特征工程:从入门到实践》)

  4. Quantitative data

  5. Quantitative Investment Data Mining (《量化投资数据挖掘》)
  6. Analysis of Financial Time Series (《金融时间序列分析》)

  7. Technical indicators

  8. The Encyclopedia of Technical Market Indicators (《技术分析指标大全》)
  9. Quantitative Technical Analysis (《量化技术分析》)