Guide to the Qlib Scripts Directory¶
Overview¶
The Qlib scripts directory contains important utility scripts for data management, system diagnostics, and data collection. These scripts are the infrastructure of the Qlib ecosystem, responsible for data acquisition, conversion, validation, and maintenance.
Directory Structure¶
scripts/
├── README.md # documentation for the scripts directory
├── get_data.py # data download tool
├── check_data_health.py # data health check tool
├── dump_bin.py # data format conversion tool (CSV -> Binary)
├── dump_pit.py # point-in-time data conversion tool
├── check_dump_bin.py # binary data validation tool
├── collect_info.py # system information collection tool
└── data_collector/ # data collector modules
├── base.py # data collection base class
├── utils.py # common utility functions
├── yahoo/ # Yahoo Finance data collector
├── cn_index/ # Chinese index data collector
├── us_index/ # US index data collector
├── fund/ # fund data collector
├── crypto/ # cryptocurrency data collector
├── pit/ # point-in-time data collector
├── baostock_5min/ # baostock 5-minute data collector
├── br_index/ # Brazilian index data collector
└── contrib/ # contribution modules
├── future_trading_date_collector/ # futures trading date collector
└── fill_cn_1min_data/ # Chinese 1-minute data filling tool
Core Scripts in Detail¶
1. Data Download Tool (get_data.py)¶
Functionality¶
- Downloads preprocessed Qlib-format data from official sources
- Supports data for multiple markets and time frequencies
Usage¶
# Download Chinese market daily data
python get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn
# Download Chinese market 1-minute data (for high-frequency strategies)
python get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data_1min --region cn --interval 1min
# Download US market data
python get_data.py qlib_data --target_dir ~/.qlib/qlib_data/us_data --region us
# Download the simplified Chinese dataset
python get_data.py qlib_data --name qlib_data_simple --target_dir ~/.qlib/qlib_data/cn_data --region cn
# Show help information
python get_data.py qlib_data --help
Technical Highlights¶
- Command-line interface based on the
firelibrary - Downloads data by calling the
qlib.tests.data.GetDataclass - Supports resumable downloads and incremental updates
2. Data Health Check Tool (check_data_health.py)¶
Functionality¶
- Checks dataset integrity and correctness
- Identifies missing data, abnormal fluctuations, and other issues
- Supports both CSV files and Qlib binary format
Core Check Items¶
- Field completeness: Checks that the fields
["open", "high", "low", "close", "volume"]exist - Missing data: Identifies NaN or empty values
- Abnormal fluctuations: Detects abnormal jumps in prices and volume
- Price anomaly threshold: default 0.5 (50%)
- Volume anomaly threshold: default 3 (300%)
- Missing factors: Checks the completeness of technical indicator factors
Usage Examples¶
# Check Qlib binary data
python check_data_health.py check_data --qlib_dir ~/.qlib/qlib_data/cn_data
# Check CSV files
python check_data_health.py check_data --csv_path /path/to/csv/files
# Customize check parameters
python check_data_health.py check_data \
--qlib_dir ~/.qlib/qlib_data/cn_data \
--large_step_threshold_price 0.3 \
--large_step_threshold_volume 2 \
--missing_data_num 5
Technical Implementation¶
class DataHealthChecker:
def __init__(self,
csv_path=None,
qlib_dir=None,
freq="day",
large_step_threshold_price=0.5,
large_step_threshold_volume=3,
missing_data_num=0):
# initialize the checker configuration
3. Data Format Conversion Tool (dump_bin.py)¶
Functionality¶
- Converts raw CSV-format data into Qlib's proprietary binary format
- Optimizes data storage and access performance
- Supports incremental updates and parallel processing
Key Features¶
- High performance: Multi-threaded/multi-process parallel conversion
- Flexible configuration: Supports custom field mapping and filtering
- Incremental updates: Supports an update mode that only processes changed data
- Backup mechanism: Automatically backs up original data
Key Parameters¶
class DumpDataBase:
INSTRUMENTS_START_FIELD = "start_datetime"
INSTRUMENTS_END_FIELD = "end_datetime"
CALENDARS_DIR_NAME = "calendars" # trading calendar directory
FEATURES_DIR_NAME = "features" # feature data directory
INSTRUMENTS_DIR_NAME = "instruments" # stock list directory
DUMP_FILE_SUFFIX = ".bin" # binary file suffix
DAILY_FORMAT = "%Y-%m-%d" # daily data format
HIGH_FREQ_FORMAT = "%Y-%m-%d %H:%M:%S" # high-frequency data format
Usage Examples¶
# Basic conversion
python dump_bin.py dump_data_base \
--csv_path /path/to/csv/data \
--qlib_dir ~/.qlib/qlib_data/custom \
--max_workers 8
# Incremental update mode
python dump_bin.py dump_data_base \
--csv_path /path/to/csv/data \
--qlib_dir ~/.qlib/qlib_data/custom \
--mode update
4. Point-in-Time Data Conversion Tool (dump_pit.py)¶
Functionality¶
- Handles Point-in-Time (PIT) data
- Ensures backtests use only data that was historically available, avoiding look-ahead bias
- Supports fundamental data such as financial statements and analyst forecasts
Use Cases¶
- Time alignment of financial statement data
- Processing of analyst ratings and forecast data
- Historical reconstruction of fundamental factors
5. System Information Collection Tool (collect_info.py)¶
Functionality¶
- Collects system environment information
- Checks dependency package versions
- Used for issue diagnosis and environment verification
Usage¶
# Collect all information
python collect_info.py all
# Collect system information
python collect_info.py sys
# Collect Python information
python collect_info.py py
# Collect Qlib-related information
python collect_info.py qlib
Output Information¶
- System information: operating system, architecture, version
- Python information: Python version
- Qlib information: Qlib version and versions of all dependency packages
Data Collector Modules (data_collector/)¶
Architecture Design¶
The data collectors use an object-oriented design, providing a unified interface and an extensible architecture:
# Base class structure
class BaseCollector:
"""Data collection base class"""
def run(self):
# execute the data collection process
pass
class BaseNormalize:
"""Data normalization base class"""
def normalize(self):
# data normalization processing
pass
class BaseRun:
"""Command-line interface base class"""
pass
Supported Data Sources¶
1. Yahoo Finance (yahoo/)¶
- Data types: US and Chinese stock data
- Data frequency: daily, weekly, monthly
- Data fields: OHLCV (open, high, low, close, volume)
- Use cases: acquiring basic individual stock data
2. Chinese Indexes (cn_index/)¶
- Data source: CSI Index official website (http://www.csindex.com.cn)
- Supported indexes: CSI300, CSI100, CSI500, CSI800, etc.
- Data types: index constituent lists, weights, historical prices
3. US Indexes (us_index/)¶
- Data source: Wikipedia, official websites
- Supported indexes: SP500, NASDAQ100, DJIA, SP400
- Data types: index constituent lists, basic information
4. Fund Data (fund/)¶
- Data source: Eastmoney (http://fund.eastmoney.com)
- Data types: fund NAV, size, holdings, etc.
- Use cases: fund strategy research, performance benchmarks
5. Cryptocurrencies (crypto/)¶
- Data types: price data for major cryptocurrencies
- Data frequency: multiple time frequencies supported
- Use cases: digital asset quantitative strategies
6. Point-in-Time Data (pit/)¶
- Data types: fundamental data (financial reports, forecasts, etc.)
- Time alignment: ensures historical availability
- Use cases: fundamental quantitative strategies
Developing Custom Data Collectors¶
Development Steps¶
-
Create the directory structure
mkdir scripts/data_collector/custom_source cd scripts/data_collector/custom_source -
Implement the collector class (
collector.py)import sys from pathlib import Path # Add the parent directory to the path CUR_DIR = Path(__file__).resolve().parent sys.path.append(str(CUR_DIR.parent.parent)) from data_collector.base import BaseCollector, BaseNormalize, BaseRun class CustomCollector(BaseCollector): def __init__(self, save_dir="./custom_data"): self.save_dir = save_dir def run(self): """Implement the data collection logic""" # 1. fetch data from the source raw_data = self.fetch_data() # 2. clean the data clean_data = self.clean_data(raw_data) # 3. save the data self.save_data(clean_data) def fetch_data(self): """Fetch raw data from the data source""" pass def clean_data(self, data): """Data cleaning and preprocessing""" pass def save_data(self, data): """Save the processed data""" pass class CustomNormalize(BaseNormalize): def __init__(self, source_dir, target_dir): self.source_dir = source_dir self.target_dir = target_dir def normalize(self): """Normalize data into Qlib format""" # implement the data format conversion pass class Run(BaseRun): def __init__(self): # set up the available subcommands pass -
Add a documentation file (
README.md)# Custom Data Collector ## Description Describe the data source and the collector's functionality ## Usage ```bash python collector.py download --save_dir ./data python collector.py normalize --source_dir ./data --target_dir ~/.qlib/qlib_data/custom
Dependencies¶
List the required third-party libraries
4. **Add a dependency file** (`requirements.txt`)
#### Best Practices
1. **Error handling**: Implement a comprehensive exception handling mechanism
2. **Logging**: Use `loguru` to record the processing workflow
3. **Configuration management**: Support both configuration files and command-line arguments
4. **Data validation**: Implement data quality checks
5. **Performance optimization**: Use multithreading/async processing to improve efficiency
## Data Format Specifications
### Standard Data Structure
Qlib requires data to follow a specific directory structure and format:
### Data Field Requirements
#### Basic Price and Volume Data
- **$close**: closing price (required)
- **$open**: opening price (required)
- **$high**: highest price (required)
- **$low**: lowest price (required)
- **$volume**: trading volume (required)
- **$change**: price change percentage (optional)
- **$factor**: adjustment factor (defaults to 1)
#### Technical Indicators
- **$vwap**: volume-weighted average price
- **$amount**: trading amount
- Other custom technical indicators
### Data Quality Standards
1. **Temporal continuity**: trading-day data should have no gaps
2. **Data consistency**: OHLC data should satisfy logical relationships (H>=C>=L, H>=O>=L)
3. **Outlier handling**: identify and handle abnormal price jumps
4. **Adjustment handling**: correctly process corporate actions such as dividends and stock splits
## Practical Examples
### Scenario 1: Downloading and Preparing the Data Environment
```bash
# 1. Download Chinese market data
cd scripts
python get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn
# 2. Check data health status
python check_data_health.py check_data --qlib_dir ~/.qlib/qlib_data/cn_data
# 3. Initialize Qlib in Python
import qlib
from qlib.constant import REG_CN
# Initialize Qlib
qlib.init(provider_uri="~/.qlib/qlib_data/cn_data", region=REG_CN)
# Verify data availability
from qlib.data import D
instruments = D.instruments()
print(f"Number of available stocks: {len(instruments)}")
Scenario 2: Custom Data Processing Workflow¶
# 1. Collect raw CSV data (assumed to already exist)
# Data structure: date,symbol,open,high,low,close,volume
# 2. Convert to Qlib format
python dump_bin.py dump_data_base \
--csv_path ./raw_csv_data \
--qlib_dir ~/.qlib/qlib_data/custom \
--freq day \
--max_workers 8
# 3. Validate the conversion result
python check_dump_bin.py --qlib_dir ~/.qlib/qlib_data/custom
# 4. Check data quality
python check_data_health.py check_data --qlib_dir ~/.qlib/qlib_data/custom
Scenario 3: System Diagnostics and Troubleshooting¶
# 1. Collect system information
python collect_info.py all > system_info.txt
# 2. Check a specific issue
python check_data_health.py check_data \
--qlib_dir ~/.qlib/qlib_data/cn_data \
--large_step_threshold_price 0.2 # stricter anomaly detection
# 3. Verify data integrity
python check_dump_bin.py --qlib_dir ~/.qlib/qlib_data/cn_data --detailed
Advanced Usage¶
1. Data Update Strategies¶
# Incrementally update existing data
python dump_bin.py dump_data_base \
--csv_path ./new_data \
--qlib_dir ~/.qlib/qlib_data/cn_data \
--mode update \
--backup_dir ./backup
# Validate the update result
python check_data_health.py check_data \
--qlib_dir ~/.qlib/qlib_data/cn_data
2. Multi-Market Data Management¶
# Manage data for multiple markets
import qlib
# Chinese market
qlib.init(provider_uri="~/.qlib/qlib_data/cn_data", region="cn")
# ... perform Chinese market analysis
# Switch to the US market
qlib.init(provider_uri="~/.qlib/qlib_data/us_data", region="us")
# ... perform US market analysis
3. Performance Optimization Tips¶
- Parallel processing: Use the
--max_workersparameter to optimize conversion speed - Memory management: Process large datasets in batches
- Storage optimization: Use SSD storage to improve I/O performance
- Network optimization: Use proxies or mirror sources to speed up downloads
Common Issues and Solutions¶
1. Data Download Problems¶
Problem: network connection failure or interrupted downloads Solutions: - Check the network connection - Use a proxy server - Consider using crowdsourced data sources
2. Data Format Problems¶
Problem: CSV data format does not meet requirements Solutions: - Check field name mappings - Adjust date format settings - Use a custom normalizer
3. Performance Problems¶
Problem: slow data conversion Solutions: - Increase the number of parallel worker processes - Use SSD storage - Optimize memory usage
4. Data Quality Problems¶
Problem: large amounts of abnormal data Solutions: - Adjust anomaly detection thresholds - Implement custom data cleaning logic - Validate against multiple data sources
Summary¶
The Qlib scripts directory provides a complete data management ecosystem, with end-to-end tooling covering data acquisition, conversion, validation, and maintenance. By using these tools properly, you can:
- Rapid deployment: Quickly set up a research environment with official data
- Custom extension: Develop your own data collectors
- Quality assurance: Ensure data quality through health checks
- Performance optimization: Store data in an efficient binary format
- Issue diagnosis: Quickly locate problems through system information collection
These tools are the infrastructure of Qlib quantitative research, and mastering them is essential for conducting quantitative research efficiently.