Skip to content

Chapter 1: Quantitative Investment and the Qlib Platform

Notes - The architecture diagrams and capability layers in this chapter are meant to help you understand Qlib's research workflow; they do not imply that the repository contains one-to-one corresponding directories or service modules. - Engineering-layer capabilities related to production deployment, real-time services, and operations usually need to be built by users outside of Qlib.

Learning Objectives

After studying this chapter, you will be able to: - Understand the basic concepts and history of quantitative investment - Grasp the overall architecture of the Qlib platform - Set up a Qlib development environment proficiently - Know the main challenges in quantitative investment and their solutions

1.1 Basic Concepts of Quantitative Investment

1.1.1 Definition and History of Quantitative Investment

What Is Quantitative Investment?

Quantitative Investment is an investment strategy that makes decisions based on mathematics, statistics, and computer science. It builds mathematical models to analyze market data, identify investment opportunities, and execute trading decisions automatically.

Core characteristics: - Data-driven: Based on large volumes of historical and real-time data - Model-based: Uses mathematical models to describe market behavior - Automated: Executes trading decisions automatically via algorithms - Systematic: Follows predefined rules and strategies

The History of Quantitative Investment

Phase 1: Traditional quantitative investing (1970–2000) - 1970s: Modern Portfolio Theory (MPT) is born - 1980s: Multi-factor models rise to prominence - 1990s: Statistical arbitrage and pairs trading

Phase 2: The algorithmic trading era (2000–2010) - High-frequency trading technology develops - Market microstructure research - Algorithmic trading platforms become widespread

Phase 3: AI-driven quantitative investing (2010–present) - Machine learning techniques applied - Deep learning models introduced - Big data and cloud computing support

1.1.2 Quantitative vs. Traditional Investing

Characteristic Traditional Investing Quantitative Investing
Decision-making Subjective judgment Objective models
Data usage Limited data Massive data
Execution speed Manual operations Automated execution
Emotional impact Easily affected by emotions Avoids emotional interference
Scalability Limited Highly scalable
Consistency Varies by individual Highly consistent

1.1.3 Main Challenges and Solutions in Quantitative Investment

Main Challenges

1. Data challenges - Data quality: Market data contains noise, missing values, and errors - Data timeliness: Large volumes of data need real-time processing - Data dimensionality: Integrating multi-dimensional data is difficult

2. Model challenges - Overfitting risk: Models perform well on historical data but poorly in the future - Market dynamics: Market conditions keep changing; models must adapt - Model interpretability: Complex models make decision logic hard to explain

3. Execution challenges - Transaction costs: Frequent trading incurs high costs - Market impact: Large orders move market prices - Liquidity risk: Some assets lack sufficient liquidity

Solutions

1. Data solutions - Data cleaning and preprocessing techniques - Real-time data processing architectures - Multi-source data fusion methods

2. Model solutions - Regularization techniques to prevent overfitting - Online learning and model updates - Model ensembling and combination methods

3. Execution solutions - Smart order routing - Algorithmic trading optimization - Risk control mechanisms

1.2 Qlib Platform Architecture

1.2.1 Overall Framework Design

Qlib is an AI-oriented quantitative investment platform whose architecture follows modular and extensible design principles.

Core Design Philosophy

1. Modular design - Components are developed independently and loosely coupled - Components can be replaced and upgraded - Easier to maintain and extend

2. Data-driven - Data sits at the core - Multiple data sources supported - Efficient data processing

3. AI-oriented - Many machine learning models built in - Deep learning frameworks supported - Reinforcement learning integrated

Overall Architecture Diagram

┌─────────────────────────────────────────────────────────────┐
│                    Qlib Platform                           │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│  │   Data      │  │   Model     │  │  Strategy   │        │
│  │   Layer     │  │   Layer     │  │   Layer     │        │
│  └─────────────┘  └─────────────┘  └─────────────┘        │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│  │  Backtest   │  │  Analysis   │  │   Online    │        │
│  │   Engine    │  │   Report    │  │  Serving    │        │
│  └─────────────┘  └─────────────┘  └─────────────┘        │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│  │  Workflow   │  │     RL      │  │    Meta     │        │
│  │ Management  │  │ Framework   │  │  Learning   │        │
│  └─────────────┘  └─────────────┘  └─────────────┘        │
└─────────────────────────────────────────────────────────────┘

