数据层:数据框架与使用¶
简介¶
Data Layer
提供了用户友好的API来管理和检索数据。它提供了高性能的数据基础设施。
该层专为量化投资设计。例如,用户可以通过 Data Layer
轻松构建公式化阿尔法因子。更多细节请参阅 构建公式化阿尔法因子 。
Data Layer
的介绍包含以下部分:
数据准备
数据API
数据加载器
数据处理器
数据集
缓存
数据与缓存文件结构
以下是Qlib数据工作流的典型示例:
用户下载数据并将其转换为Qlib格式(文件后缀为`.bin`)。此步骤通常只将基础数据(如OHLCV)存储在磁盘上
基于Qlib表达式引擎创建基础特征(例如"Ref($close, 60) / $close"表示过去60个交易日的收益率)。表达式引擎支持的运算符可查看 此处。此步骤通常由 数据加载器 实现,它是 数据处理器 的组成部分
如需更复杂的数据处理(如数据标准化),Data Handler 支持用户自定义处理器(预定义处理器参见 此处)。这些处理器与表达式引擎中的运算符不同,专为难以通过表达式运算符实现的复杂数据处理方法设计
最后,数据集 负责从Data Handler处理后的数据中准备模型专用数据集
数据准备¶
Qlib格式数据¶
We've specially designed a data structure to manage financial data, please refer to the File storage design section in Qlib paper for detailed information. 此类数据将以`.bin`为文件后缀存储(我们称之为`.bin`文件、.bin`格式或qlib格式)。.bin`文件专为金融数据的科学计算设计。
Qlib
提供两种现成数据集,可通过此 链接 获取:
此外,Qlib
还提供高频数据集。用户可通过此 链接 运行高频数据集示例。
Qlib格式数据集¶
Qlib
提供了一个现成的 .bin 格式数据集,用户可以使用脚本 scripts/get_data.py
下载中国股票数据集如下。用户也可以使用 numpy 加载 .bin 文件来验证数据。
由于价格成交量数据经过了**复权**处理 (复权价格),它们与实际交易价格看起来不同。因此您可能会发现不同数据源的复权价格存在差异,这是因为不同数据源采用的复权方式可能不同。Qlib 在复权时会将每只股票的首个交易日价格标准化为1。
用户可以利用 $factor 获取原始交易价格(例如通过 $close / $factor 获取原始收盘价)。
以下是关于 Qlib 价格复权的一些讨论:
# download 1d
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn
# download 1min
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/qlib_cn_1min --region cn --interval 1min
除了中国股票数据外,Qlib
还包含一个美国股票数据集,可通过以下命令下载:
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/us_data --region us
After running the above command, users can find china-stock and us-stock data in Qlib
format in the ~/.qlib/qlib_data/cn_data
directory and ~/.qlib/qlib_data/us_data
directory respectively.
Qlib
还在 scripts/data_collector
中提供了脚本,帮助用户从互联网爬取最新数据并转换为 qlib 格式。
当使用该数据集初始化 Qlib
后,用户可以用它构建和评估自己的模型。更多详情请参阅 初始化。
日频数据的自动更新¶
建议用户先手动更新一次数据(--trading_date 2021-05-25),然后设置为自动更新。
更多信息请参考:雅虎收集器
- 每个交易日自动更新数据到 "qlib" 目录(Linux)
使用 crontab:crontab -e
设置定时任务:
* * * * 1-5 python <script path> update_data_to_bin --qlib_data_1d_dir <user data dir>
脚本路径:scripts/data_collector/yahoo/collector.py
数据的手动更新
python scripts/data_collector/yahoo/collector.py update_data_to_bin --qlib_data_1d_dir <user data dir> --trading_date <start date> --end_date <end date>
trading_date: 交易日开始时间
end_date: 交易日结束时间(不包含)
将CSV和Parquet格式转换为Qlib格式¶
Qlib
提供了脚本 scripts/dump_bin.py
用于将 任何 CSV或Parquet格式的数据转换为 .bin 文件(Qlib
格式),只要它们符合正确的格式要求。
除了下载准备好的演示数据外,用户还可以直接从Collector下载演示数据作为CSV格式的参考。 以下是一些示例:
- 对于日线数据:
python scripts/get_data.py download_data --file_name csv_data_cn.zip --target_dir ~/.qlib/csv_data/cn_data
- 对于1分钟数据:
python scripts/data_collector/yahoo/collector.py download_data --source_dir ~/.qlib/stock_data/source/cn_1min --region CN --start 2021-05-20 --end 2021-05-23 --delay 0.1 --interval 1min --limit_nums 10
用户也可以提供自己的CSV或Parquet格式数据。但数据 必须满足 以下条件:
CSV或Parquet文件以特定股票命名 或 CSV/Parquet文件包含股票名称列
以股票命名CSV或Parquet文件:SH600000.csv、AAPL.csv 或 SH600000.parquet、`AAPL.parquet`(大小写不敏感)。
CSV或Parquet文件包含股票名称列。用户在转储数据时 必须 指定列名。以下是一个示例:
python scripts/dump_bin.py dump_all ... --symbol_field_name symbol --file_suffix <.csv or .parquet>
数据需符合以下格式:
symbol
close
SH600000
120
CSV或Parquet文件**必须**包含日期列,在转储数据时用户必须指定日期列名。示例如下:
python scripts/dump_bin.py dump_all ... --date_field_name date --file_suffix <.csv or .parquet>
数据需符合以下格式:
symbol
date
close
open
volume
SH600000
2020-11-01
120
121
12300000
SH600000
2020-11-02
123
120
12300000
假设用户已将CSV或Parquet格式数据准备在目录``~/.qlib/my_data``中,可运行以下命令开始转换。
python scripts/dump_bin.py dump_all --data_path ~/.qlib/my_data --qlib_dir ~/.qlib/qlib_data/ --include_fields open,close,high,low,volume,factor --file_suffix <.csv or .parquet>
如需了解将数据转储为`.bin`文件时支持的其他参数,用户可运行以下命令查看相关信息:
python scripts/dump_bin.py dump_all --help
After conversion, users can find their Qlib format data in the directory ~/.qlib/qlib_data/.
备注
--include_fields 的参数应与CSV或Parquet文件的列名对应。Qlib
提供的数据集列名至少应包含开盘价、收盘价、最高价、最低价、成交量和复权因子。
- open
复权后的开盘价
- close
复权后的收盘价
- high
复权后的最高价
- low
复权后的最低价
- volume
复权后的成交量
- factor
复权因子。通常,
factor = 复权价格 / 原始价格
,复权价格`参考:`split adjusted
按照 Qlib 数据处理的惯例,如果股票停牌,open、close、high、low、volume、money 和 factor 将被设为NaN。 如果你想使用无法通过OHLCV计算的alpha因子(如PE、EPS等),可以将其与OHLCV一起添加到CSV或Parquet文件中,然后转储为Qlib格式数据。
检查数据健康状况¶
Qlib
提供了一个脚本来检查数据的健康状况。
主要检查点如下
检查DataFrame中是否有数据缺失。
检查OHLCV列中是否存在超过阈值的大幅阶跃变化。
检查DataFrame中是否缺少必需列(OHLCV)。
检查DataFrame中是否缺少'factor'列。
你可以运行以下命令来检查数据是否健康。
- 对于日线数据:
python scripts/check_data_health.py check_data --qlib_dir ~/.qlib/qlib_data/cn_data
- 对于1分钟数据:
python scripts/check_data_health.py check_data --qlib_dir ~/.qlib/qlib_data/cn_data_1min --freq 1min
当然,你也可以添加一些参数来调整测试结果。
可用参数如下。
freq: 数据频率。
large_step_threshold_price: 允许的最大价格变化
large_step_threshold_volume: 允许的最大成交量变化。
missing_data_num: 允许数据为null的最大值。
你可以运行以下命令来检查数据是否健康。
- 对于日线数据:
python scripts/check_data_health.py check_data --qlib_dir ~/.qlib/qlib_data/cn_data --missing_data_num 30055 --large_step_threshold_volume 94485 --large_step_threshold_price 20
- 针对1分钟数据:
python scripts/check_data_health.py check_data --qlib_dir ~/.qlib/qlib_data/cn_data --freq 1min --missing_data_num 35806 --large_step_threshold_volume 3205452000000 --large_step_threshold_price 0.91
股票池(市场)¶
Qlib
defines stock pool as stock list and their date ranges. Predefined stock pools (e.g. csi300) may be imported as follows.
python collector.py --index_name CSI300 --qlib_dir <user qlib data dir> --method parse_instruments
多股票模式¶
Qlib
目前为用户提供两种不同的股票模式:中国股票模式和美国股票模式。以下是这两种模式的一些不同设置:
地区 |
交易单位 |
涨跌幅限制 |
---|---|---|
中国 |
100 |
0.099 |
美国 |
1 |
无 |
`交易单位`定义了每次交易可使用的股票数量单位,`涨跌幅限制`定义了股票价格波动的百分比边界。
- 如果用户使用``Qlib``的中国股票模式,需要准备中国股票数据。用户可以按照以下步骤使用中国股票模式:
下载qlib格式的中国股票数据,请参考章节`Qlib格式数据集 <#qlib-format-dataset>`_。
- 初始化``Qlib``为中国股票模式
假设用户将Qlib格式数据下载到目录``~/.qlib/qlib_data/cn_data``中,用户只需按如下方式初始化``Qlib``。
from qlib.constant import REG_CN qlib.init(provider_uri='~/.qlib/qlib_data/cn_data', region=REG_CN)
- 如果用户使用``Qlib``的美国股票模式,需要准备美国股票数据。``Qlib``也提供了下载美国股票数据的脚本。用户可以按照以下步骤使用美国股票模式:
下载qlib格式的美国股票数据,请参考章节`Qlib格式数据集 <#qlib-format-dataset>`_。
- 初始化``Qlib``为美国股票模式
假设用户将Qlib格式数据准备在目录``~/.qlib/qlib_data/us_data``中,用户只需按如下方式初始化``Qlib``。
from qlib.config import REG_US qlib.init(provider_uri='~/.qlib/qlib_data/us_data', region=REG_US)
备注
我们非常欢迎提交新数据源的PR!用户可以提交数据爬取代码作为PR,类似`这里的示例 <https://github.com/microsoft/qlib/tree/main/scripts>`_。然后我们将使用该代码在我们的服务器上创建数据缓存,其他用户可以直接使用。
数据API¶
数据获取¶
用户可以使用``qlib.data``中的API来获取数据,详情请参阅`数据获取 <../start/getdata.html>`_。
特征¶
``Qlib``提供`Feature`和`ExpressionOps`来根据用户需求获取特征。
- Feature
从数据提供者加载数据。用户可以获取如`$high`、$low、$open、$close`等特征,这些应与--include_fields`参数对应,详情请参阅章节`将CSV格式转换为Qlib格式 <#converting-csv-format-into-qlib-format>`_。
- ExpressionOps
ExpressionOps`将使用运算符进行特征构建。 要了解更多关于``Operator``的信息,请参阅`Operator API。 此外,
Qlib``支持用户定义自定义``Operator
,示例见``tests/test_register_ops.py``。
要了解更多关于``Feature``的信息,请参阅`Feature API <../reference/api.html#module-qlib.data.base>`_。
过滤器¶
``Qlib``提供`NameDFilter`和`ExpressionDFilter`来根据用户需求筛选证券。
- NameDFilter
名称动态证券过滤器。基于规范化的名称格式筛选证券。需要一个名称规则正则表达式。
- ExpressionDFilter
表达式动态证券过滤器。基于特定表达式筛选证券。需要一个指示特定特征字段的表达式规则。
基础特征过滤器: rule_expression = '$close/$open>5'
横截面特征过滤器 : rule_expression = '$rank($close)<10'
时间序列特征过滤器: rule_expression = '$Ref($close, 3)>100'
以下是一个简单示例,展示如何在基础``Qlib``工作流配置文件中使用过滤器:
filter: &filter
filter_type: ExpressionDFilter
rule_expression: "Ref($close, -2) / Ref($close, -1) > 1"
filter_start_time: 2010-01-01
filter_end_time: 2010-01-07
keep: False
data_handler_config: &data_handler_config
start_time: 2010-01-01
end_time: 2021-01-22
fit_start_time: 2010-01-01
fit_end_time: 2015-12-31
instruments: *market
filter_pipe: [*filter]
要了解更多关于 Filter
的信息,请参阅 Filter API。
参考¶
要了解更多关于 Data API
的信息,请参阅 Data API。
Data Loader¶
Data Loader
in Qlib
is designed to load raw data from the original data source. It will be loaded and used in the Data Handler
module.
QlibDataLoader¶
The QlibDataLoader
class in Qlib
is such an interface that allows users to load raw data from the Qlib
data source.
StaticDataLoader¶
The StaticDataLoader
class in Qlib
is such an interface that allows users to load raw data from file or as provided.
接口¶
以下是 QlibDataLoader
类的一些接口:
- class qlib.data.dataset.loader.DataLoader
DataLoader is designed for loading raw data from original data source.
- abstractmethod load(instruments, start_time=None, end_time=None) DataFrame
load the data as pd.DataFrame.
Example of the data (The multi-index of the columns is optional.):
feature label $close $volume Ref($close, 1) Mean($close, 3) $high-$low LABEL0 datetime instrument 2010-01-04 SH600000 81.807068 17145150.0 83.737389 83.016739 2.741058 0.0032 SH600004 13.313329 11800983.0 13.313329 13.317701 0.183632 0.0042 SH600005 37.796539 12231662.0 38.258602 37.919757 0.970325 0.0289
- 参数:
instruments (str or dict) -- it can either be the market name or the config file of instruments generated by InstrumentProvider. If the value of instruments is None, it means that no filtering is done.
start_time (str) -- start of the time range.
end_time (str) -- end of the time range.
- 返回:
data load from the under layer source
- 返回类型:
pd.DataFrame
- 抛出:
KeyError: -- if the instruments filter is not supported, raise KeyError
API¶
要了解更多关于 Data Loader
的信息,请参阅 数据加载器 API。
Data Handler¶
Qlib
中的 Data Handler
模块旨在处理那些大多数模型都会用到的通用数据处理方法。
用户可以通过 qrun
在自动化工作流中使用 Data Handler
,更多细节请参阅 工作流:工作流管理。
DataHandlerLP¶
除了在 qrun
的自动化工作流中使用 Data Handler
外,Data Handler
还可以作为独立模块使用,用户可以通过它轻松地预处理数据(标准化、去除NaN值等)并构建数据集。
为此,Qlib
提供了一个基类 qlib.data.dataset.DataHandlerLP。该类的核心思想是:我们将拥有一些可学习的 处理器s
,它们能够学习数据处理的参数(例如zscore归一化的参数)。当新数据到来时,这些'训练过'的 Processors
就可以处理新数据,从而使得高效处理实时数据成为可能。关于 Processors
的更多信息将在下一小节中列出。
接口¶
以下是 DataHandlerLP
提供的一些重要接口:
- class qlib.data.dataset.handler.DataHandlerLP(instruments=None, start_time=None, end_time=None, data_loader: dict | str | DataLoader = None, infer_processors: List = [], learn_processors: List = [], shared_processors: List = [], process_type='append', drop_raw=False, **kwargs)
Motivation: - For the case that we hope using different processor workflows for learning and inference;
DataHandler with (L)earnable (P)rocessor
This handler will produce three pieces of data in pd.DataFrame format.
DK_R / self._data: the raw data loaded from the loader
DK_I / self._infer: the data processed for inference
DK_L / self._learn: the data processed for learning model.
The motivation of using different processor workflows for learning and inference Here are some examples.
The instrument universe for learning and inference may be different.
The processing of some samples may rely on label (for example, some samples hit the limit may need extra processing or be dropped).
These processors only apply to the learning phase.
Tips for data handler
To reduce the memory cost
drop_raw=True: this will modify the data inplace on raw data;
Please note processed data like self._infer or self._learn are concepts different from segments in Qlib's Dataset like "train" and "test"
Processed data like self._infer or self._learn are underlying data processed with different processors
segments in Qlib's Dataset like "train" and "test" are simply the time segmentations when querying data("train" are often before "test" in time-series).
For example, you can query data._infer processed by infer_processors in the "train" time segmentation.
- __init__(instruments=None, start_time=None, end_time=None, data_loader: dict | str | DataLoader = None, infer_processors: List = [], learn_processors: List = [], shared_processors: List = [], process_type='append', drop_raw=False, **kwargs)
- 参数:
infer_processors (list) --
list of <description info> of processors to generate data for inference
example of <description info>:
1) classname & kwargs: { "class": "MinMaxNorm", "kwargs": { "fit_start_time": "20080101", "fit_end_time": "20121231" } } 2) Only classname: "DropnaFeature" 3) object instance of Processor
learn_processors (list) -- similar to infer_processors, but for generating data for learning models
process_type (str) --
PTYPE_I = 'independent'
self._infer will be processed by infer_processors
self._learn will be processed by learn_processors
PTYPE_A = 'append'
self._infer will be processed by infer_processors
self._learn will be processed by infer_processors + learn_processors
(e.g. self._infer processed by learn_processors )
drop_raw (bool) -- Whether to drop the raw data
- fit()
fit data without processing the data
- fit_process_data()
fit and process data
The input of the fit will be the output of the previous processor
- process_data(with_fit: bool = False)
process_data data. Fun processor.fit if necessary
Notation: (data) [processor]
# data processing flow of self.process_type == DataHandlerLP.PTYPE_I
(self._data)-[shared_processors]-(_shared_df)-[learn_processors]-(_learn_df) \ -[infer_processors]-(_infer_df)
# data processing flow of self.process_type == DataHandlerLP.PTYPE_A
(self._data)-[shared_processors]-(_shared_df)-[infer_processors]-(_infer_df)-[learn_processors]-(_learn_df)
- 参数:
with_fit (bool) -- The input of the fit will be the output of the previous processor
- config(processor_kwargs: dict = None, **kwargs)
configuration of data. # what data to be loaded from data source
This method will be used when loading pickled handler from dataset. The data will be initialized with different time range.
- setup_data(init_type: str = 'fit_seq', **kwargs)
Set up the data in case of running initialization for multiple time
- 参数:
init_type (str) -- The type IT_* listed above.
enable_cache (bool) --
default value is false:
if enable_cache == True:
the processed data will be saved on disk, and handler will load the cached data from the disk directly when we call init next time
- fetch(selector: Timestamp | slice | str = slice(None, None, None), level: str | int = 'datetime', col_set='__all', data_key: Literal['raw', 'infer', 'learn'] = 'infer', squeeze: bool = False, proc_func: Callable = None) DataFrame
fetch data from underlying data source
- 参数:
selector (Union[pd.Timestamp, slice, str]) -- describe how to select data by index.
level (Union[str, int]) -- which index level to select the data.
col_set (str) -- select a set of meaningful columns.(e.g. features, columns).
data_key (str) -- the data to fetch: DK_*.
proc_func (Callable) -- please refer to the doc of DataHandler.fetch
- 返回类型:
pd.DataFrame
- get_cols(col_set='__all', data_key: Literal['raw', 'infer', 'learn'] = 'infer') list
get the column names
- 参数:
col_set (str) -- select a set of meaningful columns.(e.g. features, columns).
data_key (DATA_KEY_TYPE) -- the data to fetch: DK_*.
- 返回:
list of column names
- 返回类型:
list
- classmethod cast(handler: DataHandlerLP) DataHandlerLP
Motivation
A user creates a datahandler in his customized package. Then he wants to share the processed handler to other users without introduce the package dependency and complicated data processing logic.
This class make it possible by casting the class to DataHandlerLP and only keep the processed data
- 参数:
handler (DataHandlerLP) -- A subclass of DataHandlerLP
- 返回:
the converted processed data
- 返回类型:
- classmethod from_df(df: DataFrame) DataHandlerLP
Motivation: - When user want to get a quick data handler.
The created data handler will have only one shared Dataframe without processors. After creating the handler, user may often want to dump the handler for reuse Here is a typical use case
from qlib.data.dataset import DataHandlerLP dh = DataHandlerLP.from_df(df) dh.to_pickle(fname, dump_all=True)
TODO: - The StaticDataLoader is quite slow. It don't have to copy the data again...
如果用户希望通过配置加载特征和标签,可以定义一个新的处理器并调用 qlib.contrib.data.handler.Alpha158
的静态方法 parse_config_to_fields。
此外,用户还可以将 qlib.contrib.data.processor.ConfigSectionProcessor
传入新处理器,该处理器为配置定义的特征提供了一些预处理方法。
Processor¶
Qlib
中的 Processor
模块设计为可学习的,负责处理诸如`归一化`和`丢弃空值/缺失特征/标签`等数据处理任务。
Qlib
提供以下 Processor
:
DropnaProcessor
:丢弃N/A特征的`处理器`DropnaLabel
:丢弃N/A标签的`处理器`TanhProcess
:使用`tanh`处理噪声数据的`处理器`ProcessInf
:处理无穷值的`处理器`,会用列均值替换无穷值Fillna
:处理N/A值的`处理器`,会用0或其他给定值填充缺失值MinMaxNorm
:应用最小-最大归一化的`处理器`ZscoreNorm
:应用z-score归一化的`处理器`RobustZScoreNorm
:应用鲁棒z-score归一化的`处理器`CSZScoreNorm
:应用横截面z-score归一化的`处理器`CSRankNorm
:应用横截面秩归一化的`处理器`CSZFillna
:以横截面方式用列均值填充N/A值的`处理器`
用户也可以通过继承 Processor
基类创建自己的`处理器`。更多信息请参考所有处理器的实现(Processor 链接)。
要了解更多关于 Processor
的信息,请参阅 Processor API。
示例¶
Data Handler
可以通过修改配置文件与 qrun
一起运行,也可以作为独立模块使用。
了解更多关于如何使用 qrun
运行 Data Handler
的信息,请参阅 工作流:工作流管理
Qlib提供了已实现的数据处理器 Alpha158。以下示例展示如何将 Alpha158 作为独立模块运行。
备注
用户需要先用 qlib.init 初始化 Qlib
,请参考 初始化。
import qlib
from qlib.contrib.data.handler import Alpha158
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": "csi300",
}
if __name__ == "__main__":
qlib.init()
h = Alpha158(**data_handler_config)
# get all the columns of the data
print(h.get_cols())
# fetch all the labels
print(h.fetch(col_set="label"))
# fetch all the features
print(h.fetch(col_set="feature"))
备注
在 Alpha158
中,Qlib
使用标签 Ref($close, -2)/Ref($close, -1) - 1 表示从T+1日到T+2日的变化,而不是 Ref($close, -1)/$close - 1,原因是当获取中国股票T日收盘价时,股票可以在T+1日买入并在T+2日卖出。
API¶
要了解更多关于 Data Handler
的信息,请参阅 Data Handler API。
Dataset¶
Qlib
中的 Dataset
模块旨在为模型训练和推理准备数据。
该模块的设计动机是希望最大化不同模型处理适合自身数据的灵活性。该模块允许模型以独特的方式处理数据。例如,像 GBDT
这样的模型可以很好地处理包含 nan 或 None 值的数据,而像 MLP
这样的神经网络在此类数据上会出现问题。
如果用户的模型需要以不同方式处理数据,可以实现自己的 Dataset
类。如果模型的数据处理并不特殊,可以直接使用 DatasetH
。
DatasetH
类是带有 Data Handler 的 dataset。以下是该类最重要的接口:
- class qlib.data.dataset.__init__.DatasetH(handler: Dict | DataHandler, segments: Dict[str, Tuple], fetch_kwargs: Dict = {}, **kwargs)
Dataset with Data(H)andler
User should try to put the data preprocessing functions into handler. Only following data processing functions should be placed in Dataset:
The processing is related to specific model.
The processing is related to data split.
- __init__(handler: Dict | DataHandler, segments: Dict[str, Tuple], fetch_kwargs: Dict = {}, **kwargs)
Setup the underlying data.
- 参数:
handler (Union[dict, DataHandler]) --
handler could be:
instance of DataHandler
config of DataHandler. Please refer to DataHandler
segments (dict) --
Describe the options to segment the data. Here are some examples:
1) 'segments': { 'train': ("2008-01-01", "2014-12-31"), 'valid': ("2017-01-01", "2020-08-01",), 'test': ("2015-01-01", "2016-12-31",), } 2) 'segments': { 'insample': ("2008-01-01", "2014-12-31"), 'outsample': ("2017-01-01", "2020-08-01",), }
- config(handler_kwargs: dict = None, **kwargs)
Initialize the DatasetH
- 参数:
handler_kwargs (dict) --
Config of DataHandler, which could include the following arguments:
arguments of DataHandler.conf_data, such as 'instruments', 'start_time' and 'end_time'.
kwargs (dict) --
Config of DatasetH, such as
- segmentsdict
Config of segments which is same as 'segments' in self.__init__
- setup_data(handler_kwargs: dict = None, **kwargs)
Setup the Data
- 参数:
handler_kwargs (dict) --
init arguments of DataHandler, which could include the following arguments:
init_type : Init Type of Handler
enable_cache : whether to enable cache
- prepare(segments: List[str] | Tuple[str] | str | slice | Index, col_set='__all', data_key='infer', **kwargs) List[DataFrame] | DataFrame
Prepare the data for learning and inference.
- 参数:
segments (Union[List[Text], Tuple[Text], Text, slice]) --
Describe the scope of the data to be prepared Here are some examples:
'train'
['train', 'valid']
col_set (str) --
The col_set will be passed to self.handler when fetching data. TODO: make it automatic:
select DK_I for test data
select DK_L for training data.
data_key (str) -- The data to fetch: DK_* Default is DK_I, which indicate fetching data for inference.
kwargs --
- The parameters that kwargs may contain:
- flt_colstr
It only exists in TSDatasetH, can be used to add a column of data(True or False) to filter data. This parameter is only supported when it is an instance of TSDatasetH.
- 返回类型:
Union[List[pd.DataFrame], pd.DataFrame]
- 抛出:
NotImplementedError: --
API¶
要了解更多关于 Dataset
的信息,请参阅 Dataset API。
缓存¶
Cache
是一个可选模块,通过将一些频繁使用的数据保存为缓存文件来帮助加速数据提供。Qlib
提供了一个 Memcache 类用于缓存内存中最频繁使用的数据,一个可继承的 ExpressionCache 类,以及一个可继承的 DatasetCache 类。
全局内存缓存¶
Memcache 是一种全局内存缓存机制,由三个 MemCacheUnit 实例组成,分别用于缓存**日历**、证券列表**和**特征数据。该 MemCache 在 cache.py 中全局定义为 H。用户可以使用 H['c'], H['i'], H['f'] 来获取/设置 memcache。
- class qlib.data.cache.MemCacheUnit(*args, **kwargs)
Memory Cache Unit.
- __init__(*args, **kwargs)
- property limited
whether memory cache is limited
- class qlib.data.cache.MemCache(mem_cache_size_limit=None, limit_type='length')
Memory cache.
- __init__(mem_cache_size_limit=None, limit_type='length')
- 参数:
mem_cache_size_limit -- cache max size.
limit_type -- length or sizeof; length(call fun: len), size(call fun: sys.getsizeof).
ExpressionCache¶
ExpressionCache 是一种缓存机制,用于保存诸如 Mean($close, 5) 之类的表达式。用户可以继承此基类,按照以下步骤定义自己的表达式缓存机制。
重写 self._uri 方法以定义缓存文件路径的生成方式
重写 self._expression 方法以定义将被缓存的数据内容及缓存方式
以下展示了相关接口的详细信息:
- class qlib.data.cache.ExpressionCache(provider)
Expression cache mechanism base class.
This class is used to wrap expression provider with self-defined expression cache mechanism.
备注
Override the _uri and _expression method to create your own expression cache mechanism.
- expression(instrument, field, start_time, end_time, freq)
Get expression data.
备注
Same interface as expression method in expression provider
- update(cache_uri: str | Path, freq: str = 'day')
Update expression cache to latest calendar.
Override this method to define how to update expression cache corresponding to users' own cache mechanism.
- 参数:
cache_uri (str or Path) -- the complete uri of expression cache file (include dir path).
freq (str)
- 返回:
0(successful update)/ 1(no need to update)/ 2(update failure).
- 返回类型:
int
Qlib
has currently provided implemented disk cache DiskExpressionCache which inherits from ExpressionCache . The expressions data will be stored in the disk.
DatasetCache¶
DatasetCache 是一种数据集缓存机制。特定数据集由股票池配置(或一系列标的,但不推荐)、表达式列表或静态特征字段、特征采集的起止时间及频率所规范。用户可以继承此基类,按照以下步骤定义自己的数据集缓存机制。
重写 self._uri 方法以定义其缓存文件路径的生成方式
重写 self._expression 方法以定义将被缓存的数据内容及缓存方式
以下展示了相关接口的详细信息:
- class qlib.data.cache.DatasetCache(provider)
Dataset cache mechanism base class.
This class is used to wrap dataset provider with self-defined dataset cache mechanism.
备注
Override the _uri and _dataset method to create your own dataset cache mechanism.
- dataset(instruments, fields, start_time=None, end_time=None, freq='day', disk_cache=1, inst_processors=[])
Get feature dataset.
备注
Same interface as dataset method in dataset provider
备注
The server use redis_lock to make sure read-write conflicts will not be triggered but client readers are not considered.
- update(cache_uri: str | Path, freq: str = 'day')
Update dataset cache to latest calendar.
Override this method to define how to update dataset cache corresponding to users' own cache mechanism.
- 参数:
cache_uri (str or Path) -- the complete uri of dataset cache file (include dir path).
freq (str)
- 返回:
0(successful update)/ 1(no need to update)/ 2(update failure)
- 返回类型:
int
- static cache_to_origin_data(data, fields)
cache data to origin data
- 参数:
data -- pd.DataFrame, cache data.
fields -- feature fields.
- 返回:
pd.DataFrame.
- static normalize_uri_args(instruments, fields, freq)
normalize uri args
Qlib
has currently provided implemented disk cache DiskDatasetCache which inherits from DatasetCache . The datasets' data will be stored in the disk.
数据与缓存文件结构¶
We've specially designed a file structure to manage data and cache, please refer to the File storage design section in Qlib paper for detailed information. The file structure of data and cache is listed as follows.
- data/
[raw data] updated by data providers
- calendars/
- day.txt
- instruments/
- all.txt
- csi500.txt
- ...
- features/
- sh600000/
- open.day.bin
- close.day.bin
- ...
- ...
[cached data] updated when raw data is updated
- calculated features/
- sh600000/
- [hash(instrtument, field_expression, freq)]
- all-time expression -cache data file
- .meta : an assorted meta file recording the instrument name, field name, freq, and visit times
- ...
- cache/
- [hash(stockpool_config, field_expression_list, freq)]
- all-time Dataset-cache data file
- .meta : an assorted meta file recording the stockpool config, field names and visit times
- .index : an assorted index file recording the line index of all calendars
- ...