数据层:数据框架与使用

介绍

数据层 提供用户友好的API来管理和检索数据。它提供高性能的数据基础设施。

它专为量化投资而设计。例如,用户可以轻松使用 数据层 构建公式化的阿尔法。有关详细信息,请参阅 构建公式化阿尔法

数据层 的介绍包括以下内容。

  • 数据准备

  • 数据API

  • 数据加载器

  • 数据处理器

  • 数据集

  • 缓存

  • 数据和缓存文件结构

以下是Qlib数据工作流的典型示例:

  • 用户下载数据并将数据转换为Qlib格式(文件名后缀为 .bin)。在此步骤中,通常只有一些基本数据被存储在磁盘上(例如OHLCV)。

  • 根据Qlib的表达式引擎创建一些基本特征(例如 “Ref($close, 60) / $close”,过去60个交易日的回报)。表达式引擎中支持的运算符可以在 这里 找到。此步骤通常是在Qlib的 数据加载器 中实现的,该组件是 数据处理器 的一部分。

  • 如果用户需要更复杂的数据处理(例如数据标准化),数据处理器 支持用户自定义的处理器来处理数据(一些预定义的处理器可以在 这里 找到)。处理器与表达式引擎中的运算符不同。它专为一些复杂的数据处理方法而设计,这些方法无法在表达式引擎中支持。

  • 最后,数据集 负责从数据处理器处理后的数据中准备特定于模型的数据集

数据准备

Qlib 格式数据

我们特别设计了一种数据结构来管理金融数据,请参考 Qlib 论文中的 文件存储设计部分 以获取详细信息。 这些数据将以 .bin 后缀存储(我们将其称为 .bin 文件、.bin 格式或 qlib 格式)。.bin 文件是为金融数据上的科学计算而设计的。

Qlib 提供了两个不同的现成数据集,可以通过这个 链接 进行访问。

数据集

美国市场

中国市场

Alpha360

Alpha158

此外,Qlib 还提供了一个高频数据集。用户可以通过这个 链接 运行一个高频数据集示例。

Qlib 格式数据集

Qlib 向用户提供了一个现成的 .bin 格式数据集,用户可以使用脚本 scripts/get_data.py 来下载 China-Stock 数据集,如下所示。用户还可以使用 numpy 来加载 .bin 文件以验证数据。 价格成交量数据与实际交易价格不同,因为它们经过了 调整调整后的价格 )。然后您可能会发现,不同的数据源中调整后的价格可能会有所不同。这是因为不同的数据源在调整价格的方式上可能有所不同。在调整时,Qlib 将每只股票的首个交易日价格归一化为1。 用户可以利用 $factor 来获取原始交易价格(例如,使用 $close / $factor 来获取原始收盘价)。

以下是关于 Qlib 价格调整的一些讨论。

# 下载1日数据
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn

# 下载1分钟数据
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

运行上述命令后,用户可以在 ~/.qlib/qlib_data/cn_data 目录和 ~/.qlib/qlib_data/us_data 目录中找到以 Qlib 格式存储的中国股票数据和美国股票数据。

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>
      
      • script path: 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 格式转换为 Qlib 格式

Qlib 提供了脚本 scripts/dump_bin.py,可以将 任何 CSV 格式的数据转换为 .bin 文件(Qlib 格式),只要它们符合正确的格式要求。

除了下载预先准备好的演示数据,用户还可以直接从收集器中下载演示数据,方法如下所示,以供 CSV 格式的参考。 下面是一些示例:

对于日线数据:
python scripts/get_data.py download_data --file_name csv_data_cn.zip --target_dir ~/.qlib/csv_data/cn_data
对于一分钟数据:
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 格式数据。但是,CSV 数据必须满足以下条件:

  • CSV 文件的命名方式是特定股票的名称 或者 CSV 文件包含股票名称的列

    • 将 CSV 文件命名为股票名称:SH600000.csvAAPL.csv (不区分大小写)。- CSV文件中包含一列股票名称。当转储数据时,用户 必须 指定列名。以下是一个示例:

      python scripts/dump_bin.py dump_all ... --symbol_field_name symbol
      

      数据的格式如下:

      symbol

      close

      SH600000

      120

  • CSV文件 必须 包含一个日期列,并且在转储数据时,用户必须指定日期列名。以下是一个示例:

    python scripts/dump_bin.py dump_all ... --date_field_name date
    

    数据的格式如下: .. code-block:

    +---------+------------+-------+------+----------+
    | symbol  | date       | close | open | volume   |
    +=========+============+=======+======+==========+
    | SH600000| 2020-11-01 | 120   | 121  | 12300000 |
    +---------+------------+-------+------+----------+
    | SH600000| 2020-11-02 | 123   | 120  | 12300000 |
    +---------+------------+-------+------+----------+
    