1.2.2 Core Components

Data Layer

Responsibilities: - Data storage and management - Data access interfaces - Data preprocessing and cleaning - Feature engineering support

Key characteristics: - Multiple data formats supported - Efficient data queries - Data caching mechanisms - Real-time data updates

Model Layer

Responsibilities: - Model training and prediction - Feature selection and engineering - Model evaluation and optimization - Model deployment and management

Supported model types: - Traditional machine learning models - Deep learning models - Reinforcement learning models - Ensemble learning models

Strategy Layer

Responsibilities: - Investment strategy design - Signal generation and processing - Portfolio optimization - Risk control

Strategy types: - Multi-factor strategies - Momentum strategies - Arbitrage strategies - High-frequency strategies

Backtest Layer

Responsibilities: - Backtesting on historical data - Performance evaluation - Risk analysis - Trade simulation

Core features: - Event-driven backtest engine - Order management system - Cost calculation - Performance analysis

1.2.3 Platform Advantages and Signature Features

Main Advantages

1. Completeness - Covers the main pipeline from quantitative research to backtest analysis - Servicing, production operations, and business-system integration usually require user-supplied implementations - Multiple investment strategies supported

2. State of the art - Integrates the latest AI techniques - Multiple machine learning paradigms supported - Continuously updated and optimized

3. Ease of use - Clean API design - Rich documentation and examples - Active community support

4. Extensibility - Modular architecture - Custom components supported - Easy to build on

Signature Features

1. Rich model library - Built-in/contributed implementations of many machine learning and deep learning models - Ranges from traditional ML to deep learning - Custom models supported

2. Powerful data processing - Efficient data storage format - Fast data queries - Can integrate with real-time/streaming systems, though the related engineering usually needs to be built by users

3. Flexible strategy framework - Multiple strategy types supported - Nested decision framework - Dynamic strategy adjustment

4. Complete evaluation system - Multiple evaluation metrics - Graphical analysis reports - Strategy comparison analysis

1.3 Environment Setup and Installation

1.3.1 Python Environment Configuration

System Requirements

Supported operating systems: - Linux (recommended) - Windows - macOS

Python version requirements: - Python 3.8+ - Python 3.9 or 3.10 recommended

Environment Preparation

1. Install Python

# Create a virtual environment with conda (recommended)
conda create -n qlib python=3.9
conda activate qlib

# Or use venv
python -m venv qlib_env
source qlib_env/bin/activate  # Linux/macOS
qlib_env\Scripts\activate     # Windows

2. Install base dependencies

pip install numpy pandas scipy
pip install --upgrade cython

1.3.2 Installing Qlib

pip install pyqlib

Pros: - Simple and fast installation - Dependencies handled automatically - Good for getting started quickly

Cons: - Installs the stable release - Latest features not available

# Clone the repository
git clone https://github.com/microsoft/qlib.git
cd qlib

# Install dependencies
pip install numpy
pip install --upgrade cython

# Install qlib
pip install .  # normal install
# or
pip install -e .  # editable (development) install

Pros: - Access to the latest features - Easy to modify and debug - Suited for development environments

Cons: - More involved installation - Possible dependency issues

1.3.3 Docker Deployment

Installing with Docker

1. Pull the image

docker pull pyqlib/qlib_image_stable:stable

2. Start the container

docker run -it --name qlib_container \
  -v /path/to/your/data:/app/data \
  pyqlib/qlib_image_stable:stable

3. Work inside the container

# Enter the container
docker exec -it qlib_container bash

# Run an example
python scripts/get_data.py qlib_data \
  --target_dir ~/.qlib/qlib_data/cn_data \
  --region cn

1.3.4 Data Preparation and Initialization

Downloading Data