假设用户将他们的CSV格式数据准备在目录 ~/.qlib/csv_data/my_data 中,他们可以执行以下命令开始转换。

python scripts/dump_bin.py dump_all --csv_path  ~/.qlib/csv_data/my_data --qlib_dir ~/.qlib/qlib_data/my_data --include_fields open,close,high,low,volume,factor

有关将数据转储到`.bin`文件时的其他支持参数,用户可以运行以下命令查看信息:

python dump_bin.py dump_all --help

转换完成后,用户可以在目录 ~/.qlib/qlib_data/my_data 中找到他们的Qlib格式数据。

备注

–include_fields 的参数应该与CSV文件的列名对应。Qlib 提供的数据集的列名至少应包括开盘价(open)、收盘价(close)、最高价(high)、最低价(low)、成交量(volume)和复权因子(factor)。

  • open

    调整后的开盘价

  • close

    调整后的收盘价

  • high

    调整后的最高价

  • low

    调整后的最低价

  • volume

    调整后的成交量

  • factor

    复权因子。通常,factor = adjusted_price / original_price,参考 split adjusted

按照 Qlib 数据处理的约定,如果股票停牌,open, close, high, low, volume, moneyfactor 将被设置为NaN。 如果要使用无法通过OCHLV计算的自定义因子,比如PE、EPS等,可以将其与OHCLV一起添加到CSV文件中,然后将其转储为Qlib格式的数据。

股票池(市场)

Qlib股票池 定义为股票列表及其日期范围。可以通过以下方式导入预定义的股票池(如csi300)。

python collector.py --index_name CSI300 --qlib_dir <user qlib data dir> --method parse_instruments

多股票模式

Qlib 现在为用户提供了两种不同的股票模式:中国股票模式和美国股票模式。以下是这两种模式的一些不同设置:

区域

交易单位

限制阈值

中国

100

0.099

美国

1

“交易单位”定义了一次交易中可以使用的股票数量,“限制阈值”定义了股票涨跌幅的百分比范围。

  • 如果用户在中国股票模式下使用 Qlib,则需要中国股票数据。用户可以按照以下步骤在中国股票模式下使用 Qlib
    • Qlib 格式下载中国股票数据,请参考“Qlib格式数据集”一节。

    • 初始化中国股票模式的 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格式数据集”一节。

    • 初始化美国股票模式的 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 来获取数据,请参考 数据获取

特征

Qlib 提供了 FeatureExpressionOps 来根据用户需求提取特征。

  • Feature

    从数据提供商加载数据。用户可以获取像 $high, $low, $open, $close 等特征,这些特征应该与 –include_fields 的参数相对应,请参考 将 CSV 格式转换为 Qlib 格式 部分。

  • ExpressionOps

    ExpressionOps 将使用运算符进行特征构建。 要了解更多关于 Operator 的信息,请参考 运算符 API。 此外,Qlib 还支持用户定义自己的自定义 Operator,在 tests/test_register_ops.py 中提供了一个示例。

要了解更多关于 Feature 的信息,请参考 特征 API

过滤器

Qlib 提供了 NameDFilterExpressionDFilter 来根据用户需求过滤工具。

  • 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 <../reference/api.html#module-qlib.data.filter>`_。

参考

要了解更多关于``Data API``的信息,请参考`Data API <../reference/api.html#data>`_。

数据加载器

Qlib 中的 数据加载器(Data Loader) 被设计用于从原始数据源加载数据。它将在 数据处理器(Data Handler) 模块中被加载和使用。

QlibDataLoader

Qlib 中的 QlibDataLoader 类是一个接口,允许用户从 Qlib 数据源加载原始数据。

StaticDataLoader

Qlib 中的 StaticDataLoader 类是一个接口,允许用户从文件或提供的数据中加载原始数据。

接口

下面是 QlibDataLoader 类的一些接口:

class qlib.data.dataset.loader.DataLoader

DataLoader is designed for loading raw data from original data source.

abstract 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.

  • 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

API

要了解更多关于 DataLoader 的信息,请参考 DataLoader API

数据处理者

“Data Handler” 模块在 “Qlib” 中设计用于处理那些大多数模型都会使用的常见数据处理方法。

用户可以在自动化工作流程中使用 “Data Handler” ,详细信息请参阅 工作流程: 工作流管理

DataHandlerLP

除了在使用 qrun 自动化工作流中使用 “Data Handler” 之外,还可以将 “Data Handler” 作为一个独立的模块使用,通过它,用户可以轻松预处理数据(标准化,NaN 值删除等)。并构建数据集。

为了实现这一点,Qlib 提供了一个基类 qlib.data.dataset.DataHandlerLP 。这个类的核心思想是:我们将拥有一些可学习的“处理器”,这些处理器可以学习数据处理的参数(例如,zscore 归一化的参数)。当新的数据进来时,这些“经过训练的”处理器就能够处理新的数据,从而实现实时数据处理变得可能。关于“处理器”的更多信息将在下面的子节中列出。

接口

下面是 DataHandlerLP 提供的一些重要接口:

class qlib.data.dataset.handler.DataHandlerLP(instruments=None, start_time=None, end_time=None, data_loader: dict | str | DataLoader | None = None, infer_processors: List = [], learn_processors: List = [], shared_processors: List = [], process_type='append', drop_raw=False, **kwargs)

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 = 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 = 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 = 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

返回类型:

DataHandlerLP

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 传递到新的处理器中。

处理器

Qlib 中的 Processor 模块旨在可学习,并负责处理数据处理,如 标准化删除无特征/标签

Qlib 提供以下 Processors

  • DropnaProcessor:删除N/A特征的处理器。

  • DropnaLabel:删除N/A标签的处理器。

  • TanhProcess:使用`tanh`处理噪声数据的处理器。

  • ProcessInf:处理无穷大值的处理器,将被列均值替换。

  • Fillna:处理N/A值的处理器,将N/A值填充为0或其他给定的数字。

  • MinMaxNorm:应用最值归一化的处理器。

  • ZscoreNorm:应用Z分数归一化的处理器。

  • RobustZScoreNorm:应用鲁棒的Z分数归一化的处理器。

  • CSZScoreNorm:应用截面Z分数归一化的处理器。

  • CSRankNorm:应用截面排名归一化的处理器。

  • CSZFillna:按列均值进行截面方式填充N/A值的处理器。

用户也可以通过继承 Processor 的基类来创建自己的处理器。有关所有处理器的实现,请参阅实现的所有处理器的详细信息( ``Processor Link <https://github.com/microsoft/qlib/blob/main/qlib/data/dataset/processor.py>``_)。

了解更多关于 Processor 的信息,请参阅 Processor API

示例

通过修改配置文件,可以使用 qrun``运行 ``数据处理器,也可以将其作为单个模块使用。

如何使用 qrun 运行 数据处理器 的更多信息,请参阅`工作流:工作流管理 <workflow.html>`_

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)

    # 获取所有数据的列
    print(h.get_cols())

    # 获取所有标签
    print(h.fetch(col_set="label"))

    # 获取所有特征
    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 的信息,请参考 数据处理器 API

数据集

Qlib 中的 Dataset 模块旨在为模型的训练和推断准备数据。

该模块的动机是我们希望最大程度地提高不同模型处理适合自身的数据的灵活性。该模块为模型提供了以独特方式处理其数据的灵活性。例如,像 GBDT 这样的模型可能在包含 nanNone 值的数据上表现良好,而像 MLP 这样的神经网络则无法处理此类数据。

如果用户的模型需要根据不同的方式处理其数据,用户可以实现自己的 Dataset 类。如果模型的数据处理没有特殊需求,可以直接使用 DatasetH

DatasetH 类是带有 Data Handler数据集。以下是该类的最重要接口:

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 = 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 = 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 的信息,请参考 数据集 API

缓存

Cache 是一个可选模块,通过将一些经常使用的数据保存为缓存文件来加快数据的提供速度。Qlib 提供了一个 Memcache 类,用于在内存中缓存最常用的数据,一个可继承的 ExpressionCache 类,和一个可继承的 DatasetCache 类。

全局内存缓存

Memcache 是一个全局内存缓存机制,由三个 MemCacheUnit 实例组成,用于缓存 日历工具特征MemCachecache.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 当前已提供了从 ExpressionCache 继承而来的实现了磁盘缓存 DiskExpressionCache。表达式数据将被存储在磁盘中。

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 当前已提供了从 DatasetCache 继承而来的实现了磁盘缓存 DiskDatasetCache。数据集的数据将被存储在磁盘中。

数据和缓存文件结构

我们专门设计了一个文件结构来管理数据和缓存,请参考Qlib论文中的“文件存储设计”一节,了解详细信息。数据和缓存的文件结构如下所示。

- data/
    [原始数据]由数据提供者更新
    - 日历/
        - day.txt
    - 仪器/
        - all.txt
        - csi500.txt
        - ...
    - 特征/
        - sh600000/
            - open.day.bin
            - close.day.bin
            - ...
        - ...
    [缓存数据]在原始数据更新时更新
    - 计算特征/
        - sh600000/
            - [hash(仪器, 字段表达式, 频率)]
                - 全时期表达式 - 缓存数据文件
                - .meta:记录仪器名称、字段名称、频率和访问次数的混合元文件
        - ...
    - 缓存/
        - [hash(股票池配置, 字段表达式列表, 频率)]
            - 全时期数据集 - 缓存数据文件
            - .meta:记录股票池配置、字段名称和访问次数的混合元文件
            - .index:记录所有日历行索引的混合索引文件
        - ...