1. Getting the data

# Download the data
wget https://github.com/chenditc/investment_data/releases/latest/download/qlib_bin.tar.gz

# Extract the data
mkdir -p ~/.qlib/qlib_data/cn_data
tar -zxvf qlib_bin.tar.gz -C ~/.qlib/qlib_data/cn_data --strip-components=1
rm -f qlib_bin.tar.gz

2. Fetching data via the module interface

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

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

Data Initialization

1. Basic initialization

import qlib
from qlib.constant import REG_CN

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

2. Verify the installation

from qlib.data import D

# Get the trading calendar
calendar = D.calendar(start_time='2020-01-01', end_time='2020-12-31', freq='day')
print("Trading calendar:", calendar[:5])

# Get the stock list
instruments = D.instruments('csi300')
stock_list = D.list_instruments(instruments=instruments, 
                               start_time='2020-01-01', 
                               end_time='2020-12-31', 
                               as_list=True)
print("Stock list:", stock_list[:5])

1.3.5 Environment Verification

Quick Verification Script

# test_qlib_installation.py
import qlib
from qlib.data import D
from qlib.constant import REG_CN

def test_qlib_installation():
    """Test whether qlib was installed successfully"""
    try:
        # Initialize
        qlib.init(mount_path="~/.qlib/qlib_data/cn_data", region=REG_CN)
        print("✓ Qlib initialized successfully")

        # Test data access
        calendar = D.calendar(start_time='2020-01-01', end_time='2020-01-10', freq='day')
        print(f"✓ Data access OK, calendar length: {len(calendar)}")

        # Test feature retrieval
        instruments = ['SH600000']
        fields = ['$close', '$volume']
        data = D.features(instruments, fields, start_time='2020-01-01', end_time='2020-01-10', freq='day')
        print(f"✓ Feature retrieval OK, data shape: {data.shape}")

        print("🎉 Qlib environment configured successfully!")
        return True

    except Exception as e:
        print(f"❌ Environment configuration failed: {e}")
        return False

if __name__ == "__main__":
    test_qlib_installation()

Troubleshooting Common Problems

1. Installation failure

# Upgrade pip
pip install --upgrade pip

# Install build tools
pip install wheel setuptools

# Reinstall
pip install pyqlib

2. Data download failure

# Use an alternative data source
python scripts/get_data.py qlib_data \
  --target_dir ~/.qlib/qlib_data/cn_data \
  --region cn \
  --source yahoo

3. Out of memory

# Reduce the data range
python -m qlib.run.get_data qlib_data \
  --target_dir ~/.qlib/qlib_data/cn_data \
  --region cn \
  --start_date 2020-01-01 \
  --end_date 2023-12-31

Chapter Summary

This chapter introduced the basic concepts of quantitative investment and the overall architecture of the Qlib platform. After studying it, you should be able to:

  1. Understand quantitative investing: grasp its definition, history, and main challenges
  2. Know the Qlib architecture: understand the platform's overall design and core components
  3. Set up a development environment: install and configure Qlib successfully
  4. Prepare base data: download and initialize the required datasets

Exercises

Exercise 1: Environment verification

Run the provided test script and make sure the Qlib environment is configured correctly.

Exercise 2: Data exploration

Use the Qlib API to obtain the following: - The CSI300 constituent stock list - Closing price and volume data for one stock - A simple technical indicator (e.g., a moving average)

Exercise 3: Reading the documentation

Read the following parts of the official Qlib documentation: - Quick start guide - Data layer documentation - API reference

Further Reading

  1. Quantitative investment theory
  2. Active Portfolio Management
  3. Quantitative Investment Strategies and Techniques (《量化投资策略与技术》)

  4. Qlib-related papers

  5. "Qlib: An AI-oriented Quantitative Investment Platform"
  6. Related academic papers and reports

  7. Online resources

  8. Official Qlib documentation: https://qlib.readthedocs.io/
  9. GitHub repository: https://github.com/microsoft/qlib
  10. Community discussions: https://gitter.im/Microsoft/qlib