mirror of
https://github.com/microsoft/qlib.git
synced 2026-07-22 19:55:48 +08:00
Compare commits
38 Commits
you-n-g-pa
...
mini_proje
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
949d96d768 | ||
|
|
597359f98f | ||
|
|
75aae820e8 | ||
|
|
558603beca | ||
|
|
157481abd1 | ||
|
|
9d7a0f032a | ||
|
|
58f9eed3c9 | ||
|
|
8f1e28c43f | ||
|
|
e7c660f0d4 | ||
|
|
2752bdc92c | ||
|
|
687edd79d0 | ||
|
|
ba705d39e0 | ||
|
|
a53f59cdf7 | ||
|
|
8e063828f9 | ||
|
|
86f08e47e8 | ||
|
|
8199822ca0 | ||
|
|
1b9915501c | ||
|
|
c65c598bde | ||
|
|
fb5779a64c | ||
|
|
d149c2b177 | ||
|
|
6fddae9965 | ||
|
|
107d716cf8 | ||
|
|
792285b64f | ||
|
|
78b6b16640 | ||
|
|
b9bba4940f | ||
|
|
c34051c1ce | ||
|
|
a0c83d7997 | ||
|
|
82b10ee37a | ||
|
|
9b446f9a92 | ||
|
|
59b1820447 | ||
|
|
1dededa33f | ||
|
|
e62684eddf | ||
|
|
8a5efda0f6 | ||
|
|
a6700d81ff | ||
|
|
623774d8fb | ||
|
|
3db22452fb | ||
|
|
b655f90511 | ||
|
|
5e404909cf |
11
.github/workflows/test_qlib_from_pip.yml
vendored
11
.github/workflows/test_qlib_from_pip.yml
vendored
@@ -37,6 +37,17 @@ jobs:
|
|||||||
# and this line of code will be removed when the next version of qlib is released.
|
# and this line of code will be removed when the next version of qlib is released.
|
||||||
python -m pip install "numpy<1.23"
|
python -m pip install "numpy<1.23"
|
||||||
|
|
||||||
|
- name: Install Lightgbm for MacOS
|
||||||
|
if: ${{ matrix.os == 'macos-11' || matrix.os == 'macos-latest' }}
|
||||||
|
run: |
|
||||||
|
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Microsoft/qlib/main/.github/brew_install.sh)"
|
||||||
|
HOMEBREW_NO_AUTO_UPDATE=1 brew install lightgbm
|
||||||
|
# FIX MacOS error: Segmentation fault
|
||||||
|
# reference: https://github.com/microsoft/LightGBM/issues/4229
|
||||||
|
wget https://raw.githubusercontent.com/Homebrew/homebrew-core/fb8323f2b170bd4ae97e1bac9bf3e2983af3fdb0/Formula/libomp.rb
|
||||||
|
brew unlink libomp
|
||||||
|
brew install libomp.rb
|
||||||
|
|
||||||
- name: Downloads dependencies data
|
- name: Downloads dependencies data
|
||||||
run: |
|
run: |
|
||||||
python scripts/get_data.py qlib_data --name qlib_data_simple --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn
|
python scripts/get_data.py qlib_data --name qlib_data_simple --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn
|
||||||
|
|||||||
25
.github/workflows/test_qlib_from_source.yml
vendored
25
.github/workflows/test_qlib_from_source.yml
vendored
@@ -8,7 +8,8 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
timeout-minutes: 120
|
timeout-minutes: 180
|
||||||
|
# we may retry for 3 times for `Unit tests with Pytest`
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
@@ -34,7 +35,6 @@ jobs:
|
|||||||
if: ${{ matrix.os == 'macos-11' || matrix.os == 'macos-latest' }}
|
if: ${{ matrix.os == 'macos-11' || matrix.os == 'macos-latest' }}
|
||||||
run: |
|
run: |
|
||||||
python -m pip install torch torchvision torchaudio
|
python -m pip install torch torchvision torchaudio
|
||||||
brew install libomp # lightgbm dependencies
|
|
||||||
|
|
||||||
- name: Installing pytorch for ubuntu
|
- name: Installing pytorch for ubuntu
|
||||||
if: ${{ matrix.os == 'ubuntu-18.04' || matrix.os == 'ubuntu-20.04' }}
|
if: ${{ matrix.os == 'ubuntu-18.04' || matrix.os == 'ubuntu-20.04' }}
|
||||||
@@ -126,6 +126,17 @@ jobs:
|
|||||||
azcopy copy https://qlibpublic.blob.core.windows.net/data/rl /tmp/qlibpublic/data --recursive
|
azcopy copy https://qlibpublic.blob.core.windows.net/data/rl /tmp/qlibpublic/data --recursive
|
||||||
mv /tmp/qlibpublic/data tests/.data
|
mv /tmp/qlibpublic/data tests/.data
|
||||||
|
|
||||||
|
- name: Install Lightgbm for MacOS
|
||||||
|
if: ${{ matrix.os == 'macos-11' || matrix.os == 'macos-latest' }}
|
||||||
|
run: |
|
||||||
|
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Microsoft/qlib/main/.github/brew_install.sh)"
|
||||||
|
HOMEBREW_NO_AUTO_UPDATE=1 brew install lightgbm
|
||||||
|
# FIX MacOS error: Segmentation fault
|
||||||
|
# reference: https://github.com/microsoft/LightGBM/issues/4229
|
||||||
|
wget https://raw.githubusercontent.com/Homebrew/homebrew-core/fb8323f2b170bd4ae97e1bac9bf3e2983af3fdb0/Formula/libomp.rb
|
||||||
|
brew unlink libomp
|
||||||
|
brew install libomp.rb
|
||||||
|
|
||||||
- name: Test workflow by config (install from source)
|
- name: Test workflow by config (install from source)
|
||||||
run: |
|
run: |
|
||||||
# Version 0.52.0 of numba must be installed manually in CI, otherwise it will cause incompatibility with the latest version of numpy.
|
# Version 0.52.0 of numba must be installed manually in CI, otherwise it will cause incompatibility with the latest version of numpy.
|
||||||
@@ -135,6 +146,10 @@ jobs:
|
|||||||
python qlib/workflow/cli.py examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
python qlib/workflow/cli.py examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
||||||
|
|
||||||
- name: Unit tests with Pytest
|
- name: Unit tests with Pytest
|
||||||
run: |
|
uses: nick-fields/retry@v2
|
||||||
cd tests
|
with:
|
||||||
python -m pytest . -m "not slow" --durations=0
|
timeout_minutes: 60
|
||||||
|
max_attempts: 3
|
||||||
|
command: |
|
||||||
|
cd tests
|
||||||
|
python -m pytest . -m "not slow" --durations=0
|
||||||
|
|||||||
17
.github/workflows/test_qlib_from_source_slow.yml
vendored
17
.github/workflows/test_qlib_from_source_slow.yml
vendored
@@ -8,7 +8,8 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
timeout-minutes: 120
|
timeout-minutes: 720
|
||||||
|
# we may retry for 3 times for `Unit tests with Pytest`
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
@@ -28,7 +29,9 @@ jobs:
|
|||||||
|
|
||||||
- name: Set up Python tools
|
- name: Set up Python tools
|
||||||
run: |
|
run: |
|
||||||
pip install --upgrade cython numpy pip
|
python -m pip install --upgrade pip
|
||||||
|
# python -m pip is necessary to upgrade pip.
|
||||||
|
pip install --upgrade cython numpy
|
||||||
pip install -e .[dev]
|
pip install -e .[dev]
|
||||||
|
|
||||||
- name: Downloads dependencies data
|
- name: Downloads dependencies data
|
||||||
@@ -47,6 +50,10 @@ jobs:
|
|||||||
brew install libomp.rb
|
brew install libomp.rb
|
||||||
|
|
||||||
- name: Unit tests with Pytest
|
- name: Unit tests with Pytest
|
||||||
run: |
|
uses: nick-fields/retry@v2
|
||||||
cd tests
|
with:
|
||||||
python -m pytest . -m "slow" --durations=0
|
timeout_minutes: 240
|
||||||
|
max_attempts: 3
|
||||||
|
command: |
|
||||||
|
cd tests
|
||||||
|
python -m pytest . -m "slow" --durations=0
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/psf/black
|
- repo: https://github.com/psf/black
|
||||||
rev: 22.1.0
|
rev: 22.6.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: black
|
- id: black
|
||||||
args: ["qlib", "-l 120"]
|
args: ["qlib", "-l 120"]
|
||||||
|
|||||||
56
CHANGES.rst
56
CHANGES.rst
@@ -1,63 +1,63 @@
|
|||||||
Changelog
|
Changelog
|
||||||
====================
|
=========
|
||||||
Here you can see the full list of changes between each QLib release.
|
Here you can see the full list of changes between each QLib release.
|
||||||
|
|
||||||
Version 0.1.0
|
Version 0.1.0
|
||||||
--------------------
|
-------------
|
||||||
This is the initial release of QLib library.
|
This is the initial release of QLib library.
|
||||||
|
|
||||||
Version 0.1.1
|
Version 0.1.1
|
||||||
--------------------
|
-------------
|
||||||
Performance optimize. Add more features and operators.
|
Performance optimize. Add more features and operators.
|
||||||
|
|
||||||
Version 0.1.2
|
Version 0.1.2
|
||||||
--------------------
|
-------------
|
||||||
- Support operator syntax. Now ``High() - Low()`` is equivalent to ``Sub(High(), Low())``.
|
- Support operator syntax. Now ``High() - Low()`` is equivalent to ``Sub(High(), Low())``.
|
||||||
- Add more technical indicators.
|
- Add more technical indicators.
|
||||||
|
|
||||||
Version 0.1.3
|
Version 0.1.3
|
||||||
--------------------
|
-------------
|
||||||
Bug fix and add instruments filtering mechanism.
|
Bug fix and add instruments filtering mechanism.
|
||||||
|
|
||||||
Version 0.2.0
|
Version 0.2.0
|
||||||
--------------------
|
-------------
|
||||||
- Redesign ``LocalProvider`` database format for performance improvement.
|
- Redesign ``LocalProvider`` database format for performance improvement.
|
||||||
- Support load features as string fields.
|
- Support load features as string fields.
|
||||||
- Add scripts for database construction.
|
- Add scripts for database construction.
|
||||||
- More operators and technical indicators.
|
- More operators and technical indicators.
|
||||||
|
|
||||||
Version 0.2.1
|
Version 0.2.1
|
||||||
--------------------
|
-------------
|
||||||
- Support registering user-defined ``Provider``.
|
- Support registering user-defined ``Provider``.
|
||||||
- Support use operators in string format, e.g. ``['Ref($close, 1)']`` is valid field format.
|
- Support use operators in string format, e.g. ``['Ref($close, 1)']`` is valid field format.
|
||||||
- Support dynamic fields in ``$some_field`` format. And existing fields like ``Close()`` may be deprecated in the future.
|
- Support dynamic fields in ``$some_field`` format. And existing fields like ``Close()`` may be deprecated in the future.
|
||||||
|
|
||||||
Version 0.2.2
|
Version 0.2.2
|
||||||
--------------------
|
-------------
|
||||||
- Add ``disk_cache`` for reusing features (enabled by default).
|
- Add ``disk_cache`` for reusing features (enabled by default).
|
||||||
- Add ``qlib.contrib`` for experimental model construction and evaluation.
|
- Add ``qlib.contrib`` for experimental model construction and evaluation.
|
||||||
|
|
||||||
|
|
||||||
Version 0.2.3
|
Version 0.2.3
|
||||||
--------------------
|
-------------
|
||||||
- Add ``backtest`` module
|
- Add ``backtest`` module
|
||||||
- Decoupling the Strategy, Account, Position, Exchange from the backtest module
|
- Decoupling the Strategy, Account, Position, Exchange from the backtest module
|
||||||
|
|
||||||
Version 0.2.4
|
Version 0.2.4
|
||||||
--------------------
|
-------------
|
||||||
- Add ``profit attribution`` module
|
- Add ``profit attribution`` module
|
||||||
- Add ``rick_control`` and ``cost_control`` strategies
|
- Add ``rick_control`` and ``cost_control`` strategies
|
||||||
|
|
||||||
Version 0.3.0
|
Version 0.3.0
|
||||||
--------------------
|
-------------
|
||||||
- Add ``estimator`` module
|
- Add ``estimator`` module
|
||||||
|
|
||||||
Version 0.3.1
|
Version 0.3.1
|
||||||
--------------------
|
-------------
|
||||||
- Add ``filter`` module
|
- Add ``filter`` module
|
||||||
|
|
||||||
Version 0.3.2
|
Version 0.3.2
|
||||||
--------------------
|
-------------
|
||||||
- Add real price trading, if the ``factor`` field in the data set is incomplete, use ``adj_price`` trading
|
- Add real price trading, if the ``factor`` field in the data set is incomplete, use ``adj_price`` trading
|
||||||
- Refactor ``handler`` ``launcher`` ``trainer`` code
|
- Refactor ``handler`` ``launcher`` ``trainer`` code
|
||||||
- Support ``backtest`` configuration parameters in the configuration file
|
- Support ``backtest`` configuration parameters in the configuration file
|
||||||
@@ -65,16 +65,16 @@ Version 0.3.2
|
|||||||
- Fix bug of ``filter`` module
|
- Fix bug of ``filter`` module
|
||||||
|
|
||||||
Version 0.3.3
|
Version 0.3.3
|
||||||
-------------------
|
-------------
|
||||||
- Fix bug of ``filter`` module
|
- Fix bug of ``filter`` module
|
||||||
|
|
||||||
Version 0.3.4
|
Version 0.3.4
|
||||||
--------------------
|
-------------
|
||||||
- Support for ``finetune model``
|
- Support for ``finetune model``
|
||||||
- Refactor ``fetcher`` code
|
- Refactor ``fetcher`` code
|
||||||
|
|
||||||
Version 0.3.5
|
Version 0.3.5
|
||||||
--------------------
|
-------------
|
||||||
- Support multi-label training, you can provide multiple label in ``handler``. (But LightGBM doesn't support due to the algorithm itself)
|
- Support multi-label training, you can provide multiple label in ``handler``. (But LightGBM doesn't support due to the algorithm itself)
|
||||||
- Refactor ``handler`` code, dataset.py is no longer used, and you can deploy your own labels and features in ``feature_label_config``
|
- Refactor ``handler`` code, dataset.py is no longer used, and you can deploy your own labels and features in ``feature_label_config``
|
||||||
- Handler only offer DataFrame. Also, ``trainer`` and model.py only receive DataFrame
|
- Handler only offer DataFrame. Also, ``trainer`` and model.py only receive DataFrame
|
||||||
@@ -82,7 +82,7 @@ Version 0.3.5
|
|||||||
- Move some date config from ``handler`` to ``trainer``
|
- Move some date config from ``handler`` to ``trainer``
|
||||||
|
|
||||||
Version 0.4.0
|
Version 0.4.0
|
||||||
--------------------
|
-------------
|
||||||
- Add `data` package that holds all data-related codes
|
- Add `data` package that holds all data-related codes
|
||||||
- Reform the data provider structure
|
- Reform the data provider structure
|
||||||
- Create a server for data centralized management `qlib-server<https://amc-msra.visualstudio.com/trading-algo/_git/qlib-server>`_
|
- Create a server for data centralized management `qlib-server<https://amc-msra.visualstudio.com/trading-algo/_git/qlib-server>`_
|
||||||
@@ -100,7 +100,7 @@ Version 0.4.0
|
|||||||
|
|
||||||
|
|
||||||
Version 0.4.1
|
Version 0.4.1
|
||||||
--------------------
|
-------------
|
||||||
- Add support Windows
|
- Add support Windows
|
||||||
- Fix ``instruments`` type bug
|
- Fix ``instruments`` type bug
|
||||||
- Fix ``features`` is empty bug(It will cause failure in updating)
|
- Fix ``features`` is empty bug(It will cause failure in updating)
|
||||||
@@ -112,19 +112,19 @@ Version 0.4.1
|
|||||||
|
|
||||||
|
|
||||||
Version 0.4.2
|
Version 0.4.2
|
||||||
--------------------
|
-------------
|
||||||
- Refactor DataHandler
|
- Refactor DataHandler
|
||||||
- Add ``Alpha360`` DataHandler
|
- Add ``Alpha360`` DataHandler
|
||||||
|
|
||||||
|
|
||||||
Version 0.4.3
|
Version 0.4.3
|
||||||
--------------------
|
-------------
|
||||||
- Implementing Online Inference and Trading Framework
|
- Implementing Online Inference and Trading Framework
|
||||||
- Refactoring The interfaces of backtest and strategy module.
|
- Refactoring The interfaces of backtest and strategy module.
|
||||||
|
|
||||||
|
|
||||||
Version 0.4.4
|
Version 0.4.4
|
||||||
--------------------
|
-------------
|
||||||
- Optimize cache generation performance
|
- Optimize cache generation performance
|
||||||
- Add report module
|
- Add report module
|
||||||
- Fix bug when using ``ServerDatasetCache`` offline.
|
- Fix bug when using ``ServerDatasetCache`` offline.
|
||||||
@@ -138,7 +138,7 @@ Version 0.4.4
|
|||||||
|
|
||||||
|
|
||||||
Version 0.4.5
|
Version 0.4.5
|
||||||
--------------------
|
-------------
|
||||||
- Add multi-kernel implementation for both client and server.
|
- Add multi-kernel implementation for both client and server.
|
||||||
- Support a new way to load data from client which skips dataset cache.
|
- Support a new way to load data from client which skips dataset cache.
|
||||||
- Change the default dataset method from single kernel implementation to multi kernel implementation.
|
- Change the default dataset method from single kernel implementation to multi kernel implementation.
|
||||||
@@ -146,14 +146,14 @@ Version 0.4.5
|
|||||||
- Support a new method to write config file by using dict.
|
- Support a new method to write config file by using dict.
|
||||||
|
|
||||||
Version 0.4.6
|
Version 0.4.6
|
||||||
--------------------
|
-------------
|
||||||
- Some bugs are fixed
|
- Some bugs are fixed
|
||||||
- The default config in `Version 0.4.5` is not friendly to daily frequency data.
|
- The default config in `Version 0.4.5` is not friendly to daily frequency data.
|
||||||
- Backtest error in TopkWeightStrategy when `WithInteract=True`.
|
- Backtest error in TopkWeightStrategy when `WithInteract=True`.
|
||||||
|
|
||||||
|
|
||||||
Version 0.5.0
|
Version 0.5.0
|
||||||
--------------------
|
-------------
|
||||||
- First opensource version
|
- First opensource version
|
||||||
- Refine the docs, code
|
- Refine the docs, code
|
||||||
- Add baselines
|
- Add baselines
|
||||||
@@ -161,7 +161,7 @@ Version 0.5.0
|
|||||||
|
|
||||||
|
|
||||||
Version 0.8.0
|
Version 0.8.0
|
||||||
--------------------
|
-------------
|
||||||
- The backtest is greatly refactored.
|
- The backtest is greatly refactored.
|
||||||
- Nested decision execution framework is supported
|
- Nested decision execution framework is supported
|
||||||
- There are lots of changes for daily trading, it is hard to list all of them. But a few important changes could be noticed
|
- There are lots of changes for daily trading, it is hard to list all of them. But a few important changes could be noticed
|
||||||
@@ -175,5 +175,5 @@ Version 0.8.0
|
|||||||
|
|
||||||
|
|
||||||
Other Versions
|
Other Versions
|
||||||
----------------------------------
|
--------------
|
||||||
Please refer to `Github release Notes <https://github.com/microsoft/qlib/releases>`_
|
Please refer to `Github release Notes <https://github.com/microsoft/qlib/releases>`_
|
||||||
|
|||||||
17
README.md
17
README.md
@@ -172,10 +172,23 @@ Also, users can install the latest dev version ``Qlib`` by the source code accor
|
|||||||
```
|
```
|
||||||
**Note**: You can install Qlib with `python setup.py install` as well. But it is not the recommanded approach. It will skip `pip` and cause obscure problems. For example, **only** the command ``pip install .`` **can** overwrite the stable version installed by ``pip install pyqlib``, while the command ``python setup.py install`` **can't**.
|
**Note**: You can install Qlib with `python setup.py install` as well. But it is not the recommanded approach. It will skip `pip` and cause obscure problems. For example, **only** the command ``pip install .`` **can** overwrite the stable version installed by ``pip install pyqlib``, while the command ``python setup.py install`` **can't**.
|
||||||
|
|
||||||
**Tips**: If you fail to install `Qlib` or run the examples in your environment, comparing your steps and the [CI workflow](.github/workflows/test.yml) may help you find the problem.
|
**Tips**: If you fail to install `Qlib` or run the examples in your environment, comparing your steps and the [CI workflow](.github/workflows/test_qlib_from_source.yml) may help you find the problem.
|
||||||
|
|
||||||
## Data Preparation
|
## Data Preparation
|
||||||
Load and prepare data by running the following code:
|
Load and prepare data by running the following code:
|
||||||
|
|
||||||
|
### Get with module
|
||||||
|
```bash
|
||||||
|
# get 1d data
|
||||||
|
python -m qlib.run.get_data qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn
|
||||||
|
|
||||||
|
# get 1min data
|
||||||
|
python -m qlib.run.get_data qlib_data --target_dir ~/.qlib/qlib_data/cn_data_1min --region cn --interval 1min
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
### Get from source
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# get 1d data
|
# get 1d data
|
||||||
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn
|
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn
|
||||||
@@ -197,6 +210,8 @@ We recommend users to prepare their own data if they have a high-quality dataset
|
|||||||
>
|
>
|
||||||
> It is recommended that users update the data manually once (--trading_date 2021-05-25) and then set it to update automatically.
|
> It is recommended that users update the data manually once (--trading_date 2021-05-25) and then set it to update automatically.
|
||||||
>
|
>
|
||||||
|
> **NOTE**: Users can't incrementally update data based on the offline data provided by Qlib(some fields are removed to reduce the data size). Users should use [yahoo collector](https://github.com/microsoft/qlib/tree/main/scripts/data_collector/yahoo#automatic-update-of-daily-frequency-datafrom-yahoo-finance) to download Yahoo data from scratch and then incrementally update it.
|
||||||
|
>
|
||||||
> For more information, please refer to: [yahoo collector](https://github.com/microsoft/qlib/tree/main/scripts/data_collector/yahoo#automatic-update-of-daily-frequency-datafrom-yahoo-finance)
|
> For more information, please refer to: [yahoo collector](https://github.com/microsoft/qlib/tree/main/scripts/data_collector/yahoo#automatic-update-of-daily-frequency-datafrom-yahoo-finance)
|
||||||
|
|
||||||
* Automatic update of data to the "qlib" directory each trading day(Linux)
|
* Automatic update of data to the "qlib" directory each trading day(Linux)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ Qlib FAQ
|
|||||||
############
|
############
|
||||||
|
|
||||||
Qlib Frequently Asked Questions
|
Qlib Frequently Asked Questions
|
||||||
================================
|
===============================
|
||||||
.. contents::
|
.. contents::
|
||||||
:depth: 1
|
:depth: 1
|
||||||
:local:
|
:local:
|
||||||
@@ -13,7 +13,7 @@ Qlib Frequently Asked Questions
|
|||||||
|
|
||||||
|
|
||||||
1. RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase...
|
1. RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase...
|
||||||
------------------------------------------------------------------------------------------------------------------------------------
|
-----------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
.. code-block:: console
|
.. code-block:: console
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ This is caused by the limitation of multiprocessing under windows OS. Please ref
|
|||||||
|
|
||||||
|
|
||||||
2. qlib.data.cache.QlibCacheException: It sees the key(...) of the redis lock has existed in your redis db now.
|
2. qlib.data.cache.QlibCacheException: It sees the key(...) of the redis lock has existed in your redis db now.
|
||||||
-----------------------------------------------------------------------------------------------------------------
|
---------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
It sees the key of the redis lock has existed in your redis db now. You can use the following command to clear your redis keys and rerun your commands
|
It sees the key of the redis lock has existed in your redis db now. You can use the following command to clear your redis keys and rerun your commands
|
||||||
|
|
||||||
@@ -72,7 +72,7 @@ If the issue is not resolved, use ``keys *`` to find if multiple keys exist. If
|
|||||||
Also, feel free to post a new issue in our GitHub repository. We always check each issue carefully and try our best to solve them.
|
Also, feel free to post a new issue in our GitHub repository. We always check each issue carefully and try our best to solve them.
|
||||||
|
|
||||||
3. ModuleNotFoundError: No module named 'qlib.data._libs.rolling'
|
3. ModuleNotFoundError: No module named 'qlib.data._libs.rolling'
|
||||||
------------------------------------------------------------------------------------------------------------------------------------
|
-----------------------------------------------------------------
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
@@ -101,7 +101,7 @@ Also, feel free to post a new issue in our GitHub repository. We always check ea
|
|||||||
|
|
||||||
|
|
||||||
4. BadNamespaceError: / is not a connected namespace
|
4. BadNamespaceError: / is not a connected namespace
|
||||||
------------------------------------------------------------------------------------------------------------------------------------
|
----------------------------------------------------
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
@@ -125,7 +125,7 @@ Also, feel free to post a new issue in our GitHub repository. We always check ea
|
|||||||
|
|
||||||
|
|
||||||
5. TypeError: send() got an unexpected keyword argument 'binary'
|
5. TypeError: send() got an unexpected keyword argument 'binary'
|
||||||
------------------------------------------------------------------------------------------------------------------------------------
|
----------------------------------------------------------------
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
.. _pit:
|
.. _pit:
|
||||||
|
|
||||||
===========================
|
============================
|
||||||
(P)oint-(I)n-(T)ime Database
|
(P)oint-(I)n-(T)ime Database
|
||||||
===========================
|
============================
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
------------
|
------------
|
||||||
Point-in-time data is a very important consideration when performing any sort of historical market analysis.
|
Point-in-time data is a very important consideration when performing any sort of historical market analysis.
|
||||||
|
|
||||||
For example, let’s say we are backtesting a trading strategy and we are using the past five years of historical data as our input.
|
For example, let’s say we are backtesting a trading strategy and we are using the past five years of historical data as our input.
|
||||||
Our model is assumed to trade once a day, at the market close, and we’ll say we are calculating the trading signal for 1 January 2020 in our backtest. At that point, we should only have data for 1 January 2020, 31 December 2019, 30 December 2019 etc.
|
Our model is assumed to trade once a day, at the market close, and we’ll say we are calculating the trading signal for 1 January 2020 in our backtest. At that point, we should only have data for 1 January 2020, 31 December 2019, 30 December 2019 etc.
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
.. _alpha:
|
.. _alpha:
|
||||||
|
|
||||||
===========================
|
=========================
|
||||||
Building Formulaic Alphas
|
Building Formulaic Alphas
|
||||||
===========================
|
=========================
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
|
|
||||||
In quantitative trading practice, designing novel factors that can explain and predict future asset returns are of vital importance to the profitability of a strategy. Such factors are usually called alpha factors, or alphas in short.
|
In quantitative trading practice, designing novel factors that can explain and predict future asset returns are of vital importance to the profitability of a strategy. Such factors are usually called alpha factors, or alphas in short.
|
||||||
|
|
||||||
@@ -15,28 +15,28 @@ A formulaic alpha, as the name suggests, is a kind of alpha that can be presente
|
|||||||
|
|
||||||
|
|
||||||
Building Formulaic Alphas in ``Qlib``
|
Building Formulaic Alphas in ``Qlib``
|
||||||
======================================
|
=====================================
|
||||||
|
|
||||||
In ``Qlib``, users can easily build formulaic alphas.
|
In ``Qlib``, users can easily build formulaic alphas.
|
||||||
|
|
||||||
Example
|
Example
|
||||||
-----------------
|
-------
|
||||||
|
|
||||||
`MACD`, short for moving average convergence/divergence, is a formulaic alpha used in technical analysis of stock prices. It is designed to reveal changes in the strength, direction, momentum, and duration of a trend in a stock's price.
|
`MACD`, short for moving average convergence/divergence, is a formulaic alpha used in technical analysis of stock prices. It is designed to reveal changes in the strength, direction, momentum, and duration of a trend in a stock's price.
|
||||||
|
|
||||||
`MACD` can be presented as the following formula:
|
`MACD` can be presented as the following formula:
|
||||||
|
|
||||||
.. math::
|
.. math::
|
||||||
|
|
||||||
MACD = 2\times (DIF-DEA)
|
MACD = 2\times (DIF-DEA)
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
`DIF` means Differential value, which is 12-period EMA minus 26-period EMA.
|
`DIF` means Differential value, which is 12-period EMA minus 26-period EMA.
|
||||||
|
|
||||||
.. math::
|
.. math::
|
||||||
|
|
||||||
DIF = \frac{EMA(CLOSE, 12) - EMA(CLOSE, 26)}{CLOSE}
|
DIF = \frac{EMA(CLOSE, 12) - EMA(CLOSE, 26)}{CLOSE}
|
||||||
|
|
||||||
`DEA`means a 9-period EMA of the DIF.
|
`DEA`means a 9-period EMA of the DIF.
|
||||||
|
|
||||||
@@ -65,7 +65,7 @@ Users can use ``Data Handler`` to build formulaic alphas `MACD` in qlib:
|
|||||||
>> print(df)
|
>> print(df)
|
||||||
feature label
|
feature label
|
||||||
MACD LABEL
|
MACD LABEL
|
||||||
datetime instrument
|
datetime instrument
|
||||||
2010-01-04 SH600000 -0.011547 -0.019672
|
2010-01-04 SH600000 -0.011547 -0.019672
|
||||||
SH600004 0.002745 -0.014721
|
SH600004 0.002745 -0.014721
|
||||||
SH600006 0.010133 0.002911
|
SH600006 0.010133 0.002911
|
||||||
@@ -79,7 +79,7 @@ Users can use ``Data Handler`` to build formulaic alphas `MACD` in qlib:
|
|||||||
SZ300315 -0.030557 0.012455
|
SZ300315 -0.030557 0.012455
|
||||||
|
|
||||||
Reference
|
Reference
|
||||||
===========
|
=========
|
||||||
|
|
||||||
To learn more about ``Data Loader``, please refer to `Data Loader <../component/data.html#data-loader>`_
|
To learn more about ``Data Loader``, please refer to `Data Loader <../component/data.html#data-loader>`_
|
||||||
|
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
.. _serial:
|
.. _serial:
|
||||||
|
|
||||||
=================================
|
=============
|
||||||
Serialization
|
Serialization
|
||||||
=================================
|
=============
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
``Qlib`` supports dumping the state of ``DataHandler``, ``DataSet``, ``Processor`` and ``Model``, etc. into a disk and reloading them.
|
``Qlib`` supports dumping the state of ``DataHandler``, ``DataSet``, ``Processor`` and ``Model``, etc. into a disk and reloading them.
|
||||||
|
|
||||||
Serializable Class
|
Serializable Class
|
||||||
========================
|
==================
|
||||||
|
|
||||||
``Qlib`` provides a base class ``qlib.utils.serial.Serializable``, whose state can be dumped into or loaded from disk in `pickle` format.
|
``Qlib`` provides a base class ``qlib.utils.serial.Serializable``, whose state can be dumped into or loaded from disk in `pickle` format.
|
||||||
When users dump the state of a ``Serializable`` instance, the attributes of the instance whose name **does not** start with `_` will be saved on the disk.
|
When users dump the state of a ``Serializable`` instance, the attributes of the instance whose name **does not** start with `_` will be saved on the disk.
|
||||||
However, users can use ``config`` method or override ``default_dump_all`` attribute to prevent this feature.
|
However, users can use ``config`` method or override ``default_dump_all`` attribute to prevent this feature.
|
||||||
|
|
||||||
Users can also override ``pickle_backend`` attribute to choose a pickle backend. The supported value is "pickle" (default and common) and "dill" (dump more things such as function, more information in `here <https://pypi.org/project/dill/>`_).
|
Users can also override ``pickle_backend`` attribute to choose a pickle backend. The supported value is "pickle" (default and common) and "dill" (dump more things such as function, more information in `here <https://pypi.org/project/dill/>`_).
|
||||||
|
|
||||||
Example
|
Example
|
||||||
==========================
|
=======
|
||||||
``Qlib``'s serializable class includes ``DataHandler``, ``DataSet``, ``Processor`` and ``Model``, etc., which are subclass of ``qlib.utils.serial.Serializable``.
|
``Qlib``'s serializable class includes ``DataHandler``, ``DataSet``, ``Processor`` and ``Model``, etc., which are subclass of ``qlib.utils.serial.Serializable``.
|
||||||
Specifically, ``qlib.data.dataset.DatasetH`` is one of them. Users can serialize ``DatasetH`` as follows.
|
Specifically, ``qlib.data.dataset.DatasetH`` is one of them. Users can serialize ``DatasetH`` as follows.
|
||||||
|
|
||||||
.. code-block:: Python
|
.. code-block:: Python
|
||||||
@@ -33,7 +33,7 @@ Specifically, ``qlib.data.dataset.DatasetH`` is one of them. Users can serialize
|
|||||||
dataset = pickle.load(file_dataset)
|
dataset = pickle.load(file_dataset)
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
Only state of ``DatasetH`` should be saved on the disk, such as some `mean` and `variance` used for data normalization, etc.
|
Only state of ``DatasetH`` should be saved on the disk, such as some `mean` and `variance` used for data normalization, etc.
|
||||||
|
|
||||||
After reloading the ``DatasetH``, users need to reinitialize it. It means that users can reset some states of ``DatasetH`` or ``QlibDataHandler`` such as `instruments`, `start_time`, `end_time` and `segments`, etc., and generate new data according to the states (data is not state and should not be saved on the disk).
|
After reloading the ``DatasetH``, users need to reinitialize it. It means that users can reset some states of ``DatasetH`` or ``QlibDataHandler`` such as `instruments`, `start_time`, `end_time` and `segments`, etc., and generate new data according to the states (data is not state and should not be saved on the disk).
|
||||||
|
|
||||||
@@ -41,5 +41,5 @@ A more detailed example is in this `link <https://github.com/microsoft/qlib/tree
|
|||||||
|
|
||||||
|
|
||||||
API
|
API
|
||||||
===================
|
===
|
||||||
Please refer to `Serializable API <../reference/api.html#module-qlib.utils.serial.Serializable>`_.
|
Please refer to `Serializable API <../reference/api.html#module-qlib.utils.serial.Serializable>`_.
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
.. _server:
|
.. _server:
|
||||||
|
|
||||||
=================================
|
=============================
|
||||||
``Online`` & ``Offline`` mode
|
``Online`` & ``Offline`` mode
|
||||||
=================================
|
=============================
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
=============
|
============
|
||||||
|
|
||||||
``Qlib`` supports ``Online`` mode and ``Offline`` mode. Only the ``Offline`` mode is introduced in this document.
|
``Qlib`` supports ``Online`` mode and ``Offline`` mode. Only the ``Offline`` mode is introduced in this document.
|
||||||
|
|
||||||
The ``Online`` mode is designed to solve the following problems:
|
The ``Online`` mode is designed to solve the following problems:
|
||||||
|
|
||||||
@@ -18,12 +18,12 @@ The ``Online`` mode is designed to solve the following problems:
|
|||||||
- Make the data can be accessed in a remote way.
|
- Make the data can be accessed in a remote way.
|
||||||
|
|
||||||
Qlib-Server
|
Qlib-Server
|
||||||
===============
|
===========
|
||||||
|
|
||||||
``Qlib-Server`` is the assorted server system for ``Qlib``, which utilizes ``Qlib`` for basic calculations and provides extensive server system and cache mechanism. With QLibServer, the data provided for ``Qlib`` can be managed in a centralized manner. With ``Qlib-Server``, users can use ``Qlib`` in ``Online`` mode.
|
``Qlib-Server`` is the assorted server system for ``Qlib``, which utilizes ``Qlib`` for basic calculations and provides extensive server system and cache mechanism. With QLibServer, the data provided for ``Qlib`` can be managed in a centralized manner. With ``Qlib-Server``, users can use ``Qlib`` in ``Online`` mode.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Reference
|
Reference
|
||||||
=================
|
=========
|
||||||
If users are interested in ``Qlib-Server`` and ``Online`` mode, please refer to `Qlib-Server Project <https://github.com/microsoft/qlib-server>`_ and `Qlib-Server Document <https://qlib-server.readthedocs.io/en/latest/>`_.
|
If users are interested in ``Qlib-Server`` and ``Online`` mode, please refer to `Qlib-Server Project <https://github.com/microsoft/qlib-server>`_ and `Qlib-Server Document <https://qlib-server.readthedocs.io/en/latest/>`_.
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
.. _task_management:
|
.. _task_management:
|
||||||
|
|
||||||
=================================
|
===============
|
||||||
Task Management
|
Task Management
|
||||||
=================================
|
===============
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
=============
|
============
|
||||||
|
|
||||||
The `Workflow <../component/introduction.html>`_ part introduces how to run research workflow in a loosely-coupled way. But it can only execute one ``task`` when you use ``qrun``.
|
The `Workflow <../component/introduction.html>`_ part introduces how to run research workflow in a loosely-coupled way. But it can only execute one ``task`` when you use ``qrun``.
|
||||||
To automatically generate and execute different tasks, ``Task Management`` provides a whole process including `Task Generating`_, `Task Storing`_, `Task Training`_ and `Task Collecting`_.
|
To automatically generate and execute different tasks, ``Task Management`` provides a whole process including `Task Generating`_, `Task Storing`_, `Task Training`_ and `Task Collecting`_.
|
||||||
@@ -36,7 +36,7 @@ Here is the base class of ``TaskGen``:
|
|||||||
This class allows users to verify the effect of data from different periods on the model in one experiment. More information is `here <../reference/api.html#TaskGen>`_.
|
This class allows users to verify the effect of data from different periods on the model in one experiment. More information is `here <../reference/api.html#TaskGen>`_.
|
||||||
|
|
||||||
Task Storing
|
Task Storing
|
||||||
===============
|
============
|
||||||
To achieve higher efficiency and the possibility of cluster operation, ``Task Manager`` will store all tasks in `MongoDB <https://www.mongodb.com/>`_.
|
To achieve higher efficiency and the possibility of cluster operation, ``Task Manager`` will store all tasks in `MongoDB <https://www.mongodb.com/>`_.
|
||||||
``TaskManager`` can fetch undone tasks automatically and manage the lifecycle of a set of tasks with error handling.
|
``TaskManager`` can fetch undone tasks automatically and manage the lifecycle of a set of tasks with error handling.
|
||||||
Users **MUST** finish the configuration of `MongoDB <https://www.mongodb.com/>`_ when using this module.
|
Users **MUST** finish the configuration of `MongoDB <https://www.mongodb.com/>`_ when using this module.
|
||||||
@@ -57,7 +57,7 @@ Users need to provide the MongoDB URL and database name for using ``TaskManager`
|
|||||||
More information of ``Task Manager`` can be found in `here <../reference/api.html#TaskManager>`_.
|
More information of ``Task Manager`` can be found in `here <../reference/api.html#TaskManager>`_.
|
||||||
|
|
||||||
Task Training
|
Task Training
|
||||||
===============
|
=============
|
||||||
After generating and storing those ``task``, it's time to run the ``task`` which is in the *WAITING* status.
|
After generating and storing those ``task``, it's time to run the ``task`` which is in the *WAITING* status.
|
||||||
``Qlib`` provides a method called ``run_task`` to run those ``task`` in task pool, however, users can also customize how tasks are executed.
|
``Qlib`` provides a method called ``run_task`` to run those ``task`` in task pool, however, users can also customize how tasks are executed.
|
||||||
An easy way to get the ``task_func`` is using ``qlib.model.trainer.task_train`` directly.
|
An easy way to get the ``task_func`` is using ``qlib.model.trainer.task_train`` directly.
|
||||||
|
|||||||
@@ -1,2 +1 @@
|
|||||||
.. include:: ../../CHANGES.rst
|
.. include:: ../../CHANGES.rst
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
.. _data:
|
.. _data:
|
||||||
|
|
||||||
================================
|
==================================
|
||||||
Data Layer: Data Framework & Usage
|
Data Layer: Data Framework & Usage
|
||||||
================================
|
==================================
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
============================
|
============
|
||||||
|
|
||||||
``Data Layer`` provides user-friendly APIs to manage and retrieve data. It provides high-performance data infrastructure.
|
``Data Layer`` provides user-friendly APIs to manage and retrieve data. It provides high-performance data infrastructure.
|
||||||
|
|
||||||
It is designed for quantitative investment. For example, users could build formulaic alphas with ``Data Layer`` easily. Please refer to `Building Formulaic Alphas <../advanced/alpha.html>`_ for more details.
|
It is designed for quantitative investment. For example, users could build formulaic alphas with ``Data Layer`` easily. Please refer to `Building Formulaic Alphas <../advanced/alpha.html>`_ for more details.
|
||||||
|
|
||||||
@@ -23,16 +23,16 @@ The introduction of ``Data Layer`` includes the following parts.
|
|||||||
|
|
||||||
Here is a typical example of Qlib data workflow
|
Here is a typical example of Qlib data workflow
|
||||||
|
|
||||||
- Users download data and converting data into Qlib format(with filename suffix `.bin`). In this step, typically only some basic data are stored on disk(such as OHLCV).
|
- Users download data and converting data into Qlib format(with filename suffix `.bin`). In this step, typically only some basic data are stored on disk(such as OHLCV).
|
||||||
- Creating some basic features based on Qlib's expression Engine(e.g. "Ref($close, 60) / $close", the return of last 60 trading days). Supported operators in the expression engine can be found `here <https://github.com/microsoft/qlib/blob/main/qlib/data/ops.py>`_. This step is typically implemented in Qlib's `Data Loader <https://qlib.readthedocs.io/en/latest/component/data.html#data-loader>`_ which is a component of `Data Handler <https://qlib.readthedocs.io/en/latest/component/data.html#data-handler>`_ .
|
- Creating some basic features based on Qlib's expression Engine(e.g. "Ref($close, 60) / $close", the return of last 60 trading days). Supported operators in the expression engine can be found `here <https://github.com/microsoft/qlib/blob/main/qlib/data/ops.py>`_. This step is typically implemented in Qlib's `Data Loader <https://qlib.readthedocs.io/en/latest/component/data.html#data-loader>`_ which is a component of `Data Handler <https://qlib.readthedocs.io/en/latest/component/data.html#data-handler>`_ .
|
||||||
- If users require more complicated data processing (e.g. data normalization), `Data Handler <https://qlib.readthedocs.io/en/latest/component/data.html#data-handler>`_ support user-customized processors to process data(some predefined processors can be found `here <https://github.com/microsoft/qlib/blob/main/qlib/data/dataset/processor.py>`_). The processors are different from operators in expression engine. It is designed for some complicated data processing methods which is hard to supported in operators in expression engine.
|
- If users require more complicated data processing (e.g. data normalization), `Data Handler <https://qlib.readthedocs.io/en/latest/component/data.html#data-handler>`_ support user-customized processors to process data(some predefined processors can be found `here <https://github.com/microsoft/qlib/blob/main/qlib/data/dataset/processor.py>`_). The processors are different from operators in expression engine. It is designed for some complicated data processing methods which is hard to supported in operators in expression engine.
|
||||||
- At last, `Dataset <https://qlib.readthedocs.io/en/latest/component/data.html#dataset>`_ is responsible to prepare model-specific dataset from the processed data of Data Handler
|
- At last, `Dataset <https://qlib.readthedocs.io/en/latest/component/data.html#dataset>`_ is responsible to prepare model-specific dataset from the processed data of Data Handler
|
||||||
|
|
||||||
Data Preparation
|
Data Preparation
|
||||||
============================
|
================
|
||||||
|
|
||||||
Qlib Format Data
|
Qlib Format Data
|
||||||
------------------
|
----------------
|
||||||
|
|
||||||
We've specially designed a data structure to manage financial data, please refer to the `File storage design section in Qlib paper <https://arxiv.org/abs/2009.11189>`_ for detailed information.
|
We've specially designed a data structure to manage financial data, please refer to the `File storage design section in Qlib paper <https://arxiv.org/abs/2009.11189>`_ for detailed information.
|
||||||
Such data will be stored with filename suffix `.bin` (We'll call them `.bin` file, `.bin` format, or qlib format). `.bin` file is designed for scientific computing on finance data.
|
Such data will be stored with filename suffix `.bin` (We'll call them `.bin` file, `.bin` format, or qlib format). `.bin` file is designed for scientific computing on finance data.
|
||||||
@@ -50,11 +50,16 @@ Alpha158 √ √
|
|||||||
Also, ``Qlib`` provides a high-frequency dataset. Users can run a high-frequency dataset example through this `link <https://github.com/microsoft/qlib/tree/main/examples/highfreq>`_.
|
Also, ``Qlib`` provides a high-frequency dataset. Users can run a high-frequency dataset example through this `link <https://github.com/microsoft/qlib/tree/main/examples/highfreq>`_.
|
||||||
|
|
||||||
Qlib Format Dataset
|
Qlib Format Dataset
|
||||||
--------------------
|
-------------------
|
||||||
``Qlib`` has provided an off-the-shelf dataset in `.bin` format, users could use the script ``scripts/get_data.py`` to download the China-Stock dataset as follows.
|
``Qlib`` has provided an off-the-shelf dataset in `.bin` format, users could use the script ``scripts/get_data.py`` to download the China-Stock dataset as follows. User can also use numpy to load `.bin` file to validate data.
|
||||||
The price volume data look different from the actual dealling price because of they are **adjusted** (`adjusted price <https://www.investopedia.com/terms/a/adjusted_closing_price.asp>`_). And then you may find that the adjusted price may be different from different data sources. This is because different data sources may vary in the way of adjusting prices. Qlib normalize the price on first trading day of each stock to 1 when adjusting them.
|
The price volume data look different from the actual dealling price because of they are **adjusted** (`adjusted price <https://www.investopedia.com/terms/a/adjusted_closing_price.asp>`_). And then you may find that the adjusted price may be different from different data sources. This is because different data sources may vary in the way of adjusting prices. Qlib normalize the price on first trading day of each stock to 1 when adjusting them.
|
||||||
Users can leverage `$factor` to get the original trading price (e.g. `$close / $factor` to get the original close price).
|
Users can leverage `$factor` to get the original trading price (e.g. `$close / $factor` to get the original close price).
|
||||||
|
|
||||||
|
Here are some discussions about the price adjusting of Qlib.
|
||||||
|
|
||||||
|
- https://github.com/microsoft/qlib/issues/991#issuecomment-1075252402
|
||||||
|
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
# download 1d
|
# download 1d
|
||||||
@@ -104,7 +109,7 @@ Automatic update of daily frequency data
|
|||||||
|
|
||||||
|
|
||||||
Converting CSV Format into Qlib Format
|
Converting CSV Format into Qlib Format
|
||||||
-------------------------------------------
|
--------------------------------------
|
||||||
|
|
||||||
``Qlib`` has provided the script ``scripts/dump_bin.py`` to convert **any** data in CSV format into `.bin` files (``Qlib`` format) as long as they are in the correct format.
|
``Qlib`` has provided the script ``scripts/dump_bin.py`` to convert **any** data in CSV format into `.bin` files (``Qlib`` format) as long as they are in the correct format.
|
||||||
|
|
||||||
@@ -126,16 +131,16 @@ Users can also provide their own data in CSV format. However, the CSV data **mus
|
|||||||
- CSV file is named after a specific stock *or* the CSV file includes a column of the stock name
|
- CSV file is named after a specific stock *or* the CSV file includes a column of the stock name
|
||||||
|
|
||||||
- Name the CSV file after a stock: `SH600000.csv`, `AAPL.csv` (not case sensitive).
|
- Name the CSV file after a stock: `SH600000.csv`, `AAPL.csv` (not case sensitive).
|
||||||
|
|
||||||
- CSV file includes a column of the stock name. User **must** specify the column name when dumping the data. Here is an example:
|
- CSV file includes a column of the stock name. User **must** specify the column name when dumping the data. Here is an example:
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
python scripts/dump_bin.py dump_all ... --symbol_field_name symbol
|
python scripts/dump_bin.py dump_all ... --symbol_field_name symbol
|
||||||
|
|
||||||
where the data are in the following format:
|
where the data are in the following format:
|
||||||
|
|
||||||
.. code-block::
|
.. code-block::
|
||||||
|
|
||||||
symbol,close
|
symbol,close
|
||||||
SH600000,120
|
SH600000,120
|
||||||
@@ -145,10 +150,10 @@ Users can also provide their own data in CSV format. However, the CSV data **mus
|
|||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
python scripts/dump_bin.py dump_all ... --date_field_name date
|
python scripts/dump_bin.py dump_all ... --date_field_name date
|
||||||
|
|
||||||
where the data are in the following format:
|
where the data are in the following format:
|
||||||
|
|
||||||
.. code-block::
|
.. code-block::
|
||||||
|
|
||||||
symbol,date,close,open,volume
|
symbol,date,close,open,volume
|
||||||
SH600000,2020-11-01,120,121,12300000
|
SH600000,2020-11-01,120,121,12300000
|
||||||
@@ -172,7 +177,7 @@ After conversion, users can find their Qlib format data in the directory `~/.qli
|
|||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
The arguments of `--include_fields` should correspond with the column names of CSV files. The columns names of dataset provided by ``Qlib`` should include open, close, high, low, volume and factor at least.
|
The arguments of `--include_fields` should correspond with the column names of CSV files. The columns names of dataset provided by ``Qlib`` should include open, close, high, low, volume and factor at least.
|
||||||
|
|
||||||
- `open`
|
- `open`
|
||||||
The adjusted opening price
|
The adjusted opening price
|
||||||
- `close`
|
- `close`
|
||||||
@@ -186,11 +191,11 @@ After conversion, users can find their Qlib format data in the directory `~/.qli
|
|||||||
- `factor`
|
- `factor`
|
||||||
The Restoration factor. Normally, ``factor = adjusted_price / original_price``, `adjusted price` reference: `split adjusted <https://www.investopedia.com/terms/s/splitadjusted.asp>`_
|
The Restoration factor. Normally, ``factor = adjusted_price / original_price``, `adjusted price` reference: `split adjusted <https://www.investopedia.com/terms/s/splitadjusted.asp>`_
|
||||||
|
|
||||||
In the convention of `Qlib` data processing, `open, close, high, low, volume, money and factor` will be set to NaN if the stock is suspended.
|
In the convention of `Qlib` data processing, `open, close, high, low, volume, money and factor` will be set to NaN if the stock is suspended.
|
||||||
If you want to use your own alpha-factor which can't be calculate by OCHLV, like PE, EPS and so on, you could add it to the CSV files with OHCLV together and then dump it to the Qlib format data.
|
If you want to use your own alpha-factor which can't be calculate by OCHLV, like PE, EPS and so on, you could add it to the CSV files with OHCLV together and then dump it to the Qlib format data.
|
||||||
|
|
||||||
Stock Pool (Market)
|
Stock Pool (Market)
|
||||||
--------------------------------
|
-------------------
|
||||||
|
|
||||||
``Qlib`` defines `stock pool <https://github.com/microsoft/qlib/blob/main/examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml#L4>`_ as stock list and their date ranges. Predefined stock pools (e.g. csi300) may be imported as follows.
|
``Qlib`` defines `stock pool <https://github.com/microsoft/qlib/blob/main/examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml#L4>`_ as stock list and their date ranges. Predefined stock pools (e.g. csi300) may be imported as follows.
|
||||||
|
|
||||||
@@ -200,7 +205,7 @@ Stock Pool (Market)
|
|||||||
|
|
||||||
|
|
||||||
Multiple Stock Modes
|
Multiple Stock Modes
|
||||||
--------------------------------
|
--------------------
|
||||||
|
|
||||||
``Qlib`` now provides two different stock modes for users: China-Stock Mode & US-Stock Mode. Here are some different settings of these two modes:
|
``Qlib`` now provides two different stock modes for users: China-Stock Mode & US-Stock Mode. Here are some different settings of these two modes:
|
||||||
|
|
||||||
@@ -218,23 +223,23 @@ The `trade unit` defines the unit number of stocks can be used in a trade, and t
|
|||||||
- Download china-stock in qlib format, please refer to section `Qlib Format Dataset <#qlib-format-dataset>`_.
|
- Download china-stock in qlib format, please refer to section `Qlib Format Dataset <#qlib-format-dataset>`_.
|
||||||
- Initialize ``Qlib`` in china-stock mode
|
- Initialize ``Qlib`` in china-stock mode
|
||||||
Supposed that users download their Qlib format data in the directory ``~/.qlib/qlib_data/cn_data``. Users only need to initialize ``Qlib`` as follows.
|
Supposed that users download their Qlib format data in the directory ``~/.qlib/qlib_data/cn_data``. Users only need to initialize ``Qlib`` as follows.
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
from qlib.constant import REG_CN
|
from qlib.constant import REG_CN
|
||||||
qlib.init(provider_uri='~/.qlib/qlib_data/cn_data', region=REG_CN)
|
qlib.init(provider_uri='~/.qlib/qlib_data/cn_data', region=REG_CN)
|
||||||
|
|
||||||
|
|
||||||
- If users use ``Qlib`` in US-stock mode, US-stock data is required. ``Qlib`` also provides a script to download US-stock data. Users can use ``Qlib`` in US-stock mode according to the following steps:
|
- If users use ``Qlib`` in US-stock mode, US-stock data is required. ``Qlib`` also provides a script to download US-stock data. Users can use ``Qlib`` in US-stock mode according to the following steps:
|
||||||
- Download us-stock in qlib format, please refer to section `Qlib Format Dataset <#qlib-format-dataset>`_.
|
- Download us-stock in qlib format, please refer to section `Qlib Format Dataset <#qlib-format-dataset>`_.
|
||||||
- Initialize ``Qlib`` in US-stock mode
|
- Initialize ``Qlib`` in US-stock mode
|
||||||
Supposed that users prepare their Qlib format data in the directory ``~/.qlib/qlib_data/us_data``. Users only need to initialize ``Qlib`` as follows.
|
Supposed that users prepare their Qlib format data in the directory ``~/.qlib/qlib_data/us_data``. Users only need to initialize ``Qlib`` as follows.
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
from qlib.config import REG_US
|
from qlib.config import REG_US
|
||||||
qlib.init(provider_uri='~/.qlib/qlib_data/us_data', region=REG_US)
|
qlib.init(provider_uri='~/.qlib/qlib_data/us_data', region=REG_US)
|
||||||
|
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
@@ -242,14 +247,14 @@ The `trade unit` defines the unit number of stocks can be used in a trade, and t
|
|||||||
|
|
||||||
|
|
||||||
Data API
|
Data API
|
||||||
========================
|
========
|
||||||
|
|
||||||
Data Retrieval
|
Data Retrieval
|
||||||
---------------
|
--------------
|
||||||
Users can use APIs in ``qlib.data`` to retrieve data, please refer to `Data Retrieval <../start/getdata.html>`_.
|
Users can use APIs in ``qlib.data`` to retrieve data, please refer to `Data Retrieval <../start/getdata.html>`_.
|
||||||
|
|
||||||
Feature
|
Feature
|
||||||
------------------
|
-------
|
||||||
|
|
||||||
``Qlib`` provides `Feature` and `ExpressionOps` to fetch the features according to users' needs.
|
``Qlib`` provides `Feature` and `ExpressionOps` to fetch the features according to users' needs.
|
||||||
|
|
||||||
@@ -264,7 +269,7 @@ Feature
|
|||||||
To know more about ``Feature``, please refer to `Feature API <../reference/api.html#module-qlib.data.base>`_.
|
To know more about ``Feature``, please refer to `Feature API <../reference/api.html#module-qlib.data.base>`_.
|
||||||
|
|
||||||
Filter
|
Filter
|
||||||
-------------------
|
------
|
||||||
``Qlib`` provides `NameDFilter` and `ExpressionDFilter` to filter the instruments according to users' needs.
|
``Qlib`` provides `NameDFilter` and `ExpressionDFilter` to filter the instruments according to users' needs.
|
||||||
|
|
||||||
- `NameDFilter`
|
- `NameDFilter`
|
||||||
@@ -272,7 +277,7 @@ Filter
|
|||||||
|
|
||||||
- `ExpressionDFilter`
|
- `ExpressionDFilter`
|
||||||
Expression dynamic instrument filter. Filter the instruments based on a certain expression. An expression rule indicating a certain feature field is required.
|
Expression dynamic instrument filter. Filter the instruments based on a certain expression. An expression rule indicating a certain feature field is required.
|
||||||
|
|
||||||
- `basic features filter`: rule_expression = '$close/$open>5'
|
- `basic features filter`: rule_expression = '$close/$open>5'
|
||||||
- `cross-sectional features filter` \: rule_expression = '$rank($close)<10'
|
- `cross-sectional features filter` \: rule_expression = '$rank($close)<10'
|
||||||
- `time-sequence features filter`: rule_expression = '$Ref($close, 3)>100'
|
- `time-sequence features filter`: rule_expression = '$Ref($close, 3)>100'
|
||||||
@@ -299,29 +304,29 @@ Here is a simple example showing how to use filter in a basic ``Qlib`` workflow
|
|||||||
To know more about ``Filter``, please refer to `Filter API <../reference/api.html#module-qlib.data.filter>`_.
|
To know more about ``Filter``, please refer to `Filter API <../reference/api.html#module-qlib.data.filter>`_.
|
||||||
|
|
||||||
Reference
|
Reference
|
||||||
-------------
|
---------
|
||||||
|
|
||||||
To know more about ``Data API``, please refer to `Data API <../reference/api.html#data>`_.
|
To know more about ``Data API``, please refer to `Data API <../reference/api.html#data>`_.
|
||||||
|
|
||||||
|
|
||||||
Data Loader
|
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.
|
``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
|
QlibDataLoader
|
||||||
---------------
|
--------------
|
||||||
|
|
||||||
The ``QlibDataLoader`` class in ``Qlib`` is such an interface that allows users to load raw data from the ``Qlib`` data source.
|
The ``QlibDataLoader`` class in ``Qlib`` is such an interface that allows users to load raw data from the ``Qlib`` data source.
|
||||||
|
|
||||||
StaticDataLoader
|
StaticDataLoader
|
||||||
---------------
|
----------------
|
||||||
|
|
||||||
The ``StaticDataLoader`` class in ``Qlib`` is such an interface that allows users to load raw data from file or as provided.
|
The ``StaticDataLoader`` class in ``Qlib`` is such an interface that allows users to load raw data from file or as provided.
|
||||||
|
|
||||||
|
|
||||||
Interface
|
Interface
|
||||||
------------
|
---------
|
||||||
|
|
||||||
Here are some interfaces of the ``QlibDataLoader`` class:
|
Here are some interfaces of the ``QlibDataLoader`` class:
|
||||||
|
|
||||||
@@ -329,28 +334,28 @@ Here are some interfaces of the ``QlibDataLoader`` class:
|
|||||||
:members:
|
:members:
|
||||||
|
|
||||||
API
|
API
|
||||||
-----------
|
---
|
||||||
|
|
||||||
To know more about ``Data Loader``, please refer to `Data Loader API <../reference/api.html#module-qlib.data.dataset.loader>`_.
|
To know more about ``Data Loader``, please refer to `Data Loader API <../reference/api.html#module-qlib.data.dataset.loader>`_.
|
||||||
|
|
||||||
|
|
||||||
Data Handler
|
Data Handler
|
||||||
=================
|
============
|
||||||
|
|
||||||
The ``Data Handler`` module in ``Qlib`` is designed to handler those common data processing methods which will be used by most of the models.
|
The ``Data Handler`` module in ``Qlib`` is designed to handler those common data processing methods which will be used by most of the models.
|
||||||
|
|
||||||
Users can use ``Data Handler`` in an automatic workflow by ``qrun``, refer to `Workflow: Workflow Management <workflow.html>`_ for more details.
|
Users can use ``Data Handler`` in an automatic workflow by ``qrun``, refer to `Workflow: Workflow Management <workflow.html>`_ for more details.
|
||||||
|
|
||||||
DataHandlerLP
|
DataHandlerLP
|
||||||
--------------
|
-------------
|
||||||
|
|
||||||
In addition to use ``Data Handler`` in an automatic workflow with ``qrun``, ``Data Handler`` can be used as an independent module, by which users can easily preprocess data (standardization, remove NaN, etc.) and build datasets.
|
In addition to use ``Data Handler`` in an automatic workflow with ``qrun``, ``Data Handler`` can be used as an independent module, by which users can easily preprocess data (standardization, remove NaN, etc.) and build datasets.
|
||||||
|
|
||||||
In order to achieve so, ``Qlib`` provides a base class `qlib.data.dataset.DataHandlerLP <../reference/api.html#qlib.data.dataset.handler.DataHandlerLP>`_. The core idea of this class is that: we will have some learnable ``Processors`` which can learn the parameters of data processing(e.g., parameters for zscore normalization). When new data comes in, these `trained` ``Processors`` can then process the new data and thus processing real-time data in an efficient way becomes possible. More information about ``Processors`` will be listed in the next subsection.
|
In order to achieve so, ``Qlib`` provides a base class `qlib.data.dataset.DataHandlerLP <../reference/api.html#qlib.data.dataset.handler.DataHandlerLP>`_. The core idea of this class is that: we will have some learnable ``Processors`` which can learn the parameters of data processing(e.g., parameters for zscore normalization). When new data comes in, these `trained` ``Processors`` can then process the new data and thus processing real-time data in an efficient way becomes possible. More information about ``Processors`` will be listed in the next subsection.
|
||||||
|
|
||||||
|
|
||||||
Interface
|
Interface
|
||||||
----------------------
|
---------
|
||||||
|
|
||||||
Here are some important interfaces that ``DataHandlerLP`` provides:
|
Here are some important interfaces that ``DataHandlerLP`` provides:
|
||||||
|
|
||||||
@@ -364,7 +369,7 @@ Also, users can pass ``qlib.contrib.data.processor.ConfigSectionProcessor`` that
|
|||||||
|
|
||||||
|
|
||||||
Processor
|
Processor
|
||||||
----------
|
---------
|
||||||
|
|
||||||
The ``Processor`` module in ``Qlib`` is designed to be learnable and it is responsible for handling data processing such as `normalization` and `drop none/nan features/labels`.
|
The ``Processor`` module in ``Qlib`` is designed to be learnable and it is responsible for handling data processing such as `normalization` and `drop none/nan features/labels`.
|
||||||
|
|
||||||
@@ -382,14 +387,14 @@ The ``Processor`` module in ``Qlib`` is designed to be learnable and it is respo
|
|||||||
- ``CSRankNorm``: `processor` that applies cross sectional rank normalization.
|
- ``CSRankNorm``: `processor` that applies cross sectional rank normalization.
|
||||||
- ``CSZFillna``: `processor` that fills N/A values in a cross sectional way by the mean of the column.
|
- ``CSZFillna``: `processor` that fills N/A values in a cross sectional way by the mean of the column.
|
||||||
|
|
||||||
Users can also create their own `processor` by inheriting the base class of ``Processor``. Please refer to the implementation of all the processors for more information (`Processor Link <https://github.com/microsoft/qlib/blob/main/qlib/data/dataset/processor.py>`_).
|
Users can also create their own `processor` by inheriting the base class of ``Processor``. Please refer to the implementation of all the processors for more information (`Processor Link <https://github.com/microsoft/qlib/blob/main/qlib/data/dataset/processor.py>`_).
|
||||||
|
|
||||||
To know more about ``Processor``, please refer to `Processor API <../reference/api.html#module-qlib.data.dataset.processor>`_.
|
To know more about ``Processor``, please refer to `Processor API <../reference/api.html#module-qlib.data.dataset.processor>`_.
|
||||||
|
|
||||||
Example
|
Example
|
||||||
--------------
|
-------
|
||||||
|
|
||||||
``Data Handler`` can be run with ``qrun`` by modifying the configuration file, and can also be used as a single module.
|
``Data Handler`` can be run with ``qrun`` by modifying the configuration file, and can also be used as a single module.
|
||||||
|
|
||||||
Know more about how to run ``Data Handler`` with ``qrun``, please refer to `Workflow: Workflow Management <workflow.html>`_
|
Know more about how to run ``Data Handler`` with ``qrun``, please refer to `Workflow: Workflow Management <workflow.html>`_
|
||||||
|
|
||||||
@@ -427,17 +432,17 @@ Qlib provides implemented data handler `Alpha158`. The following example shows h
|
|||||||
.. note:: In the ``Alpha158``, ``Qlib`` uses the label `Ref($close, -2)/Ref($close, -1) - 1` that means the change from T+1 to T+2, rather than `Ref($close, -1)/$close - 1`, of which the reason is that when getting the T day close price of a china stock, the stock can be bought on T+1 day and sold on T+2 day.
|
.. note:: In the ``Alpha158``, ``Qlib`` uses the label `Ref($close, -2)/Ref($close, -1) - 1` that means the change from T+1 to T+2, rather than `Ref($close, -1)/$close - 1`, of which the reason is that when getting the T day close price of a china stock, the stock can be bought on T+1 day and sold on T+2 day.
|
||||||
|
|
||||||
API
|
API
|
||||||
---------
|
---
|
||||||
|
|
||||||
To know more about ``Data Handler``, please refer to `Data Handler API <../reference/api.html#module-qlib.data.dataset.handler>`_.
|
To know more about ``Data Handler``, please refer to `Data Handler API <../reference/api.html#module-qlib.data.dataset.handler>`_.
|
||||||
|
|
||||||
|
|
||||||
Dataset
|
Dataset
|
||||||
=================
|
=======
|
||||||
|
|
||||||
The ``Dataset`` module in ``Qlib`` aims to prepare data for model training and inferencing.
|
The ``Dataset`` module in ``Qlib`` aims to prepare data for model training and inferencing.
|
||||||
|
|
||||||
The motivation of this module is that we want to maximize the flexibility of different models to handle data that are suitable for themselves. This module gives the model the flexibility to process their data in an unique way. For instance, models such as ``GBDT`` may work well on data that contains `nan` or `None` value, while neural networks such as ``MLP`` will break down on such data.
|
The motivation of this module is that we want to maximize the flexibility of different models to handle data that are suitable for themselves. This module gives the model the flexibility to process their data in an unique way. For instance, models such as ``GBDT`` may work well on data that contains `nan` or `None` value, while neural networks such as ``MLP`` will break down on such data.
|
||||||
|
|
||||||
If user's model need process its data in a different way, user could implement his own ``Dataset`` class. If the model's
|
If user's model need process its data in a different way, user could implement his own ``Dataset`` class. If the model's
|
||||||
data processing is not special, ``DatasetH`` can be used directly.
|
data processing is not special, ``DatasetH`` can be used directly.
|
||||||
@@ -448,18 +453,18 @@ The ``DatasetH`` class is the `dataset` with `Data Handler`. Here is the most im
|
|||||||
:members:
|
:members:
|
||||||
|
|
||||||
API
|
API
|
||||||
---------
|
---
|
||||||
|
|
||||||
To know more about ``Dataset``, please refer to `Dataset API <../reference/api.html#dataset>`_.
|
To know more about ``Dataset``, please refer to `Dataset API <../reference/api.html#dataset>`_.
|
||||||
|
|
||||||
|
|
||||||
Cache
|
Cache
|
||||||
==========
|
=====
|
||||||
|
|
||||||
``Cache`` is an optional module that helps accelerate providing data by saving some frequently-used data as cache file. ``Qlib`` provides a `Memcache` class to cache the most-frequently-used data in memory, an inheritable `ExpressionCache` class, and an inheritable `DatasetCache` class.
|
``Cache`` is an optional module that helps accelerate providing data by saving some frequently-used data as cache file. ``Qlib`` provides a `Memcache` class to cache the most-frequently-used data in memory, an inheritable `ExpressionCache` class, and an inheritable `DatasetCache` class.
|
||||||
|
|
||||||
Global Memory Cache
|
Global Memory Cache
|
||||||
---------------------
|
-------------------
|
||||||
|
|
||||||
`Memcache` is a global memory cache mechanism that composes of three `MemCacheUnit` instances to cache **Calendar**, **Instruments**, and **Features**. The `MemCache` is defined globally in `cache.py` as `H`. Users can use `H['c'], H['i'], H['f']` to get/set `memcache`.
|
`Memcache` is a global memory cache mechanism that composes of three `MemCacheUnit` instances to cache **Calendar**, **Instruments**, and **Features**. The `MemCache` is defined globally in `cache.py` as `H`. Users can use `H['c'], H['i'], H['f']` to get/set `memcache`.
|
||||||
|
|
||||||
@@ -471,7 +476,7 @@ Global Memory Cache
|
|||||||
|
|
||||||
|
|
||||||
ExpressionCache
|
ExpressionCache
|
||||||
-----------------
|
---------------
|
||||||
|
|
||||||
`ExpressionCache` is a cache mechanism that saves expressions such as **Mean($close, 5)**. Users can inherit this base class to define their own cache mechanism that saves expressions according to the following steps.
|
`ExpressionCache` is a cache mechanism that saves expressions such as **Mean($close, 5)**. Users can inherit this base class to define their own cache mechanism that saves expressions according to the following steps.
|
||||||
|
|
||||||
@@ -486,7 +491,7 @@ The following shows the details about the interfaces:
|
|||||||
``Qlib`` has currently provided implemented disk cache `DiskExpressionCache` which inherits from `ExpressionCache` . The expressions data will be stored in the disk.
|
``Qlib`` has currently provided implemented disk cache `DiskExpressionCache` which inherits from `ExpressionCache` . The expressions data will be stored in the disk.
|
||||||
|
|
||||||
DatasetCache
|
DatasetCache
|
||||||
-----------------
|
------------
|
||||||
|
|
||||||
`DatasetCache` is a cache mechanism that saves datasets. A certain dataset is regulated by a stock pool configuration (or a series of instruments, though not recommended), a list of expressions or static feature fields, the start time, and end time for the collected features and the frequency. Users can inherit this base class to define their own cache mechanism that saves datasets according to the following steps.
|
`DatasetCache` is a cache mechanism that saves datasets. A certain dataset is regulated by a stock pool configuration (or a series of instruments, though not recommended), a list of expressions or static feature fields, the start time, and end time for the collected features and the frequency. Users can inherit this base class to define their own cache mechanism that saves datasets according to the following steps.
|
||||||
|
|
||||||
@@ -503,7 +508,7 @@ The following shows the details about the interfaces:
|
|||||||
|
|
||||||
|
|
||||||
Data and Cache File Structure
|
Data and Cache File Structure
|
||||||
==================================
|
=============================
|
||||||
|
|
||||||
We've specially designed a file structure to manage data and cache, please refer to the `File storage design section in Qlib paper <https://arxiv.org/abs/2009.11189>`_ for detailed information. The file structure of data and cache is listed as follows.
|
We've specially designed a file structure to manage data and cache, please refer to the `File storage design section in Qlib paper <https://arxiv.org/abs/2009.11189>`_ for detailed information. The file structure of data and cache is listed as follows.
|
||||||
|
|
||||||
@@ -536,4 +541,3 @@ We've specially designed a file structure to manage data and cache, please refer
|
|||||||
- .meta : an assorted meta file recording the stockpool config, field names and visit times
|
- .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
|
- .index : an assorted index file recording the line index of all calendars
|
||||||
- ...
|
- ...
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
.. _highfreq:
|
.. _highfreq:
|
||||||
|
|
||||||
============================================
|
========================================================================
|
||||||
Design of Nested Decision Execution Framework for High-Frequency Trading
|
Design of Nested Decision Execution Framework for High-Frequency Trading
|
||||||
============================================
|
========================================================================
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
|
|
||||||
Daily trading (e.g. portfolio management) and intraday trading (e.g. orders execution) are two hot topics in Quant investment and usually studied separately.
|
Daily trading (e.g. portfolio management) and intraday trading (e.g. orders execution) are two hot topics in Quant investment and usually studied separately.
|
||||||
|
|
||||||
@@ -15,18 +15,18 @@ In order to support the joint backtest strategies in multiple levels, a correspo
|
|||||||
|
|
||||||
Besides backtesting, the optimization of strategies from different levels is not standalone and can be affected by each other.
|
Besides backtesting, the optimization of strategies from different levels is not standalone and can be affected by each other.
|
||||||
For example, the best portfolio management strategy may change with the performance of order executions(e.g. a portfolio with higher turnover may becomes a better choice when we improve the order execution strategies).
|
For example, the best portfolio management strategy may change with the performance of order executions(e.g. a portfolio with higher turnover may becomes a better choice when we improve the order execution strategies).
|
||||||
To achieve the overall good performance , it is necessary to consider the interaction of strategies in different level.
|
To achieve the overall good performance , it is necessary to consider the interaction of strategies in different level.
|
||||||
|
|
||||||
Therefore, building a new framework for trading in multiple levels becomes necessary to solve the various problems mentioned above, for which we designed a nested decision execution framework that consider the interaction of strategies.
|
Therefore, building a new framework for trading in multiple levels becomes necessary to solve the various problems mentioned above, for which we designed a nested decision execution framework that consider the interaction of strategies.
|
||||||
|
|
||||||
.. image:: ../_static/img/framework.svg
|
.. image:: ../_static/img/framework.svg
|
||||||
|
|
||||||
The design of the framework is shown in the yellow part in the middle of the figure above. Each level consists of ``Trading Agent`` and ``Execution Env``. ``Trading Agent`` has its own data processing module (``Information Extractor``), forecasting module (``Forecast Model``) and decision generator (``Decision Generator``). The trading algorithm generates the decisions by the ``Decision Generator`` based on the forecast signals output by the ``Forecast Module``, and the decisions generated by the trading algorithm are passed to the ``Execution Env``, which returns the execution results.
|
The design of the framework is shown in the yellow part in the middle of the figure above. Each level consists of ``Trading Agent`` and ``Execution Env``. ``Trading Agent`` has its own data processing module (``Information Extractor``), forecasting module (``Forecast Model``) and decision generator (``Decision Generator``). The trading algorithm generates the decisions by the ``Decision Generator`` based on the forecast signals output by the ``Forecast Module``, and the decisions generated by the trading algorithm are passed to the ``Execution Env``, which returns the execution results.
|
||||||
|
|
||||||
The frequency of trading algorithm, decision content and execution environment can be customized by users (e.g. intraday trading, daily-frequency trading, weekly-frequency trading), and the execution environment can be nested with finer-grained trading algorithm and execution environment inside (i.e. sub-workflow in the figure, e.g. daily-frequency orders can be turned into finer-grained decisions by splitting orders within the day). The flexibility of nested decision execution framework makes it easy for users to explore the effects of combining different levels of trading strategies and break down the optimization barriers between different levels of trading algorithm.
|
The frequency of trading algorithm, decision content and execution environment can be customized by users (e.g. intraday trading, daily-frequency trading, weekly-frequency trading), and the execution environment can be nested with finer-grained trading algorithm and execution environment inside (i.e. sub-workflow in the figure, e.g. daily-frequency orders can be turned into finer-grained decisions by splitting orders within the day). The flexibility of nested decision execution framework makes it easy for users to explore the effects of combining different levels of trading strategies and break down the optimization barriers between different levels of trading algorithm.
|
||||||
|
|
||||||
Example
|
Example
|
||||||
===========================
|
=======
|
||||||
|
|
||||||
An example of nested decision execution framework for high-frequency can be found `here <https://github.com/microsoft/qlib/blob/main/examples/nested_decision_execution/workflow.py>`_.
|
An example of nested decision execution framework for high-frequency can be found `here <https://github.com/microsoft/qlib/blob/main/examples/nested_decision_execution/workflow.py>`_.
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
.. _meta:
|
.. _meta:
|
||||||
|
|
||||||
=================================
|
======================================================
|
||||||
Meta Controller: Meta-Task & Meta-Dataset & Meta-Model
|
Meta Controller: Meta-Task & Meta-Dataset & Meta-Model
|
||||||
=================================
|
======================================================
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
=============
|
============
|
||||||
``Meta Controller`` provides guidance to ``Forecast Model``, which aims to learn regular patterns among a series of forecasting tasks and use learned patterns to guide forthcoming forecasting tasks. Users can implement their own meta-model instance based on ``Meta Controller`` module.
|
``Meta Controller`` provides guidance to ``Forecast Model``, which aims to learn regular patterns among a series of forecasting tasks and use learned patterns to guide forthcoming forecasting tasks. Users can implement their own meta-model instance based on ``Meta Controller`` module.
|
||||||
|
|
||||||
Meta Task
|
Meta Task
|
||||||
=============
|
=========
|
||||||
|
|
||||||
A `Meta Task` instance is the basic element in the meta-learning framework. It saves the data that can be used for the `Meta Model`. Multiple `Meta Task` instances may share the same `Data Handler`, controlled by `Meta Dataset`. Users should use `prepare_task_data()` to obtain the data that can be directly fed into the `Meta Model`.
|
A `Meta Task` instance is the basic element in the meta-learning framework. It saves the data that can be used for the `Meta Model`. Multiple `Meta Task` instances may share the same `Data Handler`, controlled by `Meta Dataset`. Users should use `prepare_task_data()` to obtain the data that can be directly fed into the `Meta Model`.
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ A `Meta Task` instance is the basic element in the meta-learning framework. It s
|
|||||||
:members:
|
:members:
|
||||||
|
|
||||||
Meta Dataset
|
Meta Dataset
|
||||||
=============
|
============
|
||||||
|
|
||||||
`Meta Dataset` controls the meta-information generating process. It is on the duty of providing data for training the `Meta Model`. Users should use `prepare_tasks` to retrieve a list of `Meta Task` instances.
|
`Meta Dataset` controls the meta-information generating process. It is on the duty of providing data for training the `Meta Model`. Users should use `prepare_tasks` to retrieve a list of `Meta Task` instances.
|
||||||
|
|
||||||
@@ -27,26 +27,26 @@ Meta Dataset
|
|||||||
:members:
|
:members:
|
||||||
|
|
||||||
Meta Model
|
Meta Model
|
||||||
=============
|
==========
|
||||||
|
|
||||||
General Meta Model
|
General Meta Model
|
||||||
------------------
|
------------------
|
||||||
`Meta Model` instance is the part that controls the workflow. The usage of the `Meta Model` includes:
|
`Meta Model` instance is the part that controls the workflow. The usage of the `Meta Model` includes:
|
||||||
1. Users train their `Meta Model` with the `fit` function.
|
1. Users train their `Meta Model` with the `fit` function.
|
||||||
2. The `Meta Model` instance guides the workflow by giving useful information via the `inference` function.
|
2. The `Meta Model` instance guides the workflow by giving useful information via the `inference` function.
|
||||||
|
|
||||||
.. autoclass:: qlib.model.meta.model.MetaModel
|
.. autoclass:: qlib.model.meta.model.MetaModel
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Meta Task Model
|
Meta Task Model
|
||||||
------------------
|
---------------
|
||||||
This type of meta-model may interact with task definitions directly. Then, the `Meta Task Model` is the class for them to inherit from. They guide the base tasks by modifying the base task definitions. The function `prepare_tasks` can be used to obtain the modified base task definitions.
|
This type of meta-model may interact with task definitions directly. Then, the `Meta Task Model` is the class for them to inherit from. They guide the base tasks by modifying the base task definitions. The function `prepare_tasks` can be used to obtain the modified base task definitions.
|
||||||
|
|
||||||
.. autoclass:: qlib.model.meta.model.MetaTaskModel
|
.. autoclass:: qlib.model.meta.model.MetaTaskModel
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Meta Guide Model
|
Meta Guide Model
|
||||||
------------------
|
----------------
|
||||||
This type of meta-model participates in the training process of the base forecasting model. The meta-model may guide the base forecasting models during their training to improve their performances.
|
This type of meta-model participates in the training process of the base forecasting model. The meta-model may guide the base forecasting models during their training to improve their performances.
|
||||||
|
|
||||||
.. autoclass:: qlib.model.meta.model.MetaGuideModel
|
.. autoclass:: qlib.model.meta.model.MetaGuideModel
|
||||||
@@ -54,9 +54,9 @@ This type of meta-model participates in the training process of the base forecas
|
|||||||
|
|
||||||
|
|
||||||
Example
|
Example
|
||||||
=============
|
=======
|
||||||
``Qlib`` provides an implementation of ``Meta Model`` module, ``DDG-DA``,
|
``Qlib`` provides an implementation of ``Meta Model`` module, ``DDG-DA``,
|
||||||
which adapts to the market dynamics.
|
which adapts to the market dynamics.
|
||||||
|
|
||||||
``DDG-DA`` includes four steps:
|
``DDG-DA`` includes four steps:
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
.. _model:
|
.. _model:
|
||||||
|
|
||||||
============================================
|
===========================================
|
||||||
Forecast Model: Model Training & Prediction
|
Forecast Model: Model Training & Prediction
|
||||||
============================================
|
===========================================
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
|
|
||||||
``Forecast Model`` is designed to make the `prediction score` about stocks. Users can use the ``Forecast Model`` in an automatic workflow by ``qrun``, please refer to `Workflow: Workflow Management <workflow.html>`_.
|
``Forecast Model`` is designed to make the `prediction score` about stocks. Users can use the ``Forecast Model`` in an automatic workflow by ``qrun``, please refer to `Workflow: Workflow Management <workflow.html>`_.
|
||||||
|
|
||||||
Because the components in ``Qlib`` are designed in a loosely-coupled way, ``Forecast Model`` can be used as an independent module also.
|
Because the components in ``Qlib`` are designed in a loosely-coupled way, ``Forecast Model`` can be used as an independent module also.
|
||||||
|
|
||||||
@@ -22,11 +22,11 @@ The base class provides the following interfaces:
|
|||||||
:members:
|
:members:
|
||||||
|
|
||||||
``Qlib`` also provides a base class `qlib.model.base.ModelFT <../reference/api.html#qlib.model.base.ModelFT>`_, which includes the method for finetuning the model.
|
``Qlib`` also provides a base class `qlib.model.base.ModelFT <../reference/api.html#qlib.model.base.ModelFT>`_, which includes the method for finetuning the model.
|
||||||
|
|
||||||
For other interfaces such as `finetune`, please refer to `Model API <../reference/api.html#module-qlib.model.base>`_.
|
For other interfaces such as `finetune`, please refer to `Model API <../reference/api.html#module-qlib.model.base>`_.
|
||||||
|
|
||||||
Example
|
Example
|
||||||
==================
|
=======
|
||||||
|
|
||||||
``Qlib``'s `Model Zoo` includes models such as ``LightGBM``, ``MLP``, ``LSTM``, etc.. These models are treated as the baselines of ``Forecast Model``. The following steps show how to run`` LightGBM`` as an independent module.
|
``Qlib``'s `Model Zoo` includes models such as ``LightGBM``, ``MLP``, ``LSTM``, etc.. These models are treated as the baselines of ``Forecast Model``. The following steps show how to run`` LightGBM`` as an independent module.
|
||||||
|
|
||||||
@@ -84,7 +84,7 @@ Example
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
# model initiaiton
|
# model initiaiton
|
||||||
model = init_instance_by_config(task["model"])
|
model = init_instance_by_config(task["model"])
|
||||||
dataset = init_instance_by_config(task["dataset"])
|
dataset = init_instance_by_config(task["dataset"])
|
||||||
@@ -100,22 +100,22 @@ Example
|
|||||||
sr = SignalRecord(model, dataset, recorder)
|
sr = SignalRecord(model, dataset, recorder)
|
||||||
sr.generate()
|
sr.generate()
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
`Alpha158` is the data handler provided by ``Qlib``, please refer to `Data Handler <data.html#data-handler>`_.
|
`Alpha158` is the data handler provided by ``Qlib``, please refer to `Data Handler <data.html#data-handler>`_.
|
||||||
`SignalRecord` is the `Record Template` in ``Qlib``, please refer to `Workflow <recorder.html#record-template>`_.
|
`SignalRecord` is the `Record Template` in ``Qlib``, please refer to `Workflow <recorder.html#record-template>`_.
|
||||||
|
|
||||||
Also, the above example has been given in ``examples/train_backtest_analyze.ipynb``.
|
Also, the above example has been given in ``examples/train_backtest_analyze.ipynb``.
|
||||||
Technically, the meaning of the model prediction depends on the label setting designed by user.
|
Technically, the meaning of the model prediction depends on the label setting designed by user.
|
||||||
By default, the meaning of the score is normally the rating of the instruments by the forecasting model. The higher the score, the more profit the instruments.
|
By default, the meaning of the score is normally the rating of the instruments by the forecasting model. The higher the score, the more profit the instruments.
|
||||||
|
|
||||||
|
|
||||||
Custom Model
|
Custom Model
|
||||||
===================
|
============
|
||||||
|
|
||||||
Qlib supports custom models. If users are interested in customizing their own models and integrating the models into ``Qlib``, please refer to `Custom Model Integration <../start/integration.html>`_.
|
Qlib supports custom models. If users are interested in customizing their own models and integrating the models into ``Qlib``, please refer to `Custom Model Integration <../start/integration.html>`_.
|
||||||
|
|
||||||
|
|
||||||
API
|
API
|
||||||
===================
|
===
|
||||||
Please refer to `Model API <../reference/api.html#module-qlib.model.base>`_.
|
Please refer to `Model API <../reference/api.html#module-qlib.model.base>`_.
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
.. _online:
|
.. _online:
|
||||||
|
|
||||||
=================================
|
==============
|
||||||
Online Serving
|
Online Serving
|
||||||
=================================
|
==============
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
=============
|
============
|
||||||
|
|
||||||
.. image:: ../_static/img/online_serving.png
|
.. image:: ../_static/img/online_serving.png
|
||||||
:align: center
|
:align: center
|
||||||
@@ -15,7 +15,7 @@ Introduction
|
|||||||
|
|
||||||
In addition to backtesting, one way to test a model is effective is to make predictions in real market conditions or even do real trading based on those predictions.
|
In addition to backtesting, one way to test a model is effective is to make predictions in real market conditions or even do real trading based on those predictions.
|
||||||
``Online Serving`` is a set of modules for online models using the latest data,
|
``Online Serving`` is a set of modules for online models using the latest data,
|
||||||
which including `Online Manager <#Online Manager>`_, `Online Strategy <#Online Strategy>`_, `Online Tool <#Online Tool>`_, `Updater <#Updater>`_.
|
which including `Online Manager <#Online Manager>`_, `Online Strategy <#Online Strategy>`_, `Online Tool <#Online Tool>`_, `Updater <#Updater>`_.
|
||||||
|
|
||||||
`Here <https://github.com/microsoft/qlib/tree/main/examples/online_srv>`_ are several examples for reference, which demonstrate different features of ``Online Serving``.
|
`Here <https://github.com/microsoft/qlib/tree/main/examples/online_srv>`_ are several examples for reference, which demonstrate different features of ``Online Serving``.
|
||||||
If you have many models or `task` needs to be managed, please consider `Task Management <../advanced/task_management.html>`_.
|
If you have many models or `task` needs to be managed, please consider `Task Management <../advanced/task_management.html>`_.
|
||||||
@@ -28,25 +28,25 @@ Known limitations currently
|
|||||||
|
|
||||||
|
|
||||||
Online Manager
|
Online Manager
|
||||||
=============
|
==============
|
||||||
|
|
||||||
.. automodule:: qlib.workflow.online.manager
|
.. automodule:: qlib.workflow.online.manager
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Online Strategy
|
Online Strategy
|
||||||
=============
|
===============
|
||||||
|
|
||||||
.. automodule:: qlib.workflow.online.strategy
|
.. automodule:: qlib.workflow.online.strategy
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Online Tool
|
Online Tool
|
||||||
=============
|
===========
|
||||||
|
|
||||||
.. automodule:: qlib.workflow.online.utils
|
.. automodule:: qlib.workflow.online.utils
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Updater
|
Updater
|
||||||
=============
|
=======
|
||||||
|
|
||||||
.. automodule:: qlib.workflow.online.update
|
.. automodule:: qlib.workflow.online.update
|
||||||
:members:
|
:members:
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ Qlib Recorder: Experiment Management
|
|||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
``Qlib`` contains an experiment management system named ``QlibRecorder``, which is designed to help users handle experiment and analyse results in an efficient way.
|
``Qlib`` contains an experiment management system named ``QlibRecorder``, which is designed to help users handle experiment and analyse results in an efficient way.
|
||||||
|
|
||||||
There are three components of the system:
|
There are three components of the system:
|
||||||
|
|
||||||
@@ -34,13 +34,13 @@ Here is a general view of the structure of the system:
|
|||||||
- Recorder 2
|
- Recorder 2
|
||||||
- ...
|
- ...
|
||||||
- ...
|
- ...
|
||||||
|
|
||||||
This experiment management system defines a set of interface and provided a concrete implementation ``MLflowExpManager``, which is based on the machine learning platform: ``MLFlow`` (`link <https://mlflow.org/>`_).
|
This experiment management system defines a set of interface and provided a concrete implementation ``MLflowExpManager``, which is based on the machine learning platform: ``MLFlow`` (`link <https://mlflow.org/>`_).
|
||||||
|
|
||||||
If users set the implementation of ``ExpManager`` to be ``MLflowExpManager``, they can use the command `mlflow ui` to visualize and check the experiment results. For more information, please refer to the related documents `here <https://www.mlflow.org/docs/latest/cli.html#mlflow-ui>`_.
|
If users set the implementation of ``ExpManager`` to be ``MLflowExpManager``, they can use the command `mlflow ui` to visualize and check the experiment results. For more information, please refer to the related documents `here <https://www.mlflow.org/docs/latest/cli.html#mlflow-ui>`_.
|
||||||
|
|
||||||
Qlib Recorder
|
Qlib Recorder
|
||||||
===================
|
=============
|
||||||
``QlibRecorder`` provides a high level API for users to use the experiment management system. The interfaces are wrapped in the variable ``R`` in ``Qlib``, and users can directly use ``R`` to interact with the system. The following command shows how to import ``R`` in Python:
|
``QlibRecorder`` provides a high level API for users to use the experiment management system. The interfaces are wrapped in the variable ``R`` in ``Qlib``, and users can directly use ``R`` to interact with the system. The following command shows how to import ``R`` in Python:
|
||||||
|
|
||||||
.. code-block:: Python
|
.. code-block:: Python
|
||||||
@@ -55,7 +55,7 @@ Here are the available interfaces of ``QlibRecorder``:
|
|||||||
:members:
|
:members:
|
||||||
|
|
||||||
Experiment Manager
|
Experiment Manager
|
||||||
===================
|
==================
|
||||||
|
|
||||||
The ``ExpManager`` module in ``Qlib`` is responsible for managing different experiments. Most of the APIs of ``ExpManager`` are similar to ``QlibRecorder``, and the most important API will be the ``get_exp`` method. User can directly refer to the documents above for some detailed information about how to use the ``get_exp`` method.
|
The ``ExpManager`` module in ``Qlib`` is responsible for managing different experiments. Most of the APIs of ``ExpManager`` are similar to ``QlibRecorder``, and the most important API will be the ``get_exp`` method. User can directly refer to the documents above for some detailed information about how to use the ``get_exp`` method.
|
||||||
|
|
||||||
@@ -65,7 +65,7 @@ The ``ExpManager`` module in ``Qlib`` is responsible for managing different expe
|
|||||||
For other interfaces such as `create_exp`, `delete_exp`, please refer to `Experiment Manager API <../reference/api.html#experiment-manager>`_.
|
For other interfaces such as `create_exp`, `delete_exp`, please refer to `Experiment Manager API <../reference/api.html#experiment-manager>`_.
|
||||||
|
|
||||||
Experiment
|
Experiment
|
||||||
===================
|
==========
|
||||||
|
|
||||||
The ``Experiment`` class is solely responsible for a single experiment, and it will handle any operations that are related to an experiment. Basic methods such as `start`, `end` an experiment are included. Besides, methods related to `recorders` are also available: such methods include `get_recorder` and `list_recorders`.
|
The ``Experiment`` class is solely responsible for a single experiment, and it will handle any operations that are related to an experiment. Basic methods such as `start`, `end` an experiment are included. Besides, methods related to `recorders` are also available: such methods include `get_recorder` and `list_recorders`.
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ For other interfaces such as `search_records`, `delete_recorder`, please refer t
|
|||||||
``Qlib`` also provides a default ``Experiment``, which will be created and used under certain situations when users use the APIs such as `log_metrics` or `get_exp`. If the default ``Experiment`` is used, there will be related logged information when running ``Qlib``. Users are able to change the name of the default ``Experiment`` in the config file of ``Qlib`` or during ``Qlib``'s `initialization <../start/initialization.html#parameters>`_, which is set to be '`Experiment`'.
|
``Qlib`` also provides a default ``Experiment``, which will be created and used under certain situations when users use the APIs such as `log_metrics` or `get_exp`. If the default ``Experiment`` is used, there will be related logged information when running ``Qlib``. Users are able to change the name of the default ``Experiment`` in the config file of ``Qlib`` or during ``Qlib``'s `initialization <../start/initialization.html#parameters>`_, which is set to be '`Experiment`'.
|
||||||
|
|
||||||
Recorder
|
Recorder
|
||||||
===================
|
========
|
||||||
|
|
||||||
The ``Recorder`` class is responsible for a single recorder. It will handle some detailed operations such as ``log_metrics``, ``log_params`` of a single run. It is designed to help user to easily track results and things being generated during a run.
|
The ``Recorder`` class is responsible for a single recorder. It will handle some detailed operations such as ``log_metrics``, ``log_params`` of a single run. It is designed to help user to easily track results and things being generated during a run.
|
||||||
|
|
||||||
@@ -89,7 +89,7 @@ Here are some important APIs that are not included in the ``QlibRecorder``:
|
|||||||
For other interfaces such as `save_objects`, `load_object`, please refer to `Recorder API <../reference/api.html#recorder>`_.
|
For other interfaces such as `save_objects`, `load_object`, please refer to `Recorder API <../reference/api.html#recorder>`_.
|
||||||
|
|
||||||
Record Template
|
Record Template
|
||||||
===================
|
===============
|
||||||
|
|
||||||
The ``RecordTemp`` class is a class that enables generate experiment results such as IC and backtest in a certain format. We have provided three different `Record Template` class:
|
The ``RecordTemp`` class is a class that enables generate experiment results such as IC and backtest in a certain format. We have provided three different `Record Template` class:
|
||||||
|
|
||||||
@@ -131,7 +131,7 @@ Here is a simple exampke of what is done in ``PortAnaRecord``, which users can r
|
|||||||
"close_cost": 0.0015,
|
"close_cost": 0.0015,
|
||||||
"min_cost": 5,
|
"min_cost": 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
strategy = TopkDropoutStrategy(**STRATEGY_CONFIG)
|
strategy = TopkDropoutStrategy(**STRATEGY_CONFIG)
|
||||||
report_normal, positions_normal = normal_backtest(pred_score, strategy=strategy, **BACKTEST_CONFIG)
|
report_normal, positions_normal = normal_backtest(pred_score, strategy=strategy, **BACKTEST_CONFIG)
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
.. _report:
|
.. _report:
|
||||||
|
|
||||||
==========================================
|
=======================================
|
||||||
Analysis: Evaluation & Results Analysis
|
Analysis: Evaluation & Results Analysis
|
||||||
==========================================
|
=======================================
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
|
|
||||||
``Analysis`` is designed to show the graphical reports of ``Intraday Trading`` , which helps users to evaluate and analyse investment portfolios visually. The following are some graphics to view:
|
``Analysis`` is designed to show the graphical reports of ``Intraday Trading`` , which helps users to evaluate and analyse investment portfolios visually. The following are some graphics to view:
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ All of the accumulated profit metrics(e.g. return, max drawdown) in Qlib are cal
|
|||||||
This avoids the metrics or the plots being skewed exponentially over time.
|
This avoids the metrics or the plots being skewed exponentially over time.
|
||||||
|
|
||||||
Graphical Reports
|
Graphical Reports
|
||||||
===================
|
=================
|
||||||
|
|
||||||
Users can run the following code to get all supported reports.
|
Users can run the following code to get all supported reports.
|
||||||
|
|
||||||
@@ -41,13 +41,13 @@ Users can run the following code to get all supported reports.
|
|||||||
|
|
||||||
|
|
||||||
Usage & Example
|
Usage & Example
|
||||||
===================
|
===============
|
||||||
|
|
||||||
Usage of `analysis_position.report`
|
Usage of `analysis_position.report`
|
||||||
-----------------------------------
|
-----------------------------------
|
||||||
|
|
||||||
API
|
API
|
||||||
~~~~~~~~~~~~~~~~
|
~~~
|
||||||
|
|
||||||
.. automodule:: qlib.contrib.report.analysis_position.report
|
.. automodule:: qlib.contrib.report.analysis_position.report
|
||||||
:members:
|
:members:
|
||||||
@@ -58,7 +58,7 @@ Graphical Result
|
|||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
- Axis X: Trading day
|
- Axis X: Trading day
|
||||||
- Axis Y:
|
- Axis Y:
|
||||||
- `cum bench`
|
- `cum bench`
|
||||||
Cumulative returns series of benchmark
|
Cumulative returns series of benchmark
|
||||||
- `cum return wo cost`
|
- `cum return wo cost`
|
||||||
@@ -82,34 +82,34 @@ Graphical Result
|
|||||||
- The shaded part above: Maximum drawdown corresponding to `cum return wo cost`
|
- The shaded part above: Maximum drawdown corresponding to `cum return wo cost`
|
||||||
- The shaded part below: Maximum drawdown corresponding to `cum ex return wo cost`
|
- The shaded part below: Maximum drawdown corresponding to `cum ex return wo cost`
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/report.png
|
.. image:: ../_static/img/analysis/report.png
|
||||||
|
|
||||||
|
|
||||||
Usage of `analysis_position.score_ic`
|
Usage of `analysis_position.score_ic`
|
||||||
-------------------------------------
|
-------------------------------------
|
||||||
|
|
||||||
API
|
API
|
||||||
~~~~~~~~~~~~~~~~
|
~~~
|
||||||
|
|
||||||
.. automodule:: qlib.contrib.report.analysis_position.score_ic
|
.. automodule:: qlib.contrib.report.analysis_position.score_ic
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
Graphical Result
|
Graphical Result
|
||||||
~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
- Axis X: Trading day
|
- Axis X: Trading day
|
||||||
- Axis Y:
|
- Axis Y:
|
||||||
- `ic`
|
- `ic`
|
||||||
The `Pearson correlation coefficient` series between `label` and `prediction score`.
|
The `Pearson correlation coefficient` series between `label` and `prediction score`.
|
||||||
In the above example, the `label` is formulated as `Ref($close, -2)/Ref($close, -1)-1`. Please refer to `Data Feature <data.html#feature>`_ for more details.
|
In the above example, the `label` is formulated as `Ref($close, -2)/Ref($close, -1)-1`. Please refer to `Data Feature <data.html#feature>`_ for more details.
|
||||||
|
|
||||||
- `rank_ic`
|
- `rank_ic`
|
||||||
The `Spearman's rank correlation coefficient` series between `label` and `prediction score`.
|
The `Spearman's rank correlation coefficient` series between `label` and `prediction score`.
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/score_ic.png
|
.. image:: ../_static/img/analysis/score_ic.png
|
||||||
|
|
||||||
|
|
||||||
.. Usage of `analysis_position.cumulative_return`
|
.. Usage of `analysis_position.cumulative_return`
|
||||||
@@ -124,7 +124,7 @@ Graphical Result
|
|||||||
.. Graphical Result
|
.. Graphical Result
|
||||||
.. ~~~~~~~~~~~~~~~~~
|
.. ~~~~~~~~~~~~~~~~~
|
||||||
..
|
..
|
||||||
.. .. note::
|
.. .. note::
|
||||||
..
|
..
|
||||||
.. - Axis X: Trading day
|
.. - Axis X: Trading day
|
||||||
.. - Axis Y:
|
.. - Axis Y:
|
||||||
@@ -134,27 +134,27 @@ Graphical Result
|
|||||||
.. - In the **buy_minus_sell** graph, the **y** value of the **weight** graph at the bottom is `buy_weight + sell_weight`.
|
.. - In the **buy_minus_sell** graph, the **y** value of the **weight** graph at the bottom is `buy_weight + sell_weight`.
|
||||||
.. - In each graph, the **red line** in the histogram on the right represents the average.
|
.. - In each graph, the **red line** in the histogram on the right represents the average.
|
||||||
..
|
..
|
||||||
.. .. image:: ../_static/img/analysis/cumulative_return_buy.png
|
.. .. image:: ../_static/img/analysis/cumulative_return_buy.png
|
||||||
..
|
..
|
||||||
.. .. image:: ../_static/img/analysis/cumulative_return_sell.png
|
.. .. image:: ../_static/img/analysis/cumulative_return_sell.png
|
||||||
..
|
..
|
||||||
.. .. image:: ../_static/img/analysis/cumulative_return_buy_minus_sell.png
|
.. .. image:: ../_static/img/analysis/cumulative_return_buy_minus_sell.png
|
||||||
..
|
..
|
||||||
.. .. image:: ../_static/img/analysis/cumulative_return_hold.png
|
.. .. image:: ../_static/img/analysis/cumulative_return_hold.png
|
||||||
|
|
||||||
|
|
||||||
Usage of `analysis_position.risk_analysis`
|
Usage of `analysis_position.risk_analysis`
|
||||||
----------------------------------------------
|
------------------------------------------
|
||||||
|
|
||||||
API
|
API
|
||||||
~~~~~~~~~~~~~~~~
|
~~~
|
||||||
|
|
||||||
.. automodule:: qlib.contrib.report.analysis_position.risk_analysis
|
.. automodule:: qlib.contrib.report.analysis_position.risk_analysis
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
Graphical Result
|
Graphical Result
|
||||||
~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
@@ -210,7 +210,7 @@ Graphical Result
|
|||||||
The `Standard Deviation` series of monthly `CAR` (cumulative abnormal return) without cost.
|
The `Standard Deviation` series of monthly `CAR` (cumulative abnormal return) without cost.
|
||||||
- `excess_return_with_cost_max_drawdown`
|
- `excess_return_with_cost_max_drawdown`
|
||||||
The `Standard Deviation` series of monthly `CAR` (cumulative abnormal return) with cost.
|
The `Standard Deviation` series of monthly `CAR` (cumulative abnormal return) with cost.
|
||||||
|
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/risk_analysis_annualized_return.png
|
.. image:: ../_static/img/analysis/risk_analysis_annualized_return.png
|
||||||
:align: center
|
:align: center
|
||||||
@@ -221,58 +221,58 @@ Graphical Result
|
|||||||
.. image:: ../_static/img/analysis/risk_analysis_information_ratio.png
|
.. image:: ../_static/img/analysis/risk_analysis_information_ratio.png
|
||||||
:align: center
|
:align: center
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/risk_analysis_std.png
|
.. image:: ../_static/img/analysis/risk_analysis_std.png
|
||||||
:align: center
|
:align: center
|
||||||
|
|
||||||
..
|
..
|
||||||
.. Usage of `analysis_position.rank_label`
|
.. Usage of `analysis_position.rank_label`
|
||||||
.. ----------------------------------------------
|
.. ---------------------------------------
|
||||||
..
|
..
|
||||||
.. API
|
.. API
|
||||||
.. ~~~~~
|
.. ~~~
|
||||||
..
|
..
|
||||||
.. .. automodule:: qlib.contrib.report.analysis_position.rank_label
|
.. .. automodule:: qlib.contrib.report.analysis_position.rank_label
|
||||||
.. :members:
|
.. :members:
|
||||||
..
|
..
|
||||||
..
|
..
|
||||||
.. Graphical Result
|
.. Graphical Result
|
||||||
.. ~~~~~~~~~~~~~~~~~
|
.. ~~~~~~~~~~~~~~~~
|
||||||
..
|
..
|
||||||
.. .. note::
|
.. .. note::
|
||||||
..
|
..
|
||||||
.. - hold/sell/buy graphics:
|
.. - hold/sell/buy graphics:
|
||||||
.. - Axis X: Trading day
|
.. - Axis X: Trading day
|
||||||
.. - Axis Y:
|
.. - Axis Y:
|
||||||
.. Average `ranking ratio`of `label` for stocks that is held/sold/bought on the trading day.
|
.. Average `ranking ratio`of `label` for stocks that is held/sold/bought on the trading day.
|
||||||
..
|
..
|
||||||
.. In the above example, the `label` is formulated as `Ref($close, -1)/$close - 1`. The `ranking ratio` can be formulated as follows.
|
.. In the above example, the `label` is formulated as `Ref($close, -1)/$close - 1`. The `ranking ratio` can be formulated as follows.
|
||||||
.. .. math::
|
.. .. math::
|
||||||
..
|
..
|
||||||
.. ranking\ ratio = \frac{Ascending\ Ranking\ of\ label}{Number\ of\ Stocks\ in\ the\ Portfolio}
|
.. ranking\ ratio = \frac{Ascending\ Ranking\ of\ label}{Number\ of\ Stocks\ in\ the\ Portfolio}
|
||||||
..
|
..
|
||||||
.. .. image:: ../_static/img/analysis/rank_label_hold.png
|
.. .. image:: ../_static/img/analysis/rank_label_hold.png
|
||||||
.. :align: center
|
.. :align: center
|
||||||
..
|
..
|
||||||
.. .. image:: ../_static/img/analysis/rank_label_buy.png
|
.. .. image:: ../_static/img/analysis/rank_label_buy.png
|
||||||
.. :align: center
|
.. :align: center
|
||||||
..
|
..
|
||||||
.. .. image:: ../_static/img/analysis/rank_label_sell.png
|
.. .. image:: ../_static/img/analysis/rank_label_sell.png
|
||||||
.. :align: center
|
.. :align: center
|
||||||
..
|
..
|
||||||
..
|
..
|
||||||
|
|
||||||
Usage of `analysis_model.analysis_model_performance`
|
Usage of `analysis_model.analysis_model_performance`
|
||||||
-----------------------------------------------------
|
----------------------------------------------------
|
||||||
|
|
||||||
API
|
API
|
||||||
~~~~~
|
~~~
|
||||||
|
|
||||||
.. automodule:: qlib.contrib.report.analysis_model.analysis_model_performance
|
.. automodule:: qlib.contrib.report.analysis_model.analysis_model_performance
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
Graphical Results
|
Graphical Results
|
||||||
~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
@@ -291,13 +291,13 @@ Graphical Results
|
|||||||
The Difference series between `Cumulative Return` of `Group1` and of `Group5`
|
The Difference series between `Cumulative Return` of `Group1` and of `Group5`
|
||||||
- `long-average`
|
- `long-average`
|
||||||
The Difference series between `Cumulative Return` of `Group1` and average `Cumulative Return` for all stocks.
|
The Difference series between `Cumulative Return` of `Group1` and average `Cumulative Return` for all stocks.
|
||||||
|
|
||||||
The `ranking ratio` can be formulated as follows.
|
The `ranking ratio` can be formulated as follows.
|
||||||
.. math::
|
.. math::
|
||||||
|
|
||||||
ranking\ ratio = \frac{Ascending\ Ranking\ of\ label}{Number\ of\ Stocks\ in\ the\ Portfolio}
|
ranking\ ratio = \frac{Ascending\ Ranking\ of\ label}{Number\ of\ Stocks\ in\ the\ Portfolio}
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/analysis_model_cumulative_return.png
|
.. image:: ../_static/img/analysis/analysis_model_cumulative_return.png
|
||||||
:align: center
|
:align: center
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
@@ -305,7 +305,7 @@ Graphical Results
|
|||||||
The distribution of long-short/long-average returns on each trading day
|
The distribution of long-short/long-average returns on each trading day
|
||||||
|
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/analysis_model_long_short.png
|
.. image:: ../_static/img/analysis/analysis_model_long_short.png
|
||||||
:align: center
|
:align: center
|
||||||
|
|
||||||
.. TODO: ask xiao yang for detial
|
.. TODO: ask xiao yang for detial
|
||||||
@@ -315,14 +315,14 @@ Graphical Results
|
|||||||
- The `Pearson correlation coefficient` series between `labels` and `prediction scores` of stocks in portfolio.
|
- The `Pearson correlation coefficient` series between `labels` and `prediction scores` of stocks in portfolio.
|
||||||
- The graphics reports can be used to evaluate the `prediction scores`.
|
- The graphics reports can be used to evaluate the `prediction scores`.
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/analysis_model_IC.png
|
.. image:: ../_static/img/analysis/analysis_model_IC.png
|
||||||
:align: center
|
:align: center
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
- Monthly IC
|
- Monthly IC
|
||||||
Monthly average of the `Information Coefficient`
|
Monthly average of the `Information Coefficient`
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/analysis_model_monthly_IC.png
|
.. image:: ../_static/img/analysis/analysis_model_monthly_IC.png
|
||||||
:align: center
|
:align: center
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
@@ -331,14 +331,14 @@ Graphical Results
|
|||||||
- IC Normal Dist. Q-Q
|
- IC Normal Dist. Q-Q
|
||||||
The `Quantile-Quantile Plot` is used for the normal distribution of `Information Coefficient` on each trading day.
|
The `Quantile-Quantile Plot` is used for the normal distribution of `Information Coefficient` on each trading day.
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/analysis_model_NDQ.png
|
.. image:: ../_static/img/analysis/analysis_model_NDQ.png
|
||||||
:align: center
|
:align: center
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
- Auto Correlation
|
- Auto Correlation
|
||||||
- The `Pearson correlation coefficient` series between the latest `prediction scores` and the `prediction scores` `lag` days ago of stocks in portfolio on each trading day.
|
- The `Pearson correlation coefficient` series between the latest `prediction scores` and the `prediction scores` `lag` days ago of stocks in portfolio on each trading day.
|
||||||
- The graphics reports can be used to estimate the turnover rate.
|
- The graphics reports can be used to estimate the turnover rate.
|
||||||
|
|
||||||
|
|
||||||
.. image:: ../_static/img/analysis/analysis_model_auto_correlation.png
|
|
||||||
|
.. image:: ../_static/img/analysis/analysis_model_auto_correlation.png
|
||||||
:align: center
|
:align: center
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Portfolio Strategy: Portfolio Management
|
|||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
|
|
||||||
``Portfolio Strategy`` is designed to adopt different portfolio strategies, which means that users can adopt different algorithms to generate investment portfolios based on the prediction scores of the ``Forecast Model``. Users can use the ``Portfolio Strategy`` in an automatic workflow by ``Workflow`` module, please refer to `Workflow: Workflow Management <workflow.html>`_.
|
``Portfolio Strategy`` is designed to adopt different portfolio strategies, which means that users can adopt different algorithms to generate investment portfolios based on the prediction scores of the ``Forecast Model``. Users can use the ``Portfolio Strategy`` in an automatic workflow by ``Workflow`` module, please refer to `Workflow: Workflow Management <workflow.html>`_.
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ Base Class & Interface
|
|||||||
======================
|
======================
|
||||||
|
|
||||||
BaseStrategy
|
BaseStrategy
|
||||||
------------------
|
------------
|
||||||
|
|
||||||
Qlib provides a base class ``qlib.strategy.base.BaseStrategy``. All strategy classes need to inherit the base class and implement its interface.
|
Qlib provides a base class ``qlib.strategy.base.BaseStrategy``. All strategy classes need to inherit the base class and implement its interface.
|
||||||
|
|
||||||
@@ -32,7 +32,7 @@ Qlib provides a base class ``qlib.strategy.base.BaseStrategy``. All strategy cla
|
|||||||
Users can inherit `BaseStrategy` to customize their strategy class.
|
Users can inherit `BaseStrategy` to customize their strategy class.
|
||||||
|
|
||||||
WeightStrategyBase
|
WeightStrategyBase
|
||||||
--------------------
|
------------------
|
||||||
|
|
||||||
Qlib also provides a class ``qlib.contrib.strategy.WeightStrategyBase`` that is a subclass of `BaseStrategy`.
|
Qlib also provides a class ``qlib.contrib.strategy.WeightStrategyBase`` that is a subclass of `BaseStrategy`.
|
||||||
|
|
||||||
@@ -60,7 +60,7 @@ Implemented Strategy
|
|||||||
Qlib provides a implemented strategy classes named `TopkDropoutStrategy`.
|
Qlib provides a implemented strategy classes named `TopkDropoutStrategy`.
|
||||||
|
|
||||||
TopkDropoutStrategy
|
TopkDropoutStrategy
|
||||||
------------------
|
-------------------
|
||||||
`TopkDropoutStrategy` is a subclass of `BaseStrategy` and implement the interface `generate_order_list` whose process is as follows.
|
`TopkDropoutStrategy` is a subclass of `BaseStrategy` and implement the interface `generate_order_list` whose process is as follows.
|
||||||
|
|
||||||
- Adopt the ``Topk-Drop`` algorithm to calculate the target amount of each stock
|
- Adopt the ``Topk-Drop`` algorithm to calculate the target amount of each stock
|
||||||
@@ -74,16 +74,16 @@ TopkDropoutStrategy
|
|||||||
In general, the number of stocks currently held is `Topk`, with the exception of being zero at the beginning period of trading.
|
In general, the number of stocks currently held is `Topk`, with the exception of being zero at the beginning period of trading.
|
||||||
For each trading day, let $d$ be the number of the instruments currently held and with a rank $\gt K$ when ranked by the prediction scores from high to low.
|
For each trading day, let $d$ be the number of the instruments currently held and with a rank $\gt K$ when ranked by the prediction scores from high to low.
|
||||||
Then `d` number of stocks currently held with the worst `prediction score` will be sold, and the same number of unheld stocks with the best `prediction score` will be bought.
|
Then `d` number of stocks currently held with the worst `prediction score` will be sold, and the same number of unheld stocks with the best `prediction score` will be bought.
|
||||||
|
|
||||||
In general, $d=$`Drop`, especially when the pool of the candidate instruments is large, $K$ is large, and `Drop` is small.
|
In general, $d=$`Drop`, especially when the pool of the candidate instruments is large, $K$ is large, and `Drop` is small.
|
||||||
|
|
||||||
In most cases, ``TopkDrop`` algorithm sells and buys `Drop` stocks every trading day, which yields a turnover rate of 2$\times$`Drop`/$K$.
|
In most cases, ``TopkDrop`` algorithm sells and buys `Drop` stocks every trading day, which yields a turnover rate of 2$\times$`Drop`/$K$.
|
||||||
|
|
||||||
The following images illustrate a typical scenario.
|
The following images illustrate a typical scenario.
|
||||||
.. image:: ../_static/img/topk_drop.png
|
.. image:: ../_static/img/topk_drop.png
|
||||||
:alt: Topk-Drop
|
:alt: Topk-Drop
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
- Generate the order list from the target amount
|
- Generate the order list from the target amount
|
||||||
|
|
||||||
@@ -98,12 +98,12 @@ and `qlib.contrib.strategy.optimizer.enhanced_indexing.EnhancedIndexingOptimizer
|
|||||||
|
|
||||||
|
|
||||||
Usage & Example
|
Usage & Example
|
||||||
====================
|
===============
|
||||||
|
|
||||||
First, user can create a model to get trading signals(the variable name is ``pred_score`` in following cases).
|
First, user can create a model to get trading signals(the variable name is ``pred_score`` in following cases).
|
||||||
|
|
||||||
Prediction Score
|
Prediction Score
|
||||||
-----------------
|
----------------
|
||||||
|
|
||||||
The `prediction score` is a pandas DataFrame. Its index is <datetime(pd.Timestamp), instrument(str)> and it must
|
The `prediction score` is a pandas DataFrame. Its index is <datetime(pd.Timestamp), instrument(str)> and it must
|
||||||
contains a `score` column.
|
contains a `score` column.
|
||||||
@@ -134,7 +134,7 @@ Qlib didn't add a step to scale the prediction score to a unified scale due to t
|
|||||||
- The model has the flexibility to define the target, loss, and data processing. So we don't think there is a silver bullet to rescale it back directly barely based on the model's outputs. If you want to scale it back to some meaningful values(e.g. stock returns.), an intuitive solution is to create a regression model for the model's recent outputs and your recent target values.
|
- The model has the flexibility to define the target, loss, and data processing. So we don't think there is a silver bullet to rescale it back directly barely based on the model's outputs. If you want to scale it back to some meaningful values(e.g. stock returns.), an intuitive solution is to create a regression model for the model's recent outputs and your recent target values.
|
||||||
|
|
||||||
Running backtest
|
Running backtest
|
||||||
-----------------
|
----------------
|
||||||
|
|
||||||
- In most cases, users could backtest their portfolio management strategy with ``backtest_daily``.
|
- In most cases, users could backtest their portfolio management strategy with ``backtest_daily``.
|
||||||
|
|
||||||
@@ -195,7 +195,7 @@ Running backtest
|
|||||||
|
|
||||||
CSI300_BENCH = "SH000300"
|
CSI300_BENCH = "SH000300"
|
||||||
# Benchmark is for calculating the excess return of your strategy.
|
# Benchmark is for calculating the excess return of your strategy.
|
||||||
# Its data format will be like **ONE normal instrument**.
|
# Its data format will be like **ONE normal instrument**.
|
||||||
# For example, you can query its data with the code below
|
# For example, you can query its data with the code below
|
||||||
# `D.features(["SH000300"], ["$close"], start_time='2010-01-01', end_time='2017-12-31', freq='day')`
|
# `D.features(["SH000300"], ["$close"], start_time='2010-01-01', end_time='2017-12-31', freq='day')`
|
||||||
# It is different from the argument `market`, which indicates a universe of stocks (e.g. **A SET** of stocks like csi300)
|
# It is different from the argument `market`, which indicates a universe of stocks (e.g. **A SET** of stocks like csi300)
|
||||||
@@ -262,7 +262,7 @@ Running backtest
|
|||||||
|
|
||||||
|
|
||||||
Result
|
Result
|
||||||
------------------
|
------
|
||||||
|
|
||||||
The backtest results are in the following form:
|
The backtest results are in the following form:
|
||||||
|
|
||||||
@@ -307,5 +307,5 @@ The backtest results are in the following form:
|
|||||||
|
|
||||||
|
|
||||||
Reference
|
Reference
|
||||||
===================
|
=========
|
||||||
To know more about the `prediction score` `pred_score` output by ``Forecast Model``, please refer to `Forecast Model: Model Training & Prediction <model.html>`_.
|
To know more about the `prediction score` `pred_score` output by ``Forecast Model``, please refer to `Forecast Model: Model Training & Prediction <model.html>`_.
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
.. _workflow:
|
.. _workflow:
|
||||||
|
|
||||||
=================================
|
=============================
|
||||||
Workflow: Workflow Management
|
Workflow: Workflow Management
|
||||||
=================================
|
=============================
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
|
|
||||||
The components in `Qlib Framework <../introduction/introduction.html#framework>`_ are designed in a loosely-coupled way. Users could build their own Quant research workflow with these components like `Example <https://github.com/microsoft/qlib/blob/main/examples/workflow_by_code.py>`_.
|
The components in `Qlib Framework <../introduction/introduction.html#framework>`_ are designed in a loosely-coupled way. Users could build their own Quant research workflow with these components like `Example <https://github.com/microsoft/qlib/blob/main/examples/workflow_by_code.py>`_.
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ With ``qrun``, user can easily start an `execution`, which includes the followin
|
|||||||
For each `execution`, ``Qlib`` has a complete system to tracking all the information as well as artifacts generated during training, inference and evaluation phase. For more information about how ``Qlib`` handles this, please refer to the related document: `Recorder: Experiment Management <../component/recorder.html>`_.
|
For each `execution`, ``Qlib`` has a complete system to tracking all the information as well as artifacts generated during training, inference and evaluation phase. For more information about how ``Qlib`` handles this, please refer to the related document: `Recorder: Experiment Management <../component/recorder.html>`_.
|
||||||
|
|
||||||
Complete Example
|
Complete Example
|
||||||
===================
|
================
|
||||||
|
|
||||||
Before getting into details, here is a complete example of ``qrun``, which defines the workflow in typical Quant research.
|
Before getting into details, here is a complete example of ``qrun``, which defines the workflow in typical Quant research.
|
||||||
Below is a typical config file of ``qrun``.
|
Below is a typical config file of ``qrun``.
|
||||||
@@ -54,7 +54,7 @@ Below is a typical config file of ``qrun``.
|
|||||||
topk: 50
|
topk: 50
|
||||||
n_drop: 5
|
n_drop: 5
|
||||||
signal:
|
signal:
|
||||||
- <MODEL>
|
- <MODEL>
|
||||||
- <DATASET>
|
- <DATASET>
|
||||||
backtest:
|
backtest:
|
||||||
limit_threshold: 0.095
|
limit_threshold: 0.095
|
||||||
@@ -90,13 +90,13 @@ Below is a typical config file of ``qrun``.
|
|||||||
train: [2008-01-01, 2014-12-31]
|
train: [2008-01-01, 2014-12-31]
|
||||||
valid: [2015-01-01, 2016-12-31]
|
valid: [2015-01-01, 2016-12-31]
|
||||||
test: [2017-01-01, 2020-08-01]
|
test: [2017-01-01, 2020-08-01]
|
||||||
record:
|
record:
|
||||||
- class: SignalRecord
|
- class: SignalRecord
|
||||||
module_path: qlib.workflow.record_temp
|
module_path: qlib.workflow.record_temp
|
||||||
kwargs: {}
|
kwargs: {}
|
||||||
- class: PortAnaRecord
|
- class: PortAnaRecord
|
||||||
module_path: qlib.workflow.record_temp
|
module_path: qlib.workflow.record_temp
|
||||||
kwargs:
|
kwargs:
|
||||||
config: *port_analysis_config
|
config: *port_analysis_config
|
||||||
|
|
||||||
After saving the config into `configuration.yaml`, users could start the workflow and test their ideas with a single command below.
|
After saving the config into `configuration.yaml`, users could start the workflow and test their ideas with a single command below.
|
||||||
@@ -111,22 +111,22 @@ If users want to use ``qrun`` under debug mode, please use the following command
|
|||||||
|
|
||||||
python -m pdb qlib/workflow/cli.py examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
python -m pdb qlib/workflow/cli.py examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
`qrun` will be placed in your $PATH directory when installing ``Qlib``.
|
`qrun` will be placed in your $PATH directory when installing ``Qlib``.
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
The symbol `&` in `yaml` file stands for an anchor of a field, which is useful when another fields include this parameter as part of the value. Taking the configuration file above as an example, users can directly change the value of `market` and `benchmark` without traversing the entire configuration file.
|
The symbol `&` in `yaml` file stands for an anchor of a field, which is useful when another fields include this parameter as part of the value. Taking the configuration file above as an example, users can directly change the value of `market` and `benchmark` without traversing the entire configuration file.
|
||||||
|
|
||||||
|
|
||||||
Configuration File
|
Configuration File
|
||||||
===================
|
==================
|
||||||
|
|
||||||
Let's get into details of ``qrun`` in this section.
|
Let's get into details of ``qrun`` in this section.
|
||||||
Before using ``qrun``, users need to prepare a configuration file. The following content shows how to prepare each part of the configuration file.
|
Before using ``qrun``, users need to prepare a configuration file. The following content shows how to prepare each part of the configuration file.
|
||||||
|
|
||||||
The design logic of the configuration file is very simple. It predefines fixed workflows and provide this yaml interface to users to define how to initialize each component.
|
The design logic of the configuration file is very simple. It predefines fixed workflows and provide this yaml interface to users to define how to initialize each component.
|
||||||
It follow the design of `init_instance_by_config <https://github.com/microsoft/qlib/blob/2aee9e0145decc3e71def70909639b5e5a6f4b58/qlib/utils/__init__.py#L264>`_ . It defines the initialization of each component of Qlib, which typically include the class and the initialization arguments.
|
It follow the design of `init_instance_by_config <https://github.com/microsoft/qlib/blob/2aee9e0145decc3e71def70909639b5e5a6f4b58/qlib/utils/__init__.py#L264>`_ . It defines the initialization of each component of Qlib, which typically include the class and the initialization arguments.
|
||||||
|
|
||||||
For example, the following yaml and code are equivalent.
|
For example, the following yaml and code are equivalent.
|
||||||
@@ -166,7 +166,7 @@ For example, the following yaml and code are equivalent.
|
|||||||
|
|
||||||
|
|
||||||
Qlib Init Section
|
Qlib Init Section
|
||||||
--------------------
|
-----------------
|
||||||
|
|
||||||
At first, the configuration file needs to contain several basic parameters which will be used for qlib initialization.
|
At first, the configuration file needs to contain several basic parameters which will be used for qlib initialization.
|
||||||
|
|
||||||
@@ -181,21 +181,21 @@ The meaning of each field is as follows:
|
|||||||
Type: str. The URI of the Qlib data. For example, it could be the location where the data loaded by ``get_data.py`` are stored.
|
Type: str. The URI of the Qlib data. For example, it could be the location where the data loaded by ``get_data.py`` are stored.
|
||||||
|
|
||||||
- `region`
|
- `region`
|
||||||
- If `region` == "us", ``Qlib`` will be initialized in US-stock mode.
|
- If `region` == "us", ``Qlib`` will be initialized in US-stock mode.
|
||||||
- If `region` == "cn", ``Qlib`` will be initialized in China-stock mode.
|
- If `region` == "cn", ``Qlib`` will be initialized in China-stock mode.
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
The value of `region` should be aligned with the data stored in `provider_uri`.
|
The value of `region` should be aligned with the data stored in `provider_uri`.
|
||||||
|
|
||||||
|
|
||||||
Task Section
|
Task Section
|
||||||
--------------------
|
------------
|
||||||
|
|
||||||
The `task` field in the configuration corresponds to a `task`, which contains the parameters of three different subsections: `Model`, `Dataset` and `Record`.
|
The `task` field in the configuration corresponds to a `task`, which contains the parameters of three different subsections: `Model`, `Dataset` and `Record`.
|
||||||
|
|
||||||
Model Section
|
Model Section
|
||||||
~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~
|
||||||
|
|
||||||
In the `task` field, the `model` section describes the parameters of the model to be used for training and inference. For more information about the base ``Model`` class, please refer to `Qlib Model <../component/model.html>`_.
|
In the `task` field, the `model` section describes the parameters of the model to be used for training and inference. For more information about the base ``Model`` class, please refer to `Qlib Model <../component/model.html>`_.
|
||||||
|
|
||||||
@@ -224,14 +224,14 @@ The meaning of each field is as follows:
|
|||||||
Type: str. The path for the model in qlib.
|
Type: str. The path for the model in qlib.
|
||||||
|
|
||||||
- `kwargs`
|
- `kwargs`
|
||||||
The keywords arguments for the model. Please refer to the specific model implementation for more information: `models <https://github.com/microsoft/qlib/blob/main/qlib/contrib/model>`_.
|
The keywords arguments for the model. Please refer to the specific model implementation for more information: `models <https://github.com/microsoft/qlib/blob/main/qlib/contrib/model>`_.
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
|
||||||
.. note::
|
|
||||||
|
|
||||||
``Qlib`` provides a util named: ``init_instance_by_config`` to initialize any class inside ``Qlib`` with the configuration includes the fields: `class`, `module_path` and `kwargs`.
|
``Qlib`` provides a util named: ``init_instance_by_config`` to initialize any class inside ``Qlib`` with the configuration includes the fields: `class`, `module_path` and `kwargs`.
|
||||||
|
|
||||||
Dataset Section
|
Dataset Section
|
||||||
~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
The `dataset` field describes the parameters for the ``Dataset`` module in ``Qlib`` as well those for the module ``DataHandler``. For more information about the ``Dataset`` module, please refer to `Qlib Data <../component/data.html#dataset>`_.
|
The `dataset` field describes the parameters for the ``Dataset`` module in ``Qlib`` as well those for the module ``DataHandler``. For more information about the ``Dataset`` module, please refer to `Qlib Data <../component/data.html#dataset>`_.
|
||||||
|
|
||||||
@@ -266,7 +266,7 @@ Here is the configuration for the ``Dataset`` module which will take care of dat
|
|||||||
test: [2017-01-01, 2020-08-01]
|
test: [2017-01-01, 2020-08-01]
|
||||||
|
|
||||||
Record Section
|
Record Section
|
||||||
~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~
|
||||||
|
|
||||||
The `record` field is about the parameters the ``Record`` module in ``Qlib``. ``Record`` is responsible for tracking training process and results such as `information Coefficient (IC)` and `backtest` in a standard format.
|
The `record` field is about the parameters the ``Record`` module in ``Qlib``. ``Record`` is responsible for tracking training process and results such as `information Coefficient (IC)` and `backtest` in a standard format.
|
||||||
|
|
||||||
@@ -282,7 +282,7 @@ The following script is the configuration of `backtest` and the `strategy` used
|
|||||||
topk: 50
|
topk: 50
|
||||||
n_drop: 5
|
n_drop: 5
|
||||||
signal:
|
signal:
|
||||||
- <MODEL>
|
- <MODEL>
|
||||||
- <DATASET>
|
- <DATASET>
|
||||||
backtest:
|
backtest:
|
||||||
limit_threshold: 0.095
|
limit_threshold: 0.095
|
||||||
@@ -299,13 +299,13 @@ Here is the configuration details of different `Record Template` such as ``Signa
|
|||||||
|
|
||||||
.. code-block:: YAML
|
.. code-block:: YAML
|
||||||
|
|
||||||
record:
|
record:
|
||||||
- class: SignalRecord
|
- class: SignalRecord
|
||||||
module_path: qlib.workflow.record_temp
|
module_path: qlib.workflow.record_temp
|
||||||
kwargs: {}
|
kwargs: {}
|
||||||
- class: PortAnaRecord
|
- class: PortAnaRecord
|
||||||
module_path: qlib.workflow.record_temp
|
module_path: qlib.workflow.record_temp
|
||||||
kwargs:
|
kwargs:
|
||||||
config: *port_analysis_config
|
config: *port_analysis_config
|
||||||
|
|
||||||
For more information about the ``Record`` module in ``Qlib``, user can refer to the related document: `Record <../component/recorder.html#record-template>`_.
|
For more information about the ``Record`` module in ``Qlib``, user can refer to the related document: `Record <../component/recorder.html#record-template>`_.
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
.. _code_standard:
|
.. _code_standard:
|
||||||
|
|
||||||
=================================
|
=============
|
||||||
Code Standard
|
Code Standard
|
||||||
=================================
|
=============
|
||||||
|
|
||||||
Docstring
|
Docstring
|
||||||
=================================
|
=========
|
||||||
Please use the `Numpydoc Style <https://stackoverflow.com/a/24385103>`_.
|
Please use the `Numpydoc Style <https://stackoverflow.com/a/24385103>`_.
|
||||||
|
|
||||||
Continuous Integration
|
Continuous Integration
|
||||||
=================================
|
======================
|
||||||
Continuous Integration (CI) tools help you stick to the quality standards by running tests every time you push a new commit and reporting the results to a pull request.
|
Continuous Integration (CI) tools help you stick to the quality standards by running tests every time you push a new commit and reporting the results to a pull request.
|
||||||
|
|
||||||
When you submit a PR request, you can check whether your code passes the CI tests in the "check" section at the bottom of the web page.
|
When you submit a PR request, you can check whether your code passes the CI tests in the "check" section at the bottom of the web page.
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ When you submit a PR request, you can check whether your code passes the CI test
|
|||||||
python -m black . -l 120
|
python -m black . -l 120
|
||||||
|
|
||||||
|
|
||||||
2. Qlib will check your code style pylint. The checking command is implemented in [github action workflow](https://github.com/microsoft/qlib/blob/0e8b94a552f1c457cfa6cd2c1bb3b87ebb3fb279/.github/workflows/test.yml#L66).
|
2. Qlib will check your code style pylint. The checking command is implemented in [github action workflow](https://github.com/microsoft/qlib/blob/0e8b94a552f1c457cfa6cd2c1bb3b87ebb3fb279/.github/workflows/test.yml#L66).
|
||||||
Sometime pylint's restrictions are not that reasonable. You can ignore specific errors like this
|
Sometime pylint's restrictions are not that reasonable. You can ignore specific errors like this
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
.. _client:
|
.. _client:
|
||||||
|
|
||||||
Qlib Client-Server Framework
|
Qlib Client-Server Framework
|
||||||
===================
|
============================
|
||||||
|
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
-----------
|
------------
|
||||||
Client-Server is designed to solve following problems
|
Client-Server is designed to solve following problems
|
||||||
|
|
||||||
- Manage the data in a centralized way. Users don't have to manage data of different versions.
|
- Manage the data in a centralized way. Users don't have to manage data of different versions.
|
||||||
@@ -159,13 +159,11 @@ Limitations
|
|||||||
2. The rolling operation expression with parameter `0` can not be updated rightly under mechanism of the client-server framework.
|
2. The rolling operation expression with parameter `0` can not be updated rightly under mechanism of the client-server framework.
|
||||||
|
|
||||||
API
|
API
|
||||||
********************
|
***
|
||||||
|
|
||||||
The client is based on `python-socketio<https://python-socketio.readthedocs.io>`_ which is a framework that supports WebSocket client for Python language. The client can only propose requests and receive results, which do not include any calculating procedure.
|
The client is based on `python-socketio<https://python-socketio.readthedocs.io>`_ which is a framework that supports WebSocket client for Python language. The client can only propose requests and receive results, which do not include any calculating procedure.
|
||||||
|
|
||||||
Class
|
Class
|
||||||
--------------------
|
-----
|
||||||
|
|
||||||
.. automodule:: qlib.data.client
|
.. automodule:: qlib.data.client
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
.. _online:
|
.. _online:
|
||||||
|
|
||||||
Online
|
Online
|
||||||
===================
|
======
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
-------------------
|
------------
|
||||||
|
|
||||||
Welcome to use Online, this module simulates what will be like if we do the real trading use our model and strategy.
|
Welcome to use Online, this module simulates what will be like if we do the real trading use our model and strategy.
|
||||||
|
|
||||||
@@ -31,11 +31,11 @@ The file structure can be viewed at fileStruct_.
|
|||||||
|
|
||||||
|
|
||||||
Example
|
Example
|
||||||
-------------------
|
-------
|
||||||
|
|
||||||
Let's take an example,
|
Let's take an example,
|
||||||
|
|
||||||
.. note:: Make sure you have the latest version of `qlib` installed.
|
.. note:: Make sure you have the latest version of `qlib` installed.
|
||||||
|
|
||||||
If you want to use the models and data provided by `qlib`, you only need to do as follows.
|
If you want to use the models and data provided by `qlib`, you only need to do as follows.
|
||||||
|
|
||||||
@@ -93,7 +93,7 @@ If Your account was saved in "./user_data/", you can see the performance of your
|
|||||||
Here 'SH000905' represents csi500 and 'SH000300' represents csi300
|
Here 'SH000905' represents csi500 and 'SH000300' represents csi300
|
||||||
|
|
||||||
Manage your account
|
Manage your account
|
||||||
--------------------
|
-------------------
|
||||||
|
|
||||||
Any account processed by `online` should be saved in a folder. you can use commands
|
Any account processed by `online` should be saved in a folder. you can use commands
|
||||||
defined to manage your accounts.
|
defined to manage your accounts.
|
||||||
@@ -161,7 +161,7 @@ be called at each trading date.
|
|||||||
>> online update -date 2019-10-16 -path ./user_data/
|
>> online update -date 2019-10-16 -path ./user_data/
|
||||||
|
|
||||||
API
|
API
|
||||||
------------------
|
---
|
||||||
|
|
||||||
All those operations are based on defined in `qlib.contrib.online.operator`
|
All those operations are based on defined in `qlib.contrib.online.operator`
|
||||||
|
|
||||||
@@ -170,7 +170,7 @@ All those operations are based on defined in `qlib.contrib.online.operator`
|
|||||||
.. _fileStruct:
|
.. _fileStruct:
|
||||||
|
|
||||||
File structure
|
File structure
|
||||||
------------------
|
--------------
|
||||||
|
|
||||||
'user_data' indicates the root of folder.
|
'user_data' indicates the root of folder.
|
||||||
Name that bold indicates it’s a folder, otherwise it’s a document.
|
Name that bold indicates it’s a folder, otherwise it’s a document.
|
||||||
@@ -214,7 +214,7 @@ Configuration file
|
|||||||
The configure file used in `online` should contain the model and strategy information.
|
The configure file used in `online` should contain the model and strategy information.
|
||||||
|
|
||||||
About the model
|
About the model
|
||||||
~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
First, your configuration file needs to have a field about the model,
|
First, your configuration file needs to have a field about the model,
|
||||||
this field and its contents determine the model we used when generating score at predict date.
|
this field and its contents determine the model we used when generating score at predict date.
|
||||||
@@ -243,7 +243,7 @@ contains 2 methods used in `online` module.
|
|||||||
|
|
||||||
|
|
||||||
About the strategy
|
About the strategy
|
||||||
~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
Your need define the strategy used to generate the order list at predict date.
|
Your need define the strategy used to generate the order list at predict date.
|
||||||
|
|
||||||
@@ -259,7 +259,7 @@ Followings are two examples for a TopkAmountStrategy
|
|||||||
n_drop: 10
|
n_drop: 10
|
||||||
|
|
||||||
Generated files
|
Generated files
|
||||||
------------------
|
---------------
|
||||||
|
|
||||||
The 'online_generate' command will create the order list at {folder_path}/{user_id}/temp/,
|
The 'online_generate' command will create the order list at {folder_path}/{user_id}/temp/,
|
||||||
the name of that is orderlist_{YYYY-MM-DD}.json, YYYY-MM-DD is the date that those orders to be executed.
|
the name of that is orderlist_{YYYY-MM-DD}.json, YYYY-MM-DD is the date that those orders to be executed.
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
.. _tuner:
|
.. _tuner:
|
||||||
|
|
||||||
Tuner
|
Tuner
|
||||||
===================
|
=====
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
-------------------
|
------------
|
||||||
|
|
||||||
Welcome to use Tuner, this document is based on that you can use Estimator proficiently and correctly.
|
Welcome to use Tuner, this document is based on that you can use Estimator proficiently and correctly.
|
||||||
|
|
||||||
@@ -41,19 +41,19 @@ We write a simple configuration example as following,
|
|||||||
tuner_class: QLibTuner
|
tuner_class: QLibTuner
|
||||||
qlib_client:
|
qlib_client:
|
||||||
auto_mount: False
|
auto_mount: False
|
||||||
logging_level: INFO
|
logging_level: INFO
|
||||||
optimization_criteria:
|
optimization_criteria:
|
||||||
report_type: model
|
report_type: model
|
||||||
report_factor: model_score
|
report_factor: model_score
|
||||||
optim_type: max
|
optim_type: max
|
||||||
tuner_pipeline:
|
tuner_pipeline:
|
||||||
-
|
-
|
||||||
model:
|
model:
|
||||||
class: SomeModel
|
class: SomeModel
|
||||||
space: SomeModelSpace
|
space: SomeModelSpace
|
||||||
trainer:
|
trainer:
|
||||||
class: RollingTrainer
|
class: RollingTrainer
|
||||||
strategy:
|
strategy:
|
||||||
class: TopkAmountStrategy
|
class: TopkAmountStrategy
|
||||||
space: TopkAmountStrategySpace
|
space: TopkAmountStrategySpace
|
||||||
max_evals: 2
|
max_evals: 2
|
||||||
@@ -166,13 +166,13 @@ Also, there are some optional fields. The meaning of each field is as follows:
|
|||||||
The class of tuner, str type, must be an already implemented model, such as `QLibTuner` in `qlib`, or a custom tuner, but it must be a subclass of `qlib.contrib.tuner.Tuner`, the default value is `QLibTuner`.
|
The class of tuner, str type, must be an already implemented model, such as `QLibTuner` in `qlib`, or a custom tuner, but it must be a subclass of `qlib.contrib.tuner.Tuner`, the default value is `QLibTuner`.
|
||||||
|
|
||||||
- `tuner_module_path`
|
- `tuner_module_path`
|
||||||
The module path, str type, absolute url is also supported, indicates the path of the implementation of tuner. The default value is `qlib.contrib.tuner.tuner`
|
The module path, str type, absolute url is also supported, indicates the path of the implementation of tuner. The default value is `qlib.contrib.tuner.tuner`
|
||||||
|
|
||||||
About the optimization criteria
|
About the optimization criteria
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
You need to designate a factor to optimize, for tuner need a factor to decide which case is better than other cases.
|
You need to designate a factor to optimize, for tuner need a factor to decide which case is better than other cases.
|
||||||
Usually, we use the result of `estimator`, such as backtest results and the score of model.
|
Usually, we use the result of `estimator`, such as backtest results and the score of model.
|
||||||
|
|
||||||
This part needs contain these fields:
|
This part needs contain these fields:
|
||||||
|
|
||||||
@@ -203,13 +203,13 @@ The tuner pipeline contains different tuners, and the `tuner` program will proce
|
|||||||
.. code-block:: YAML
|
.. code-block:: YAML
|
||||||
|
|
||||||
tuner_pipeline:
|
tuner_pipeline:
|
||||||
-
|
-
|
||||||
model:
|
model:
|
||||||
class: SomeModel
|
class: SomeModel
|
||||||
space: SomeModelSpace
|
space: SomeModelSpace
|
||||||
trainer:
|
trainer:
|
||||||
class: RollingTrainer
|
class: RollingTrainer
|
||||||
strategy:
|
strategy:
|
||||||
class: TopkAmountStrategy
|
class: TopkAmountStrategy
|
||||||
space: TopkAmountStrategySpace
|
space: TopkAmountStrategySpace
|
||||||
max_evals: 2
|
max_evals: 2
|
||||||
@@ -249,25 +249,25 @@ You need to use the same dataset to evaluate your different `estimator` experime
|
|||||||
test_start_date: 2016-07-01
|
test_start_date: 2016-07-01
|
||||||
test_end_date: 2018-04-30
|
test_end_date: 2018-04-30
|
||||||
|
|
||||||
- `rolling_period`
|
- `rolling_period`
|
||||||
The rolling period, integer type, indicates how many time steps need rolling when rolling the data. The default value is `60`. If you use `RollingTrainer`, this config will be used, or it will be ignored.
|
The rolling period, integer type, indicates how many time steps need rolling when rolling the data. The default value is `60`. If you use `RollingTrainer`, this config will be used, or it will be ignored.
|
||||||
|
|
||||||
- `train_start_date`
|
- `train_start_date`
|
||||||
Training start time, str type.
|
Training start time, str type.
|
||||||
|
|
||||||
- `train_end_date`
|
- `train_end_date`
|
||||||
Training end time, str type.
|
Training end time, str type.
|
||||||
|
|
||||||
- `validate_start_date`
|
- `validate_start_date`
|
||||||
Validation start time, str type.
|
Validation start time, str type.
|
||||||
|
|
||||||
- `validate_end_date`
|
- `validate_end_date`
|
||||||
Validation end time, str type.
|
Validation end time, str type.
|
||||||
|
|
||||||
- `test_start_date`
|
- `test_start_date`
|
||||||
Test start time, str type.
|
Test start time, str type.
|
||||||
|
|
||||||
- `test_end_date`
|
- `test_end_date`
|
||||||
Test end time, str type. If `test_end_date` is `-1` or greater than the last date of the data, the last date of the data will be used as `test_end_date`.
|
Test end time, str type. If `test_end_date` is `-1` or greater than the last date of the data, the last date of the data will be used as `test_end_date`.
|
||||||
|
|
||||||
About the data and backtest
|
About the data and backtest
|
||||||
@@ -315,11 +315,10 @@ About the data and backtest
|
|||||||
Experiment Result
|
Experiment Result
|
||||||
-----------------
|
-----------------
|
||||||
|
|
||||||
All the results are stored in experiment file directly, you can check them directly in the corresponding files.
|
All the results are stored in experiment file directly, you can check them directly in the corresponding files.
|
||||||
What we save are as following:
|
What we save are as following:
|
||||||
|
|
||||||
- Global optimal parameters
|
- Global optimal parameters
|
||||||
- Local optimal parameters of each tuner
|
- Local optimal parameters of each tuner
|
||||||
- Config file of this `tuner` experiment
|
- Config file of this `tuner` experiment
|
||||||
- Every `estimator` experiments result in the process
|
- Every `estimator` experiments result in the process
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
============================================================
|
======================
|
||||||
``Qlib`` Documentation
|
``Qlib`` Documentation
|
||||||
============================================================
|
======================
|
||||||
|
|
||||||
``Qlib`` is an AI-oriented quantitative investment platform, which aims to realize the potential, empower the research, and create the value of AI technologies in quantitative investment.
|
``Qlib`` is an AI-oriented quantitative investment platform, which aims to realize the potential, empower the research, and create the value of AI technologies in quantitative investment.
|
||||||
|
|
||||||
@@ -24,12 +24,12 @@ Document Structure
|
|||||||
.. toctree::
|
.. toctree::
|
||||||
:maxdepth: 3
|
:maxdepth: 3
|
||||||
:caption: FIRST STEPS:
|
:caption: FIRST STEPS:
|
||||||
|
|
||||||
Installation <start/installation.rst>
|
Installation <start/installation.rst>
|
||||||
Initialization <start/initialization.rst>
|
Initialization <start/initialization.rst>
|
||||||
Data Retrieval <start/getdata.rst>
|
Data Retrieval <start/getdata.rst>
|
||||||
Custom Model Integration <start/integration.rst>
|
Custom Model Integration <start/integration.rst>
|
||||||
|
|
||||||
|
|
||||||
.. toctree::
|
.. toctree::
|
||||||
:maxdepth: 3
|
:maxdepth: 3
|
||||||
@@ -48,7 +48,7 @@ Document Structure
|
|||||||
.. toctree::
|
.. toctree::
|
||||||
:maxdepth: 3
|
:maxdepth: 3
|
||||||
:caption: ADVANCED TOPICS:
|
:caption: ADVANCED TOPICS:
|
||||||
|
|
||||||
Building Formulaic Alphas <advanced/alpha.rst>
|
Building Formulaic Alphas <advanced/alpha.rst>
|
||||||
Online & Offline mode <advanced/server.rst>
|
Online & Offline mode <advanced/server.rst>
|
||||||
Serialization <advanced/serial.rst>
|
Serialization <advanced/serial.rst>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
===============================
|
===============================
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
|
|
||||||
.. image:: ../_static/img/logo/white_bg_rec+word.png
|
.. image:: ../_static/img/logo/white_bg_rec+word.png
|
||||||
:align: center
|
:align: center
|
||||||
@@ -13,8 +13,8 @@ Introduction
|
|||||||
With ``Qlib``, users can easily try their ideas to create better Quant investment strategies.
|
With ``Qlib``, users can easily try their ideas to create better Quant investment strategies.
|
||||||
|
|
||||||
Framework
|
Framework
|
||||||
===================
|
=========
|
||||||
|
|
||||||
.. image:: ../_static/img/framework.svg
|
.. image:: ../_static/img/framework.svg
|
||||||
:align: center
|
:align: center
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ At the module level, Qlib is a platform that consists of above components. The c
|
|||||||
Name Description
|
Name Description
|
||||||
======================== ==============================================================================
|
======================== ==============================================================================
|
||||||
`Infrastructure` layer `Infrastructure` layer provides underlying support for Quant research.
|
`Infrastructure` layer `Infrastructure` layer provides underlying support for Quant research.
|
||||||
`DataServer` provides high-performance infrastructure for users to manage
|
`DataServer` provides high-performance infrastructure for users to manage
|
||||||
and retrieve raw data. `Trainer` provides flexible interface to control
|
and retrieve raw data. `Trainer` provides flexible interface to control
|
||||||
the training process of models which enable algorithms controlling the
|
the training process of models which enable algorithms controlling the
|
||||||
training process.
|
training process.
|
||||||
@@ -35,13 +35,13 @@ Name Description
|
|||||||
`Workflow` layer `Workflow` layer covers the whole workflow of quantitative investment.
|
`Workflow` layer `Workflow` layer covers the whole workflow of quantitative investment.
|
||||||
`Information Extractor` extracts data for models. `Forecast Model` focuses
|
`Information Extractor` extracts data for models. `Forecast Model` focuses
|
||||||
on producing all kinds of forecast signals (e.g. *alpha*, risk) for other
|
on producing all kinds of forecast signals (e.g. *alpha*, risk) for other
|
||||||
modules. With these signals `Decision Generator` will generate the target
|
modules. With these signals `Decision Generator` will generate the target
|
||||||
trading decisions(i.e. portfolio, orders) to be executed by `Execution Env`
|
trading decisions(i.e. portfolio, orders) to be executed by `Execution Env`
|
||||||
(i.e. the trading market). There may be multiple levels of `Trading Agent`
|
(i.e. the trading market). There may be multiple levels of `Trading Agent`
|
||||||
and `Execution Env` (e.g. an *order executor trading agent and intraday
|
and `Execution Env` (e.g. an *order executor trading agent and intraday
|
||||||
order execution environment* could behave like an interday trading
|
order execution environment* could behave like an interday trading
|
||||||
environment and nested in *daily portfolio management trading agent and
|
environment and nested in *daily portfolio management trading agent and
|
||||||
interday trading environment* )
|
interday trading environment* )
|
||||||
|
|
||||||
`Interface` layer `Interface` layer tries to present a user-friendly interface for the underlying
|
`Interface` layer `Interface` layer tries to present a user-friendly interface for the underlying
|
||||||
system. `Analyser` module will provide users detailed analysis reports of
|
system. `Analyser` module will provide users detailed analysis reports of
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
|
|
||||||
===============================
|
===========
|
||||||
Quick Start
|
Quick Start
|
||||||
===============================
|
===========
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
==============
|
============
|
||||||
|
|
||||||
This ``Quick Start`` guide tries to demonstrate
|
This ``Quick Start`` guide tries to demonstrate
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ This ``Quick Start`` guide tries to demonstrate
|
|||||||
|
|
||||||
|
|
||||||
Installation
|
Installation
|
||||||
==================
|
============
|
||||||
|
|
||||||
Users can easily intsall ``Qlib`` according to the following steps:
|
Users can easily intsall ``Qlib`` according to the following steps:
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ Users can easily intsall ``Qlib`` according to the following steps:
|
|||||||
To known more about `installation`, please refer to `Qlib Installation <../start/installation.html>`_.
|
To known more about `installation`, please refer to `Qlib Installation <../start/installation.html>`_.
|
||||||
|
|
||||||
Prepare Data
|
Prepare Data
|
||||||
==============
|
============
|
||||||
|
|
||||||
Load and prepare data by running the following code:
|
Load and prepare data by running the following code:
|
||||||
|
|
||||||
@@ -47,14 +47,14 @@ This dataset is created by public data collected by crawler scripts in ``scripts
|
|||||||
To known more about `prepare data`, please refer to `Data Preparation <../component/data.html#data-preparation>`_.
|
To known more about `prepare data`, please refer to `Data Preparation <../component/data.html#data-preparation>`_.
|
||||||
|
|
||||||
Auto Quant Research Workflow
|
Auto Quant Research Workflow
|
||||||
====================================
|
============================
|
||||||
|
|
||||||
``Qlib`` provides a tool named ``qrun`` to run the whole workflow automatically (including building dataset, training models, backtest and evaluation). Users can start an auto quant research workflow and have a graphical reports analysis according to the following steps:
|
``Qlib`` provides a tool named ``qrun`` to run the whole workflow automatically (including building dataset, training models, backtest and evaluation). Users can start an auto quant research workflow and have a graphical reports analysis according to the following steps:
|
||||||
|
|
||||||
- Quant Research Workflow:
|
- Quant Research Workflow:
|
||||||
- Run ``qrun`` with a config file of the LightGBM model `workflow_config_lightgbm.yaml` as following.
|
- Run ``qrun`` with a config file of the LightGBM model `workflow_config_lightgbm.yaml` as following.
|
||||||
|
|
||||||
.. code-block::
|
.. code-block::
|
||||||
|
|
||||||
cd examples # Avoid running program under the directory contains `qlib`
|
cd examples # Avoid running program under the directory contains `qlib`
|
||||||
qrun benchmarks/LightGBM/workflow_config_lightgbm.yaml
|
qrun benchmarks/LightGBM/workflow_config_lightgbm.yaml
|
||||||
@@ -64,7 +64,7 @@ Auto Quant Research Workflow
|
|||||||
The result of ``qrun`` is as follows, which is also the typical result of ``Forecast model(alpha)``. Please refer to `Intraday Trading <../component/backtest.html>`_. for more details about the result.
|
The result of ``qrun`` is as follows, which is also the typical result of ``Forecast model(alpha)``. Please refer to `Intraday Trading <../component/backtest.html>`_. for more details about the result.
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
risk
|
risk
|
||||||
excess_return_without_cost mean 0.000605
|
excess_return_without_cost mean 0.000605
|
||||||
std 0.005481
|
std 0.005481
|
||||||
@@ -77,7 +77,7 @@ Auto Quant Research Workflow
|
|||||||
information_ratio 1.187411
|
information_ratio 1.187411
|
||||||
max_drawdown -0.075024
|
max_drawdown -0.075024
|
||||||
|
|
||||||
|
|
||||||
To know more about `workflow` and `qrun`, please refer to `Workflow: Workflow Management <../component/workflow.html>`_.
|
To know more about `workflow` and `qrun`, please refer to `Workflow: Workflow Management <../component/workflow.html>`_.
|
||||||
|
|
||||||
- Graphical Reports Analysis:
|
- Graphical Reports Analysis:
|
||||||
@@ -89,6 +89,6 @@ Auto Quant Research Workflow
|
|||||||
|
|
||||||
|
|
||||||
Custom Model Integration
|
Custom Model Integration
|
||||||
===============================================
|
========================
|
||||||
|
|
||||||
``Qlib`` provides a batch of models (such as ``lightGBM`` and ``MLP`` models) as examples of ``Forecast Model``. In addition to the default model, users can integrate their own custom models into ``Qlib``. If users are interested in the custom model, please refer to `Custom Model Integration <../start/integration.html>`_.
|
``Qlib`` provides a batch of models (such as ``lightGBM`` and ``MLP`` models) as examples of ``Forecast Model``. In addition to the default model, users can integrate their own custom models into ``Qlib``. If users are interested in the custom model, please refer to `Custom Model Integration <../start/integration.html>`_.
|
||||||
|
|||||||
35
docs/make.bat
Normal file
35
docs/make.bat
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
@ECHO OFF
|
||||||
|
|
||||||
|
pushd %~dp0
|
||||||
|
|
||||||
|
REM Command file for Sphinx documentation
|
||||||
|
|
||||||
|
if "%SPHINXBUILD%" == "" (
|
||||||
|
set SPHINXBUILD=sphinx-build
|
||||||
|
)
|
||||||
|
set SOURCEDIR=.
|
||||||
|
set BUILDDIR=_build
|
||||||
|
|
||||||
|
%SPHINXBUILD% >NUL 2>NUL
|
||||||
|
if errorlevel 9009 (
|
||||||
|
echo.
|
||||||
|
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
|
||||||
|
echo.installed, then set the SPHINXBUILD environment variable to point
|
||||||
|
echo.to the full path of the 'sphinx-build' executable. Alternatively you
|
||||||
|
echo.may add the Sphinx directory to PATH.
|
||||||
|
echo.
|
||||||
|
echo.If you don't have Sphinx installed, grab it from
|
||||||
|
echo.https://www.sphinx-doc.org/
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
if "%1" == "" goto help
|
||||||
|
|
||||||
|
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
|
||||||
|
goto end
|
||||||
|
|
||||||
|
:help
|
||||||
|
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
|
||||||
|
|
||||||
|
:end
|
||||||
|
popd
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
.. _api:
|
.. _api:
|
||||||
================================
|
=============
|
||||||
API Reference
|
API Reference
|
||||||
================================
|
=============
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -9,32 +9,32 @@ Here you can find all ``Qlib`` interfaces.
|
|||||||
|
|
||||||
|
|
||||||
Data
|
Data
|
||||||
====================
|
====
|
||||||
|
|
||||||
Provider
|
Provider
|
||||||
--------------------
|
--------
|
||||||
|
|
||||||
.. automodule:: qlib.data.data
|
.. automodule:: qlib.data.data
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Filter
|
Filter
|
||||||
--------------------
|
------
|
||||||
|
|
||||||
.. automodule:: qlib.data.filter
|
.. automodule:: qlib.data.filter
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Class
|
Class
|
||||||
--------------------
|
-----
|
||||||
.. automodule:: qlib.data.base
|
.. automodule:: qlib.data.base
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Operator
|
Operator
|
||||||
--------------------
|
--------
|
||||||
.. automodule:: qlib.data.ops
|
.. automodule:: qlib.data.ops
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Cache
|
Cache
|
||||||
----------------
|
-----
|
||||||
.. autoclass:: qlib.data.cache.MemCacheUnit
|
.. autoclass:: qlib.data.cache.MemCacheUnit
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ Cache
|
|||||||
|
|
||||||
|
|
||||||
Storage
|
Storage
|
||||||
-------------
|
-------
|
||||||
.. autoclass:: qlib.data.storage.storage.BaseStorage
|
.. autoclass:: qlib.data.storage.storage.BaseStorage
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
@@ -82,52 +82,52 @@ Storage
|
|||||||
|
|
||||||
|
|
||||||
Dataset
|
Dataset
|
||||||
---------------
|
-------
|
||||||
|
|
||||||
Dataset Class
|
Dataset Class
|
||||||
~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~
|
||||||
.. automodule:: qlib.data.dataset.__init__
|
.. automodule:: qlib.data.dataset.__init__
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Data Loader
|
Data Loader
|
||||||
~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~
|
||||||
.. automodule:: qlib.data.dataset.loader
|
.. automodule:: qlib.data.dataset.loader
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Data Handler
|
Data Handler
|
||||||
~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~
|
||||||
.. automodule:: qlib.data.dataset.handler
|
.. automodule:: qlib.data.dataset.handler
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Processor
|
Processor
|
||||||
~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~
|
||||||
.. automodule:: qlib.data.dataset.processor
|
.. automodule:: qlib.data.dataset.processor
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
Contrib
|
Contrib
|
||||||
====================
|
=======
|
||||||
|
|
||||||
Model
|
Model
|
||||||
--------------------
|
-----
|
||||||
.. automodule:: qlib.model.base
|
.. automodule:: qlib.model.base
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Strategy
|
Strategy
|
||||||
-------------------
|
--------
|
||||||
|
|
||||||
.. automodule:: qlib.contrib.strategy.strategy
|
.. automodule:: qlib.contrib.strategy.strategy
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Evaluate
|
Evaluate
|
||||||
-----------------
|
--------
|
||||||
|
|
||||||
.. automodule:: qlib.contrib.evaluate
|
.. automodule:: qlib.contrib.evaluate
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
Report
|
Report
|
||||||
-----------------
|
------
|
||||||
|
|
||||||
.. automodule:: qlib.contrib.report.analysis_position.report
|
.. automodule:: qlib.contrib.report.analysis_position.report
|
||||||
:members:
|
:members:
|
||||||
@@ -159,103 +159,100 @@ Report
|
|||||||
|
|
||||||
|
|
||||||
Workflow
|
Workflow
|
||||||
====================
|
========
|
||||||
|
|
||||||
|
|
||||||
Experiment Manager
|
Experiment Manager
|
||||||
--------------------
|
------------------
|
||||||
.. autoclass:: qlib.workflow.expm.ExpManager
|
.. autoclass:: qlib.workflow.expm.ExpManager
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Experiment
|
Experiment
|
||||||
--------------------
|
----------
|
||||||
.. autoclass:: qlib.workflow.exp.Experiment
|
.. autoclass:: qlib.workflow.exp.Experiment
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Recorder
|
Recorder
|
||||||
--------------------
|
--------
|
||||||
.. autoclass:: qlib.workflow.recorder.Recorder
|
.. autoclass:: qlib.workflow.recorder.Recorder
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Record Template
|
Record Template
|
||||||
--------------------
|
---------------
|
||||||
.. automodule:: qlib.workflow.record_temp
|
.. automodule:: qlib.workflow.record_temp
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Task Management
|
Task Management
|
||||||
====================
|
===============
|
||||||
|
|
||||||
|
|
||||||
TaskGen
|
TaskGen
|
||||||
--------------------
|
-------
|
||||||
.. automodule:: qlib.workflow.task.gen
|
.. automodule:: qlib.workflow.task.gen
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
TaskManager
|
TaskManager
|
||||||
--------------------
|
-----------
|
||||||
.. automodule:: qlib.workflow.task.manage
|
.. automodule:: qlib.workflow.task.manage
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Trainer
|
Trainer
|
||||||
--------------------
|
-------
|
||||||
.. automodule:: qlib.model.trainer
|
.. automodule:: qlib.model.trainer
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Collector
|
Collector
|
||||||
--------------------
|
---------
|
||||||
.. automodule:: qlib.workflow.task.collect
|
.. automodule:: qlib.workflow.task.collect
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Group
|
Group
|
||||||
--------------------
|
-----
|
||||||
.. automodule:: qlib.model.ens.group
|
.. automodule:: qlib.model.ens.group
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Ensemble
|
Ensemble
|
||||||
--------------------
|
--------
|
||||||
.. automodule:: qlib.model.ens.ensemble
|
.. automodule:: qlib.model.ens.ensemble
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Utils
|
Utils
|
||||||
--------------------
|
-----
|
||||||
.. automodule:: qlib.workflow.task.utils
|
.. automodule:: qlib.workflow.task.utils
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
Online Serving
|
Online Serving
|
||||||
====================
|
==============
|
||||||
|
|
||||||
|
|
||||||
Online Manager
|
Online Manager
|
||||||
--------------------
|
--------------
|
||||||
.. automodule:: qlib.workflow.online.manager
|
.. automodule:: qlib.workflow.online.manager
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Online Strategy
|
Online Strategy
|
||||||
--------------------
|
---------------
|
||||||
.. automodule:: qlib.workflow.online.strategy
|
.. automodule:: qlib.workflow.online.strategy
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Online Tool
|
Online Tool
|
||||||
--------------------
|
-----------
|
||||||
.. automodule:: qlib.workflow.online.utils
|
.. automodule:: qlib.workflow.online.utils
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
RecordUpdater
|
RecordUpdater
|
||||||
--------------------
|
-------------
|
||||||
.. automodule:: qlib.workflow.online.update
|
.. automodule:: qlib.workflow.online.update
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
Utils
|
Utils
|
||||||
====================
|
=====
|
||||||
|
|
||||||
Serializable
|
Serializable
|
||||||
--------------------
|
------------
|
||||||
|
|
||||||
.. automodule:: qlib.utils.serial.Serializable
|
.. automodule:: qlib.utils.serial.Serializable
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
.. _getdata:
|
.. _getdata:
|
||||||
|
|
||||||
=============================
|
==============
|
||||||
Data Retrieval
|
Data Retrieval
|
||||||
=============================
|
==============
|
||||||
|
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
====================
|
============
|
||||||
|
|
||||||
Users can get stock data with ``Qlib``. The following examples demonstrate the basic user interface.
|
Users can get stock data with ``Qlib``. The following examples demonstrate the basic user interface.
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
====================
|
========
|
||||||
|
|
||||||
|
|
||||||
``QLib`` Initialization:
|
``QLib`` Initialization:
|
||||||
@@ -30,7 +30,7 @@ If users followed steps in `initialization <initialization.html>`_ and downloade
|
|||||||
Load trading calendar with given time range and frequency:
|
Load trading calendar with given time range and frequency:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
>> from qlib.data import D
|
>> from qlib.data import D
|
||||||
>> D.calendar(start_time='2010-01-01', end_time='2017-12-31', freq='day')[:2]
|
>> D.calendar(start_time='2010-01-01', end_time='2017-12-31', freq='day')[:2]
|
||||||
[Timestamp('2010-01-04 00:00:00'), Timestamp('2010-01-05 00:00:00')]
|
[Timestamp('2010-01-04 00:00:00'), Timestamp('2010-01-05 00:00:00')]
|
||||||
@@ -46,7 +46,7 @@ Parse a given market name into a stock pool config:
|
|||||||
Load instruments of certain stock pool in the given time range:
|
Load instruments of certain stock pool in the given time range:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
>> from qlib.data import D
|
>> from qlib.data import D
|
||||||
>> instruments = D.instruments(market='csi300')
|
>> instruments = D.instruments(market='csi300')
|
||||||
>> D.list_instruments(instruments=instruments, start_time='2010-01-01', end_time='2017-12-31', as_list=True)[:6]
|
>> D.list_instruments(instruments=instruments, start_time='2010-01-01', end_time='2017-12-31', as_list=True)[:6]
|
||||||
@@ -79,14 +79,14 @@ For more details about filter, please refer `Filter API <../component/data.html>
|
|||||||
Load features of certain instruments in a given time range:
|
Load features of certain instruments in a given time range:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
>> from qlib.data import D
|
>> from qlib.data import D
|
||||||
>> instruments = ['SH600000']
|
>> instruments = ['SH600000']
|
||||||
>> fields = ['$close', '$volume', 'Ref($close, 1)', 'Mean($close, 3)', '$high-$low']
|
>> fields = ['$close', '$volume', 'Ref($close, 1)', 'Mean($close, 3)', '$high-$low']
|
||||||
>> D.features(instruments, fields, start_time='2010-01-01', end_time='2017-12-31', freq='day').head()
|
>> D.features(instruments, fields, start_time='2010-01-01', end_time='2017-12-31', freq='day').head()
|
||||||
|
|
||||||
$close $volume Ref($close, 1) Mean($close, 3) $high-$low
|
$close $volume Ref($close, 1) Mean($close, 3) $high-$low
|
||||||
instrument datetime
|
instrument datetime
|
||||||
SH600000 2010-01-04 86.778313 16162960.0 88.825928 88.061483 2.907631
|
SH600000 2010-01-04 86.778313 16162960.0 88.825928 88.061483 2.907631
|
||||||
2010-01-05 87.433578 28117442.0 86.778313 87.679273 3.235252
|
2010-01-05 87.433578 28117442.0 86.778313 87.679273 3.235252
|
||||||
2010-01-06 85.713585 23632884.0 87.433578 86.641825 1.720009
|
2010-01-06 85.713585 23632884.0 87.433578 86.641825 1.720009
|
||||||
@@ -108,7 +108,7 @@ Load features of certain stock pool in a given time range:
|
|||||||
>> D.features(instruments, fields, start_time='2010-01-01', end_time='2017-12-31', freq='day').head()
|
>> D.features(instruments, fields, start_time='2010-01-01', end_time='2017-12-31', freq='day').head()
|
||||||
|
|
||||||
$close $volume Ref($close, 1) Mean($close, 3) $high-$low
|
$close $volume Ref($close, 1) Mean($close, 3) $high-$low
|
||||||
instrument datetime
|
instrument datetime
|
||||||
SH600655 2010-01-04 2699.567383 158193.328125 2619.070312 2626.097738 124.580566
|
SH600655 2010-01-04 2699.567383 158193.328125 2619.070312 2626.097738 124.580566
|
||||||
2010-01-08 2612.359619 77501.406250 2584.567627 2623.220133 83.373047
|
2010-01-08 2612.359619 77501.406250 2584.567627 2623.220133 83.373047
|
||||||
2010-01-11 2712.982422 160852.390625 2612.359619 2636.636556 146.621582
|
2010-01-11 2712.982422 160852.390625 2612.359619 2636.636556 146.621582
|
||||||
@@ -127,7 +127,7 @@ For example, it looks quite long and complicated:
|
|||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
>> from qlib.data import D
|
>> from qlib.data import D
|
||||||
>> data = D.features(["sh600519"], ["(($high / $close) + ($open / $close)) * (($high / $close) + ($open / $close)) / ($high / $close) + ($open / $close)"], start_time="20200101")
|
>> data = D.features(["sh600519"], ["(($high / $close) + ($open / $close)) * (($high / $close) + ($open / $close)) / (($high / $close) + ($open / $close))"], start_time="20200101")
|
||||||
|
|
||||||
|
|
||||||
But using string is not the only way to implement the expression. You can also implement expression by code.
|
But using string is not the only way to implement the expression. You can also implement expression by code.
|
||||||
@@ -147,5 +147,5 @@ Here is an exmaple which does the same thing as above examples.
|
|||||||
|
|
||||||
|
|
||||||
API
|
API
|
||||||
====================
|
===
|
||||||
To know more about how to use the Data, go to API Reference: `Data API <../reference/api.html#data>`_
|
To know more about how to use the Data, go to API Reference: `Data API <../reference/api.html#data>`_
|
||||||
|
|||||||
@@ -1,23 +1,23 @@
|
|||||||
.. _initialization:
|
.. _initialization:
|
||||||
|
|
||||||
====================
|
===================
|
||||||
Qlib Initialization
|
Qlib Initialization
|
||||||
====================
|
===================
|
||||||
|
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
|
|
||||||
Initialization
|
Initialization
|
||||||
=========================
|
==============
|
||||||
|
|
||||||
Please follow the steps below to initialize ``Qlib``.
|
Please follow the steps below to initialize ``Qlib``.
|
||||||
|
|
||||||
Download and prepare the Data: execute the following command to download stock data. Please pay `attention` that the data is collected from `Yahoo Finance <https://finance.yahoo.com/lookup>`_ and the data might not be perfect. We recommend users to prepare their own data if they have high-quality datasets. Please refer to `Data <../component/data.html#converting-csv-format-into-qlib-format>`_ for more information about customized dataset.
|
Download and prepare the Data: execute the following command to download stock data. Please pay `attention` that the data is collected from `Yahoo Finance <https://finance.yahoo.com/lookup>`_ and the data might not be perfect. We recommend users to prepare their own data if they have high-quality datasets. Please refer to `Data <../component/data.html#converting-csv-format-into-qlib-format>`_ for more information about customized dataset.
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn
|
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn
|
||||||
|
|
||||||
Please refer to `Data Preparation <../component/data.html#data-preparation>`_ for more information about `get_data.py`,
|
Please refer to `Data Preparation <../component/data.html#data-preparation>`_ for more information about `get_data.py`,
|
||||||
|
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ Initialize Qlib before calling other APIs: run following code in python.
|
|||||||
from qlib.constant import REG_CN
|
from qlib.constant import REG_CN
|
||||||
provider_uri = "~/.qlib/qlib_data/cn_data" # target_dir
|
provider_uri = "~/.qlib/qlib_data/cn_data" # target_dir
|
||||||
qlib.init(provider_uri=provider_uri, region=REG_CN)
|
qlib.init(provider_uri=provider_uri, region=REG_CN)
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
Do not import qlib package in the repository directory of ``Qlib``, otherwise, errors may occur.
|
Do not import qlib package in the repository directory of ``Qlib``, otherwise, errors may occur.
|
||||||
|
|
||||||
@@ -56,16 +56,16 @@ The following are several important parameters of `qlib.init` (`Qlib` has a lot
|
|||||||
- `redis_port`
|
- `redis_port`
|
||||||
Type: int, optional parameter(default: 6379), port of `redis`
|
Type: int, optional parameter(default: 6379), port of `redis`
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
The value of `region` should be aligned with the data stored in `provider_uri`. Currently, ``scripts/get_data.py`` only provides China stock market data. If users want to use the US stock market data, they should prepare their own US-stock data in `provider_uri` and switch to US-stock mode.
|
The value of `region` should be aligned with the data stored in `provider_uri`. Currently, ``scripts/get_data.py`` only provides China stock market data. If users want to use the US stock market data, they should prepare their own US-stock data in `provider_uri` and switch to US-stock mode.
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
If Qlib fails to connect redis via `redis_host` and `redis_port`, cache mechanism will not be used! Please refer to `Cache <../component/data.html#cache>`_ for details.
|
If Qlib fails to connect redis via `redis_host` and `redis_port`, cache mechanism will not be used! Please refer to `Cache <../component/data.html#cache>`_ for details.
|
||||||
- `exp_manager`
|
- `exp_manager`
|
||||||
Type: dict, optional parameter, the setting of `experiment manager` to be used in qlib. Users can specify an experiment manager class, as well as the tracking URI for all the experiments. However, please be aware that we only support input of a dictionary in the following style for `exp_manager`. For more information about `exp_manager`, users can refer to `Recorder: Experiment Management <../component/recorder.html>`_.
|
Type: dict, optional parameter, the setting of `experiment manager` to be used in qlib. Users can specify an experiment manager class, as well as the tracking URI for all the experiments. However, please be aware that we only support input of a dictionary in the following style for `exp_manager`. For more information about `exp_manager`, users can refer to `Recorder: Experiment Management <../component/recorder.html>`_.
|
||||||
|
|
||||||
.. code-block:: Python
|
.. code-block:: Python
|
||||||
|
|
||||||
# For example, if you want to set your tracking_uri to a <specific folder>, you can initialize qlib below
|
# For example, if you want to set your tracking_uri to a <specific folder>, you can initialize qlib below
|
||||||
@@ -78,7 +78,7 @@ The following are several important parameters of `qlib.init` (`Qlib` has a lot
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
- `mongo`
|
- `mongo`
|
||||||
Type: dict, optional parameter, the setting of `MongoDB <https://www.mongodb.com/>`_ which will be used in some features such as `Task Management <../advanced/task_management.html>`_, with high performance and clustered processing.
|
Type: dict, optional parameter, the setting of `MongoDB <https://www.mongodb.com/>`_ which will be used in some features such as `Task Management <../advanced/task_management.html>`_, with high performance and clustered processing.
|
||||||
Users need to follow the steps in `installation <https://www.mongodb.com/try/download/community>`_ to install MongoDB firstly and then access it via a URI.
|
Users need to follow the steps in `installation <https://www.mongodb.com/try/download/community>`_ to install MongoDB firstly and then access it via a URI.
|
||||||
Users can access mongodb with credential by setting "task_url" to a string like `"mongodb://%s:%s@%s" % (user, pwd, host + ":" + port)`.
|
Users can access mongodb with credential by setting "task_url" to a string like `"mongodb://%s:%s@%s" % (user, pwd, host + ":" + port)`.
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
.. _installation:
|
.. _installation:
|
||||||
|
|
||||||
====================
|
============
|
||||||
Installation
|
Installation
|
||||||
====================
|
============
|
||||||
|
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ Also, Users can install ``Qlib`` by the source code according to the following s
|
|||||||
|
|
||||||
- Enter the root directory of ``Qlib``, in which the file ``setup.py`` exists.
|
- Enter the root directory of ``Qlib``, in which the file ``setup.py`` exists.
|
||||||
- Then, please execute the following command to install the environment dependencies and install ``Qlib``:
|
- Then, please execute the following command to install the environment dependencies and install ``Qlib``:
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
$ pip install numpy
|
$ pip install numpy
|
||||||
@@ -34,7 +34,7 @@ Also, Users can install ``Qlib`` by the source code according to the following s
|
|||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
It's recommended to use anaconda/miniconda to setup the environment. ``Qlib`` needs lightgbm and pytorch packages, use pip to install them.
|
It's recommended to use anaconda/miniconda to setup the environment. ``Qlib`` needs lightgbm and pytorch packages, use pip to install them.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Use the following code to make sure the installation successful:
|
Use the following code to make sure the installation successful:
|
||||||
@@ -44,6 +44,3 @@ Use the following code to make sure the installation successful:
|
|||||||
>>> import qlib
|
>>> import qlib
|
||||||
>>> qlib.__version__
|
>>> qlib.__version__
|
||||||
<LATEST VERSION>
|
<LATEST VERSION>
|
||||||
|
|
||||||
|
|
||||||
=====================
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
=========================================
|
========================
|
||||||
Custom Model Integration
|
Custom Model Integration
|
||||||
=========================================
|
========================
|
||||||
|
|
||||||
Introduction
|
Introduction
|
||||||
===================
|
============
|
||||||
|
|
||||||
``Qlib``'s `Model Zoo` includes models such as ``LightGBM``, ``MLP``, ``LSTM``, etc.. These models are examples of ``Forecast Model``. In addition to the default models ``Qlib`` provide, users can integrate their own custom models into ``Qlib``.
|
``Qlib``'s `Model Zoo` includes models such as ``LightGBM``, ``MLP``, ``LSTM``, etc.. These models are examples of ``Forecast Model``. In addition to the default models ``Qlib`` provide, users can integrate their own custom models into ``Qlib``.
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ Users can integrate their own custom models according to the following steps.
|
|||||||
- Test the custom model.
|
- Test the custom model.
|
||||||
|
|
||||||
Custom Model Class
|
Custom Model Class
|
||||||
===========================
|
==================
|
||||||
The Custom models need to inherit `qlib.model.base.Model <../reference/api.html#module-qlib.model.base>`_ and override the methods in it.
|
The Custom models need to inherit `qlib.model.base.Model <../reference/api.html#module-qlib.model.base>`_ and override the methods in it.
|
||||||
|
|
||||||
- Override the `__init__` method
|
- Override the `__init__` method
|
||||||
@@ -36,7 +36,7 @@ The Custom models need to inherit `qlib.model.base.Model <../reference/api.html#
|
|||||||
- The parameters could include some `optional` parameters with default values, such as `num_boost_round = 1000` for `GBDT`.
|
- The parameters could include some `optional` parameters with default values, such as `num_boost_round = 1000` for `GBDT`.
|
||||||
- Code Example: In the following example, `num_boost_round = 1000` is an optional parameter.
|
- Code Example: In the following example, `num_boost_round = 1000` is an optional parameter.
|
||||||
.. code-block:: Python
|
.. code-block:: Python
|
||||||
|
|
||||||
def fit(self, dataset: DatasetH, num_boost_round = 1000, **kwargs):
|
def fit(self, dataset: DatasetH, num_boost_round = 1000, **kwargs):
|
||||||
|
|
||||||
# prepare dataset for lgb training and evaluation
|
# prepare dataset for lgb training and evaluation
|
||||||
@@ -101,14 +101,14 @@ The Custom models need to inherit `qlib.model.base.Model <../reference/api.html#
|
|||||||
)
|
)
|
||||||
|
|
||||||
Configuration File
|
Configuration File
|
||||||
=======================
|
==================
|
||||||
|
|
||||||
The configuration file is described in detail in the `Workflow <../component/workflow.html#complete-example>`_ document. In order to integrate the custom model into ``Qlib``, users need to modify the "model" field in the configuration file. The configuration describes which models to use and how we can initialize it.
|
The configuration file is described in detail in the `Workflow <../component/workflow.html#complete-example>`_ document. In order to integrate the custom model into ``Qlib``, users need to modify the "model" field in the configuration file. The configuration describes which models to use and how we can initialize it.
|
||||||
|
|
||||||
- Example: The following example describes the `model` field of configuration file about the custom lightgbm model mentioned above, where `module_path` is the module path, `class` is the class name, and `args` is the hyperparameter passed into the __init__ method. All parameters in the field is passed to `self._params` by `\*\*kwargs` in `__init__` except `loss = mse`.
|
- Example: The following example describes the `model` field of configuration file about the custom lightgbm model mentioned above, where `module_path` is the module path, `class` is the class name, and `args` is the hyperparameter passed into the __init__ method. All parameters in the field is passed to `self._params` by `\*\*kwargs` in `__init__` except `loss = mse`.
|
||||||
|
|
||||||
.. code-block:: YAML
|
.. code-block:: YAML
|
||||||
|
|
||||||
model:
|
model:
|
||||||
class: LGBModel
|
class: LGBModel
|
||||||
module_path: qlib.contrib.model.gbdt
|
module_path: qlib.contrib.model.gbdt
|
||||||
@@ -126,7 +126,7 @@ The configuration file is described in detail in the `Workflow <../component/wor
|
|||||||
Users could find configuration file of the baselines of the ``Model`` in ``examples/benchmarks``. All the configurations of different models are listed under the corresponding model folder.
|
Users could find configuration file of the baselines of the ``Model`` in ``examples/benchmarks``. All the configurations of different models are listed under the corresponding model folder.
|
||||||
|
|
||||||
Model Testing
|
Model Testing
|
||||||
=====================
|
=============
|
||||||
Assuming that the configuration file is ``examples/benchmarks/LightGBM/workflow_config_lightgbm.yaml``, users can run the following command to test the custom model:
|
Assuming that the configuration file is ``examples/benchmarks/LightGBM/workflow_config_lightgbm.yaml``, users can run the following command to test the custom model:
|
||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
@@ -136,10 +136,10 @@ Assuming that the configuration file is ``examples/benchmarks/LightGBM/workflow_
|
|||||||
|
|
||||||
.. note:: ``qrun`` is a built-in command of ``Qlib``.
|
.. note:: ``qrun`` is a built-in command of ``Qlib``.
|
||||||
|
|
||||||
Also, ``Model`` can also be tested as a single module. An example has been given in ``examples/workflow_by_code.ipynb``.
|
Also, ``Model`` can also be tested as a single module. An example has been given in ``examples/workflow_by_code.ipynb``.
|
||||||
|
|
||||||
|
|
||||||
Reference
|
Reference
|
||||||
=====================
|
=========
|
||||||
|
|
||||||
To know more about ``Forecast Model``, please refer to `Forecast Model: Model Training & Prediction <../component/model.html>`_ and `Model API <../reference/api.html#module-qlib.model.base>`_.
|
To know more about ``Forecast Model``, please refer to `Forecast Model: Model Training & Prediction <../component/model.html>`_ and `Model API <../reference/api.html#module-qlib.model.base>`_.
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
qlib_init:
|
||||||
|
provider_uri: "~/.qlib/qlib_data/cn_data"
|
||||||
|
region: cn
|
||||||
|
market: &market csi500
|
||||||
|
benchmark: &benchmark SH000905
|
||||||
|
data_handler_config: &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: *market
|
||||||
|
port_analysis_config: &port_analysis_config
|
||||||
|
strategy:
|
||||||
|
class: TopkDropoutStrategy
|
||||||
|
module_path: qlib.contrib.strategy
|
||||||
|
kwargs:
|
||||||
|
signal:
|
||||||
|
- <MODEL>
|
||||||
|
- <DATASET>
|
||||||
|
topk: 50
|
||||||
|
n_drop: 5
|
||||||
|
backtest:
|
||||||
|
start_time: 2017-01-01
|
||||||
|
end_time: 2020-08-01
|
||||||
|
account: 100000000
|
||||||
|
benchmark: *benchmark
|
||||||
|
exchange_kwargs:
|
||||||
|
limit_threshold: 0.095
|
||||||
|
deal_price: close
|
||||||
|
open_cost: 0.0005
|
||||||
|
close_cost: 0.0015
|
||||||
|
min_cost: 5
|
||||||
|
task:
|
||||||
|
model:
|
||||||
|
class: CatBoostModel
|
||||||
|
module_path: qlib.contrib.model.catboost_model
|
||||||
|
kwargs:
|
||||||
|
loss: RMSE
|
||||||
|
learning_rate: 0.0421
|
||||||
|
subsample: 0.8789
|
||||||
|
max_depth: 6
|
||||||
|
num_leaves: 100
|
||||||
|
thread_count: 20
|
||||||
|
grow_policy: Lossguide
|
||||||
|
bootstrap_type: Poisson
|
||||||
|
dataset:
|
||||||
|
class: DatasetH
|
||||||
|
module_path: qlib.data.dataset
|
||||||
|
kwargs:
|
||||||
|
handler:
|
||||||
|
class: Alpha158
|
||||||
|
module_path: qlib.contrib.data.handler
|
||||||
|
kwargs: *data_handler_config
|
||||||
|
segments:
|
||||||
|
train: [2008-01-01, 2014-12-31]
|
||||||
|
valid: [2015-01-01, 2016-12-31]
|
||||||
|
test: [2017-01-01, 2020-08-01]
|
||||||
|
record:
|
||||||
|
- class: SignalRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
model: <MODEL>
|
||||||
|
dataset: <DATASET>
|
||||||
|
- class: SigAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
ana_long_short: False
|
||||||
|
ann_scaler: 252
|
||||||
|
- class: PortAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
config: *port_analysis_config
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
qlib_init:
|
||||||
|
provider_uri: "~/.qlib/qlib_data/cn_data"
|
||||||
|
region: cn
|
||||||
|
market: &market csi500
|
||||||
|
benchmark: &benchmark SH000905
|
||||||
|
data_handler_config: &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: *market
|
||||||
|
infer_processors: []
|
||||||
|
learn_processors:
|
||||||
|
- class: DropnaLabel
|
||||||
|
- class: CSRankNorm
|
||||||
|
kwargs:
|
||||||
|
fields_group: label
|
||||||
|
label: ["Ref($close, -2) / Ref($close, -1) - 1"]
|
||||||
|
port_analysis_config: &port_analysis_config
|
||||||
|
strategy:
|
||||||
|
class: TopkDropoutStrategy
|
||||||
|
module_path: qlib.contrib.strategy
|
||||||
|
kwargs:
|
||||||
|
signal:
|
||||||
|
- <MODEL>
|
||||||
|
- <DATASET>
|
||||||
|
topk: 50
|
||||||
|
n_drop: 5
|
||||||
|
backtest:
|
||||||
|
start_time: 2017-01-01
|
||||||
|
end_time: 2020-08-01
|
||||||
|
account: 100000000
|
||||||
|
benchmark: *benchmark
|
||||||
|
exchange_kwargs:
|
||||||
|
limit_threshold: 0.095
|
||||||
|
deal_price: close
|
||||||
|
open_cost: 0.0005
|
||||||
|
close_cost: 0.0015
|
||||||
|
min_cost: 5
|
||||||
|
task:
|
||||||
|
model:
|
||||||
|
class: CatBoostModel
|
||||||
|
module_path: qlib.contrib.model.catboost_model
|
||||||
|
kwargs:
|
||||||
|
loss: RMSE
|
||||||
|
learning_rate: 0.0421
|
||||||
|
subsample: 0.8789
|
||||||
|
max_depth: 6
|
||||||
|
num_leaves: 100
|
||||||
|
thread_count: 20
|
||||||
|
grow_policy: Lossguide
|
||||||
|
bootstrap_type: Poisson
|
||||||
|
dataset:
|
||||||
|
class: DatasetH
|
||||||
|
module_path: qlib.data.dataset
|
||||||
|
kwargs:
|
||||||
|
handler:
|
||||||
|
class: Alpha360
|
||||||
|
module_path: qlib.contrib.data.handler
|
||||||
|
kwargs: *data_handler_config
|
||||||
|
segments:
|
||||||
|
train: [2008-01-01, 2014-12-31]
|
||||||
|
valid: [2015-01-01, 2016-12-31]
|
||||||
|
test: [2017-01-01, 2020-08-01]
|
||||||
|
record:
|
||||||
|
- class: SignalRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
model: <MODEL>
|
||||||
|
dataset: <DATASET>
|
||||||
|
- class: SigAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
ana_long_short: False
|
||||||
|
ann_scaler: 252
|
||||||
|
- class: PortAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
config: *port_analysis_config
|
||||||
@@ -37,7 +37,7 @@ task:
|
|||||||
kwargs:
|
kwargs:
|
||||||
base_model: "gbm"
|
base_model: "gbm"
|
||||||
loss: mse
|
loss: mse
|
||||||
num_models: 6
|
num_models: 3
|
||||||
enable_sr: True
|
enable_sr: True
|
||||||
enable_fs: True
|
enable_fs: True
|
||||||
alpha1: 1
|
alpha1: 1
|
||||||
@@ -53,11 +53,8 @@ task:
|
|||||||
- 0.4
|
- 0.4
|
||||||
sub_weights:
|
sub_weights:
|
||||||
- 1
|
- 1
|
||||||
- 0.2
|
- 1
|
||||||
- 0.2
|
- 1
|
||||||
- 0.2
|
|
||||||
- 0.2
|
|
||||||
- 0.2
|
|
||||||
epochs: 28
|
epochs: 28
|
||||||
colsample_bytree: 0.8879
|
colsample_bytree: 0.8879
|
||||||
learning_rate: 0.2
|
learning_rate: 0.2
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
qlib_init:
|
||||||
|
provider_uri: "~/.qlib/qlib_data/cn_data"
|
||||||
|
region: cn
|
||||||
|
market: &market csi500
|
||||||
|
benchmark: &benchmark SH000905
|
||||||
|
data_handler_config: &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: *market
|
||||||
|
port_analysis_config: &port_analysis_config
|
||||||
|
strategy:
|
||||||
|
class: TopkDropoutStrategy
|
||||||
|
module_path: qlib.contrib.strategy
|
||||||
|
kwargs:
|
||||||
|
signal:
|
||||||
|
- <MODEL>
|
||||||
|
- <DATASET>
|
||||||
|
topk: 50
|
||||||
|
n_drop: 5
|
||||||
|
backtest:
|
||||||
|
start_time: 2017-01-01
|
||||||
|
end_time: 2020-08-01
|
||||||
|
account: 100000000
|
||||||
|
benchmark: *benchmark
|
||||||
|
exchange_kwargs:
|
||||||
|
limit_threshold: 0.095
|
||||||
|
deal_price: close
|
||||||
|
open_cost: 0.0005
|
||||||
|
close_cost: 0.0015
|
||||||
|
min_cost: 5
|
||||||
|
task:
|
||||||
|
model:
|
||||||
|
class: DEnsembleModel
|
||||||
|
module_path: qlib.contrib.model.double_ensemble
|
||||||
|
kwargs:
|
||||||
|
base_model: "gbm"
|
||||||
|
loss: mse
|
||||||
|
num_models: 6
|
||||||
|
enable_sr: True
|
||||||
|
enable_fs: True
|
||||||
|
alpha1: 1
|
||||||
|
alpha2: 1
|
||||||
|
bins_sr: 10
|
||||||
|
bins_fs: 5
|
||||||
|
decay: 0.5
|
||||||
|
sample_ratios:
|
||||||
|
- 0.8
|
||||||
|
- 0.7
|
||||||
|
- 0.6
|
||||||
|
- 0.5
|
||||||
|
- 0.4
|
||||||
|
sub_weights:
|
||||||
|
- 1
|
||||||
|
- 0.2
|
||||||
|
- 0.2
|
||||||
|
- 0.2
|
||||||
|
- 0.2
|
||||||
|
- 0.2
|
||||||
|
epochs: 28
|
||||||
|
colsample_bytree: 0.8879
|
||||||
|
learning_rate: 0.2
|
||||||
|
subsample: 0.8789
|
||||||
|
lambda_l1: 205.6999
|
||||||
|
lambda_l2: 580.9768
|
||||||
|
max_depth: 8
|
||||||
|
num_leaves: 210
|
||||||
|
num_threads: 20
|
||||||
|
verbosity: -1
|
||||||
|
dataset:
|
||||||
|
class: DatasetH
|
||||||
|
module_path: qlib.data.dataset
|
||||||
|
kwargs:
|
||||||
|
handler:
|
||||||
|
class: Alpha158
|
||||||
|
module_path: qlib.contrib.data.handler
|
||||||
|
kwargs: *data_handler_config
|
||||||
|
segments:
|
||||||
|
train: [2008-01-01, 2014-12-31]
|
||||||
|
valid: [2015-01-01, 2016-12-31]
|
||||||
|
test: [2017-01-01, 2020-08-01]
|
||||||
|
record:
|
||||||
|
- class: SignalRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
model: <MODEL>
|
||||||
|
dataset: <DATASET>
|
||||||
|
- class: SigAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
ana_long_short: False
|
||||||
|
ann_scaler: 252
|
||||||
|
- class: PortAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
config: *port_analysis_config
|
||||||
@@ -44,7 +44,7 @@ task:
|
|||||||
kwargs:
|
kwargs:
|
||||||
base_model: "gbm"
|
base_model: "gbm"
|
||||||
loss: mse
|
loss: mse
|
||||||
num_models: 6
|
num_models: 3
|
||||||
enable_sr: True
|
enable_sr: True
|
||||||
enable_fs: True
|
enable_fs: True
|
||||||
alpha1: 1
|
alpha1: 1
|
||||||
@@ -60,11 +60,8 @@ task:
|
|||||||
- 0.4
|
- 0.4
|
||||||
sub_weights:
|
sub_weights:
|
||||||
- 1
|
- 1
|
||||||
- 0.2
|
- 1
|
||||||
- 0.2
|
- 1
|
||||||
- 0.2
|
|
||||||
- 0.2
|
|
||||||
- 0.2
|
|
||||||
epochs: 136
|
epochs: 136
|
||||||
colsample_bytree: 0.8879
|
colsample_bytree: 0.8879
|
||||||
learning_rate: 0.0421
|
learning_rate: 0.0421
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
qlib_init:
|
||||||
|
provider_uri: "~/.qlib/qlib_data/cn_data"
|
||||||
|
region: cn
|
||||||
|
market: &market csi500
|
||||||
|
benchmark: &benchmark SH000905
|
||||||
|
data_handler_config: &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: *market
|
||||||
|
infer_processors: []
|
||||||
|
learn_processors:
|
||||||
|
- class: DropnaLabel
|
||||||
|
- class: CSRankNorm
|
||||||
|
kwargs:
|
||||||
|
fields_group: label
|
||||||
|
label: ["Ref($close, -2) / Ref($close, -1) - 1"]
|
||||||
|
port_analysis_config: &port_analysis_config
|
||||||
|
strategy:
|
||||||
|
class: TopkDropoutStrategy
|
||||||
|
module_path: qlib.contrib.strategy
|
||||||
|
kwargs:
|
||||||
|
signal:
|
||||||
|
- <MODEL>
|
||||||
|
- <DATASET>
|
||||||
|
topk: 50
|
||||||
|
n_drop: 5
|
||||||
|
backtest:
|
||||||
|
start_time: 2017-01-01
|
||||||
|
end_time: 2020-08-01
|
||||||
|
account: 100000000
|
||||||
|
benchmark: *benchmark
|
||||||
|
exchange_kwargs:
|
||||||
|
limit_threshold: 0.095
|
||||||
|
deal_price: close
|
||||||
|
open_cost: 0.0005
|
||||||
|
close_cost: 0.0015
|
||||||
|
min_cost: 5
|
||||||
|
task:
|
||||||
|
model:
|
||||||
|
class: DEnsembleModel
|
||||||
|
module_path: qlib.contrib.model.double_ensemble
|
||||||
|
kwargs:
|
||||||
|
base_model: "gbm"
|
||||||
|
loss: mse
|
||||||
|
num_models: 6
|
||||||
|
enable_sr: True
|
||||||
|
enable_fs: True
|
||||||
|
alpha1: 1
|
||||||
|
alpha2: 1
|
||||||
|
bins_sr: 10
|
||||||
|
bins_fs: 5
|
||||||
|
decay: 0.5
|
||||||
|
sample_ratios:
|
||||||
|
- 0.8
|
||||||
|
- 0.7
|
||||||
|
- 0.6
|
||||||
|
- 0.5
|
||||||
|
- 0.4
|
||||||
|
sub_weights:
|
||||||
|
- 1
|
||||||
|
- 0.2
|
||||||
|
- 0.2
|
||||||
|
- 0.2
|
||||||
|
- 0.2
|
||||||
|
- 0.2
|
||||||
|
epochs: 136
|
||||||
|
colsample_bytree: 0.8879
|
||||||
|
learning_rate: 0.0421
|
||||||
|
subsample: 0.8789
|
||||||
|
lambda_l1: 205.6999
|
||||||
|
lambda_l2: 580.9768
|
||||||
|
max_depth: 8
|
||||||
|
num_leaves: 210
|
||||||
|
num_threads: 20
|
||||||
|
verbosity: -1
|
||||||
|
dataset:
|
||||||
|
class: DatasetH
|
||||||
|
module_path: qlib.data.dataset
|
||||||
|
kwargs:
|
||||||
|
handler:
|
||||||
|
class: Alpha360
|
||||||
|
module_path: qlib.contrib.data.handler
|
||||||
|
kwargs: *data_handler_config
|
||||||
|
segments:
|
||||||
|
train: [2008-01-01, 2014-12-31]
|
||||||
|
valid: [2015-01-01, 2016-12-31]
|
||||||
|
test: [2017-01-01, 2020-08-01]
|
||||||
|
record:
|
||||||
|
- class: SignalRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
model: <MODEL>
|
||||||
|
dataset: <DATASET>
|
||||||
|
- class: SigAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
ana_long_short: False
|
||||||
|
ann_scaler: 252
|
||||||
|
- class: PortAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
config: *port_analysis_config
|
||||||
@@ -1,4 +1,10 @@
|
|||||||
# LightGBM
|
# LightGBM
|
||||||
* Code: [https://github.com/microsoft/LightGBM](https://github.com/microsoft/LightGBM)
|
* Code: [https://github.com/microsoft/LightGBM](https://github.com/microsoft/LightGBM)
|
||||||
* Paper: LightGBM: A Highly Efficient Gradient Boosting
|
* Paper: LightGBM: A Highly Efficient Gradient Boosting
|
||||||
Decision Tree. [https://proceedings.neurips.cc/paper/2017/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf](https://proceedings.neurips.cc/paper/2017/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf).
|
Decision Tree. [https://proceedings.neurips.cc/paper/2017/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf](https://proceedings.neurips.cc/paper/2017/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf).
|
||||||
|
|
||||||
|
|
||||||
|
# Introductions about the settings/configs.
|
||||||
|
|
||||||
|
`workflow_config_lightgbm_multi_freq.yaml`
|
||||||
|
- It uses data sources of different frequencies (i.e. multiple frequencies) for daily prediction.
|
||||||
|
|||||||
@@ -35,13 +35,13 @@ task:
|
|||||||
module_path: qlib.contrib.model.gbdt
|
module_path: qlib.contrib.model.gbdt
|
||||||
kwargs:
|
kwargs:
|
||||||
loss: mse
|
loss: mse
|
||||||
colsample_bytree: 0.8879
|
colsample_bytree: 0.9
|
||||||
learning_rate: 0.2
|
learning_rate: 0.1
|
||||||
subsample: 0.8789
|
subsample: 0.9
|
||||||
lambda_l1: 205.6999
|
lambda_l1: 205.6999
|
||||||
lambda_l2: 580.9768
|
lambda_l2: 580.9768
|
||||||
max_depth: 8
|
max_depth: 8
|
||||||
num_leaves: 210
|
num_leaves: 250
|
||||||
num_threads: 20
|
num_threads: 20
|
||||||
dataset:
|
dataset:
|
||||||
class: DatasetH
|
class: DatasetH
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
qlib_init:
|
||||||
|
provider_uri: "~/.qlib/qlib_data/cn_data"
|
||||||
|
region: cn
|
||||||
|
market: &market csi500
|
||||||
|
benchmark: &benchmark SH000905
|
||||||
|
data_handler_config: &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: *market
|
||||||
|
infer_processors:
|
||||||
|
- class: RobustZScoreNorm
|
||||||
|
kwargs:
|
||||||
|
fields_group: feature
|
||||||
|
clip_outlier: true
|
||||||
|
- class: Fillna
|
||||||
|
kwargs:
|
||||||
|
fields_group: feature
|
||||||
|
learn_processors:
|
||||||
|
- class: DropnaLabel
|
||||||
|
- class: CSRankNorm
|
||||||
|
kwargs:
|
||||||
|
fields_group: label
|
||||||
|
port_analysis_config: &port_analysis_config
|
||||||
|
strategy:
|
||||||
|
class: TopkDropoutStrategy
|
||||||
|
module_path: qlib.contrib.strategy
|
||||||
|
kwargs:
|
||||||
|
signal:
|
||||||
|
- <MODEL>
|
||||||
|
- <DATASET>
|
||||||
|
topk: 50
|
||||||
|
n_drop: 5
|
||||||
|
backtest:
|
||||||
|
start_time: 2017-01-01
|
||||||
|
end_time: 2020-08-01
|
||||||
|
account: 100000000
|
||||||
|
benchmark: *benchmark
|
||||||
|
exchange_kwargs:
|
||||||
|
limit_threshold: 0.095
|
||||||
|
deal_price: close
|
||||||
|
open_cost: 0.0005
|
||||||
|
close_cost: 0.0015
|
||||||
|
min_cost: 5
|
||||||
|
task:
|
||||||
|
model:
|
||||||
|
class: LinearModel
|
||||||
|
module_path: qlib.contrib.model.linear
|
||||||
|
kwargs:
|
||||||
|
estimator: ols
|
||||||
|
dataset:
|
||||||
|
class: DatasetH
|
||||||
|
module_path: qlib.data.dataset
|
||||||
|
kwargs:
|
||||||
|
handler:
|
||||||
|
class: Alpha158
|
||||||
|
module_path: qlib.contrib.data.handler
|
||||||
|
kwargs: *data_handler_config
|
||||||
|
segments:
|
||||||
|
train: [2008-01-01, 2014-12-31]
|
||||||
|
valid: [2015-01-01, 2016-12-31]
|
||||||
|
test: [2017-01-01, 2020-08-01]
|
||||||
|
record:
|
||||||
|
- class: SignalRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
model: <MODEL>
|
||||||
|
dataset: <DATASET>
|
||||||
|
- class: SigAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
ana_long_short: True
|
||||||
|
ann_scaler: 252
|
||||||
|
- class: PortAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
config: *port_analysis_config
|
||||||
102
examples/benchmarks/MLP/workflow_config_mlp_Alpha158_csi500.yaml
Normal file
102
examples/benchmarks/MLP/workflow_config_mlp_Alpha158_csi500.yaml
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
qlib_init:
|
||||||
|
provider_uri: "~/.qlib/qlib_data/cn_data"
|
||||||
|
region: cn
|
||||||
|
market: &market csi500
|
||||||
|
benchmark: &benchmark SH000905
|
||||||
|
data_handler_config: &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: *market
|
||||||
|
infer_processors: [
|
||||||
|
{
|
||||||
|
"class" : "DropCol",
|
||||||
|
"kwargs":{"col_list": ["VWAP0"]}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"class" : "CSZFillna",
|
||||||
|
"kwargs":{"fields_group": "feature"}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
learn_processors: [
|
||||||
|
{
|
||||||
|
"class" : "DropCol",
|
||||||
|
"kwargs":{"col_list": ["VWAP0"]}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"class" : "DropnaProcessor",
|
||||||
|
"kwargs":{"fields_group": "feature"}
|
||||||
|
},
|
||||||
|
"DropnaLabel",
|
||||||
|
{
|
||||||
|
"class": "CSZScoreNorm",
|
||||||
|
"kwargs": {"fields_group": "label"}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
process_type: "independent"
|
||||||
|
|
||||||
|
port_analysis_config: &port_analysis_config
|
||||||
|
strategy:
|
||||||
|
class: TopkDropoutStrategy
|
||||||
|
module_path: qlib.contrib.strategy
|
||||||
|
kwargs:
|
||||||
|
signal:
|
||||||
|
- <MODEL>
|
||||||
|
- <DATASET>
|
||||||
|
topk: 50
|
||||||
|
n_drop: 5
|
||||||
|
backtest:
|
||||||
|
start_time: 2017-01-01
|
||||||
|
end_time: 2020-08-01
|
||||||
|
account: 100000000
|
||||||
|
benchmark: *benchmark
|
||||||
|
exchange_kwargs:
|
||||||
|
limit_threshold: 0.095
|
||||||
|
deal_price: close
|
||||||
|
open_cost: 0.0005
|
||||||
|
close_cost: 0.0015
|
||||||
|
min_cost: 5
|
||||||
|
task:
|
||||||
|
model:
|
||||||
|
class: DNNModelPytorch
|
||||||
|
module_path: qlib.contrib.model.pytorch_nn
|
||||||
|
kwargs:
|
||||||
|
loss: mse
|
||||||
|
lr: 0.002
|
||||||
|
lr_decay: 0.96
|
||||||
|
lr_decay_steps: 100
|
||||||
|
optimizer: adam
|
||||||
|
max_steps: 8000
|
||||||
|
batch_size: 8192
|
||||||
|
GPU: 0
|
||||||
|
weight_decay: 0.0002
|
||||||
|
pt_model_kwargs:
|
||||||
|
input_dim: 157
|
||||||
|
dataset:
|
||||||
|
class: DatasetH
|
||||||
|
module_path: qlib.data.dataset
|
||||||
|
kwargs:
|
||||||
|
handler:
|
||||||
|
class: Alpha158
|
||||||
|
module_path: qlib.contrib.data.handler
|
||||||
|
kwargs: *data_handler_config
|
||||||
|
segments:
|
||||||
|
train: [2008-01-01, 2014-12-31]
|
||||||
|
valid: [2015-01-01, 2016-12-31]
|
||||||
|
test: [2017-01-01, 2020-08-01]
|
||||||
|
record:
|
||||||
|
- class: SignalRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
model: <MODEL>
|
||||||
|
dataset: <DATASET>
|
||||||
|
- class: SigAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
ana_long_short: False
|
||||||
|
ann_scaler: 252
|
||||||
|
- class: PortAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
config: *port_analysis_config
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
qlib_init:
|
||||||
|
provider_uri: "~/.qlib/qlib_data/cn_data"
|
||||||
|
region: cn
|
||||||
|
market: &market csi500
|
||||||
|
benchmark: &benchmark SH000905
|
||||||
|
data_handler_config: &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: *market
|
||||||
|
infer_processors:
|
||||||
|
- class: RobustZScoreNorm
|
||||||
|
kwargs:
|
||||||
|
fields_group: feature
|
||||||
|
clip_outlier: true
|
||||||
|
- class: Fillna
|
||||||
|
kwargs:
|
||||||
|
fields_group: feature
|
||||||
|
learn_processors:
|
||||||
|
- class: DropnaLabel
|
||||||
|
- class: CSRankNorm
|
||||||
|
kwargs:
|
||||||
|
fields_group: label
|
||||||
|
label: ["Ref($close, -2) / Ref($close, -1) - 1"]
|
||||||
|
|
||||||
|
port_analysis_config: &port_analysis_config
|
||||||
|
strategy:
|
||||||
|
class: TopkDropoutStrategy
|
||||||
|
module_path: qlib.contrib.strategy
|
||||||
|
kwargs:
|
||||||
|
signal:
|
||||||
|
- <MODEL>
|
||||||
|
- <DATASET>
|
||||||
|
topk: 50
|
||||||
|
n_drop: 5
|
||||||
|
backtest:
|
||||||
|
start_time: 2017-01-01
|
||||||
|
end_time: 2020-08-01
|
||||||
|
account: 100000000
|
||||||
|
benchmark: *benchmark
|
||||||
|
exchange_kwargs:
|
||||||
|
limit_threshold: 0.095
|
||||||
|
deal_price: close
|
||||||
|
open_cost: 0.0005
|
||||||
|
close_cost: 0.0015
|
||||||
|
min_cost: 5
|
||||||
|
task:
|
||||||
|
model:
|
||||||
|
class: DNNModelPytorch
|
||||||
|
module_path: qlib.contrib.model.pytorch_nn
|
||||||
|
kwargs:
|
||||||
|
loss: mse
|
||||||
|
lr: 0.002
|
||||||
|
lr_decay: 0.96
|
||||||
|
lr_decay_steps: 100
|
||||||
|
optimizer: adam
|
||||||
|
max_steps: 8000
|
||||||
|
batch_size: 4096
|
||||||
|
GPU: 0
|
||||||
|
pt_model_kwargs:
|
||||||
|
input_dim: 360
|
||||||
|
dataset:
|
||||||
|
class: DatasetH
|
||||||
|
module_path: qlib.data.dataset
|
||||||
|
kwargs:
|
||||||
|
handler:
|
||||||
|
class: Alpha360
|
||||||
|
module_path: qlib.contrib.data.handler
|
||||||
|
kwargs: *data_handler_config
|
||||||
|
segments:
|
||||||
|
train: [2008-01-01, 2014-12-31]
|
||||||
|
valid: [2015-01-01, 2016-12-31]
|
||||||
|
test: [2017-01-01, 2020-08-01]
|
||||||
|
record:
|
||||||
|
- class: SignalRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
model: <MODEL>
|
||||||
|
dataset: <DATASET>
|
||||||
|
- class: SigAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
ana_long_short: False
|
||||||
|
ann_scaler: 252
|
||||||
|
- class: PortAnaRecord
|
||||||
|
module_path: qlib.workflow.record_temp
|
||||||
|
kwargs:
|
||||||
|
config: *port_analysis_config
|
||||||
@@ -43,8 +43,7 @@ The numbers shown below demonstrate the performance of the entire `workflow` of
|
|||||||
| TFT (Bryan Lim, et al.) | Alpha158(with selected 20 features) | 0.0358±0.00 | 0.2160±0.03 | 0.0116±0.01 | 0.0720±0.03 | 0.0847±0.02 | 0.8131±0.19 | -0.1824±0.03 |
|
| TFT (Bryan Lim, et al.) | Alpha158(with selected 20 features) | 0.0358±0.00 | 0.2160±0.03 | 0.0116±0.01 | 0.0720±0.03 | 0.0847±0.02 | 0.8131±0.19 | -0.1824±0.03 |
|
||||||
| MLP | Alpha158 | 0.0376±0.00 | 0.2846±0.02 | 0.0429±0.00 | 0.3220±0.01 | 0.0895±0.02 | 1.1408±0.23 | -0.1103±0.02 |
|
| MLP | Alpha158 | 0.0376±0.00 | 0.2846±0.02 | 0.0429±0.00 | 0.3220±0.01 | 0.0895±0.02 | 1.1408±0.23 | -0.1103±0.02 |
|
||||||
| LightGBM(Guolin Ke, et al.) | Alpha158 | 0.0448±0.00 | 0.3660±0.00 | 0.0469±0.00 | 0.3877±0.00 | 0.0901±0.00 | 1.0164±0.00 | -0.1038±0.00 |
|
| LightGBM(Guolin Ke, et al.) | Alpha158 | 0.0448±0.00 | 0.3660±0.00 | 0.0469±0.00 | 0.3877±0.00 | 0.0901±0.00 | 1.0164±0.00 | -0.1038±0.00 |
|
||||||
| DoubleEnsemble(Chuheng Zhang, et al.) | Alpha158 | 0.0544±0.00 | 0.4340±0.00 | 0.0523±0.00 | 0.4284±0.01 | 0.1168±0.01 | 1.3384±0.12 | -0.1036±0.01 |
|
| DoubleEnsemble(Chuheng Zhang, et al.) | Alpha158 | 0.0521±0.00 | 0.4223±0.01 | 0.0502±0.00 | 0.4117±0.01 | 0.1158±0.01 | 1.3432±0.11 | -0.0920±0.01 |
|
||||||
|
|
||||||
|
|
||||||
### Alpha360 dataset
|
### Alpha360 dataset
|
||||||
|
|
||||||
@@ -56,7 +55,7 @@ The numbers shown below demonstrate the performance of the entire `workflow` of
|
|||||||
| Localformer(Juyong Jiang, et al.) | Alpha360 | 0.0404±0.00 | 0.2932±0.04 | 0.0542±0.00 | 0.4110±0.03 | 0.0246±0.02 | 0.3211±0.21 | -0.1095±0.02 |
|
| Localformer(Juyong Jiang, et al.) | Alpha360 | 0.0404±0.00 | 0.2932±0.04 | 0.0542±0.00 | 0.4110±0.03 | 0.0246±0.02 | 0.3211±0.21 | -0.1095±0.02 |
|
||||||
| CatBoost((Liudmila Prokhorenkova, et al.) | Alpha360 | 0.0378±0.00 | 0.2714±0.00 | 0.0467±0.00 | 0.3659±0.00 | 0.0292±0.00 | 0.3781±0.00 | -0.0862±0.00 |
|
| CatBoost((Liudmila Prokhorenkova, et al.) | Alpha360 | 0.0378±0.00 | 0.2714±0.00 | 0.0467±0.00 | 0.3659±0.00 | 0.0292±0.00 | 0.3781±0.00 | -0.0862±0.00 |
|
||||||
| XGBoost(Tianqi Chen, et al.) | Alpha360 | 0.0394±0.00 | 0.2909±0.00 | 0.0448±0.00 | 0.3679±0.00 | 0.0344±0.00 | 0.4527±0.02 | -0.1004±0.00 |
|
| XGBoost(Tianqi Chen, et al.) | Alpha360 | 0.0394±0.00 | 0.2909±0.00 | 0.0448±0.00 | 0.3679±0.00 | 0.0344±0.00 | 0.4527±0.02 | -0.1004±0.00 |
|
||||||
| DoubleEnsemble(Chuheng Zhang, et al.) | Alpha360 | 0.0404±0.00 | 0.3023±0.00 | 0.0495±0.00 | 0.3898±0.00 | 0.0468±0.01 | 0.6302±0.20 | -0.0860±0.01 |
|
| DoubleEnsemble(Chuheng Zhang, et al.) | Alpha360 | 0.0390±0.00 | 0.2946±0.01 | 0.0486±0.00 | 0.3836±0.01 | 0.0462±0.01 | 0.6151±0.18 | -0.0915±0.01 |
|
||||||
| LightGBM(Guolin Ke, et al.) | Alpha360 | 0.0400±0.00 | 0.3037±0.00 | 0.0499±0.00 | 0.4042±0.00 | 0.0558±0.00 | 0.7632±0.00 | -0.0659±0.00 |
|
| LightGBM(Guolin Ke, et al.) | Alpha360 | 0.0400±0.00 | 0.3037±0.00 | 0.0499±0.00 | 0.4042±0.00 | 0.0558±0.00 | 0.7632±0.00 | -0.0659±0.00 |
|
||||||
| TCN(Shaojie Bai, et al.) | Alpha360 | 0.0441±0.00 | 0.3301±0.02 | 0.0519±0.00 | 0.4130±0.01 | 0.0604±0.02 | 0.8295±0.34 | -0.1018±0.03 |
|
| TCN(Shaojie Bai, et al.) | Alpha360 | 0.0441±0.00 | 0.3301±0.02 | 0.0519±0.00 | 0.4130±0.01 | 0.0604±0.02 | 0.8295±0.34 | -0.1018±0.03 |
|
||||||
| ALSTM (Yao Qin, et al.) | Alpha360 | 0.0497±0.00 | 0.3829±0.04 | 0.0599±0.00 | 0.4736±0.03 | 0.0626±0.02 | 0.8651±0.31 | -0.0994±0.03 |
|
| ALSTM (Yao Qin, et al.) | Alpha360 | 0.0497±0.00 | 0.3829±0.04 | 0.0599±0.00 | 0.4736±0.03 | 0.0626±0.02 | 0.8651±0.31 | -0.0994±0.03 |
|
||||||
@@ -75,10 +74,15 @@ The numbers shown below demonstrate the performance of the entire `workflow` of
|
|||||||
- The base model of DoubleEnsemble is LGBM.
|
- The base model of DoubleEnsemble is LGBM.
|
||||||
- The base model of TCTS is GRU.
|
- The base model of TCTS is GRU.
|
||||||
- About the datasets
|
- About the datasets
|
||||||
- Alpha158 is a tabular dataset. There are less spatial relationships between different features. Each feature are carefully desgined by human (a.k.a feature engineering)
|
- Alpha158 is a tabular dataset. There are less spatial relationships between different features. Each feature are carefully designed by human (a.k.a feature engineering)
|
||||||
- Alpha360 contains raw price and volue data without much feature engineering. There are strong strong spatial relationships between the features in the time dimension.
|
- Alpha360 contains raw price and volue data without much feature engineering. There are strong strong spatial relationships between the features in the time dimension.
|
||||||
- The metrics can be categorized into two
|
- The metrics can be categorized into two
|
||||||
- Signal-based evaluation: IC, ICIR, Rank IC, Rank ICIR
|
- Signal-based evaluation: IC, ICIR, Rank IC, Rank ICIR
|
||||||
|
- 
|
||||||
|
- 
|
||||||
|
- 
|
||||||
|
- 
|
||||||
|
- 
|
||||||
- Portfolio-based metrics: Annualized Return, Information Ratio, Max Drawdown
|
- Portfolio-based metrics: Annualized Return, Information Ratio, Max Drawdown
|
||||||
|
|
||||||
## Results on CSI500
|
## Results on CSI500
|
||||||
@@ -103,16 +107,21 @@ python run_all_model.py run 3 lightgbm Alpha158 csi500 # for models with random
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Alpha158 dataset
|
### Alpha158 dataset
|
||||||
|
|
||||||
| Model Name | Dataset | IC | ICIR | Rank IC | Rank ICIR | Annualized Return | Information Ratio | Max Drawdown |
|
| Model Name | Dataset | IC | ICIR | Rank IC | Rank ICIR | Annualized Return | Information Ratio | Max Drawdown |
|
||||||
|------------|----------|-------------|-------------|-------------|-------------|-------------------|-------------------|--------------|
|
|------------|----------|-------------|-------------|-------------|-------------|-------------------|-------------------|--------------|
|
||||||
| LightGBM | Alpha158 | 0.0377±0.00 | 0.3860±0.00 | 0.0448±0.00 | 0.4675±0.00 | 0.1151±0.00 | 1.3884±0.00 | -0.0898±0.00 |
|
| Linear | Alpha158 | 0.0332±0.00 | 0.3044±0.00 | 0.0462±0.00 | 0.4326±0.00 | 0.0382±0.00 | 0.1723±0.00 | -0.4876±0.00 |
|
||||||
|
| MLP | Alpha158 | 0.0229±0.01 | 0.2181±0.05 | 0.0360±0.00 | 0.3409±0.02 | 0.0043±0.02 | 0.0602±0.27 | -0.2184±0.04 |
|
||||||
|
| LightGBM | Alpha158 | 0.0399±0.00 | 0.4065±0.00 | 0.0482±0.00 | 0.5101±0.00 | 0.1284±0.00 | 1.5650±0.00 | -0.0635±0.00 |
|
||||||
|
| CatBoost | Alpha158 | 0.0345±0.00 | 0.2855±0.00 | 0.0417±0.00 | 0.3740±0.00 | 0.0496±0.00 | 0.5977±0.00 | -0.1496±0.00 |
|
||||||
|
| DoubleEnsemble | Alpha158 | 0.0380±0.00 | 0.3659±0.00 | 0.0442±0.00 | 0.4324±0.00 | 0.0382±0.00 | 0.1723±0.00 | -0.4876±0.00 |
|
||||||
|
|
||||||
### Alpha360 dataset
|
### Alpha360 dataset
|
||||||
| Model Name | Dataset | IC | ICIR | Rank IC | Rank ICIR | Annualized Return | Information Ratio | Max Drawdown |
|
| Model Name | Dataset | IC | ICIR | Rank IC | Rank ICIR | Annualized Return | Information Ratio | Max Drawdown |
|
||||||
|------------|----------|-------------|-------------|-------------|-------------|-------------------|-------------------|--------------|
|
|------------|----------|-------------|-------------|-------------|-------------|-------------------|-------------------|--------------|
|
||||||
|
| MLP | Alpha360 | 0.0258±0.00 | 0.2021±0.02 | 0.0426±0.00 | 0.3840±0.02 | 0.0022±0.02 | 0.0301±0.26 | -0.2064±0.02 |
|
||||||
| LightGBM | Alpha360 | 0.0400±0.00 | 0.3605±0.00 | 0.0536±0.00 | 0.5431±0.00 | 0.0505±0.00 | 0.7658±0.02 | -0.1880±0.00 |
|
| LightGBM | Alpha360 | 0.0400±0.00 | 0.3605±0.00 | 0.0536±0.00 | 0.5431±0.00 | 0.0505±0.00 | 0.7658±0.02 | -0.1880±0.00 |
|
||||||
|
| CatBoost | Alpha360 | 0.0382±0.00 | 0.3229±0.00 | 0.0489±0.00 | 0.4649±0.00 | 0.0297±0.00 | 0.4227±0.02 | -0.1499±0.01 |
|
||||||
|
| DoubleEnsemble | Alpha360 | 0.0361±0.00 | 0.3092±0.00 | 0.0499±0.00 | 0.4793±0.00 | 0.0382±0.00 | 0.1723±0.02 | -0.4876±0.00 |
|
||||||
|
|
||||||
# Contributing
|
# Contributing
|
||||||
|
|
||||||
@@ -129,3 +138,10 @@ If you want to contribute your new models, you can follow the steps below.
|
|||||||
5. Update the info in the index page in the [news list](https://github.com/microsoft/qlib#newspaper-whats-new----sparkling_heart) and [model list](https://github.com/microsoft/qlib#quant-model-paper-zoo).
|
5. Update the info in the index page in the [news list](https://github.com/microsoft/qlib#newspaper-whats-new----sparkling_heart) and [model list](https://github.com/microsoft/qlib#quant-model-paper-zoo).
|
||||||
|
|
||||||
Finally, you can send PR for review. ([here is an example](https://github.com/microsoft/qlib/pull/1040))
|
Finally, you can send PR for review. ([here is an example](https://github.com/microsoft/qlib/pull/1040))
|
||||||
|
|
||||||
|
|
||||||
|
# FAQ
|
||||||
|
|
||||||
|
Q: What's the difference between models with name `*.py` and `*_ts.py`?
|
||||||
|
|
||||||
|
A: Models with name `*_ts.py` are designed for `TSDatasetH` (`TSDatasetH` will create time-series automatically from tabular data). Models with name `*.py` are designed for `DatasetH` (`DatasetH` is usually used in tabular data. But users still can apply time-series models on tabular datasets if the columns has time-series relationships).
|
||||||
|
|||||||
@@ -38,6 +38,9 @@
|
|||||||
" # install qlib\n",
|
" # install qlib\n",
|
||||||
" ! pip install --upgrade numpy\n",
|
" ! pip install --upgrade numpy\n",
|
||||||
" ! pip install pyqlib\n",
|
" ! pip install pyqlib\n",
|
||||||
|
" if 'google.colab' in sys.modules:\n",
|
||||||
|
" # The Google colab environment is a little outdated. We have to downgrade the pyyaml to make it compatible with other packages\n",
|
||||||
|
" ! pip install pyyaml==5.4.1\n",
|
||||||
" # reload\n",
|
" # reload\n",
|
||||||
" site.main()\n",
|
" site.main()\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
# Copyright (c) Microsoft Corporation.
|
# Copyright (c) Microsoft Corporation.
|
||||||
# Licensed under the MIT License.
|
# Licensed under the MIT License.
|
||||||
|
"""
|
||||||
|
Qlib provides two kinds of interfaces.
|
||||||
|
(1) Users could define the Quant research workflow by a simple configuration.
|
||||||
|
(2) Qlib is designed in a modularized way and supports creating research workflow by code just like building blocks.
|
||||||
|
|
||||||
|
The interface of (1) is `qrun XXX.yaml`. The interface of (2) is script like this, which nearly does the same thing as `qrun XXX.yaml`
|
||||||
|
"""
|
||||||
import qlib
|
import qlib
|
||||||
from qlib.constant import REG_CN
|
from qlib.constant import REG_CN
|
||||||
from qlib.utils import init_instance_by_config, flatten_dict
|
from qlib.utils import init_instance_by_config, flatten_dict
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ def _mount_nfs_uri(provider_uri, mount_path, auto_mount: bool = False):
|
|||||||
else:
|
else:
|
||||||
# Judging system type
|
# Judging system type
|
||||||
sys_type = platform.system()
|
sys_type = platform.system()
|
||||||
if "win" in sys_type.lower():
|
if "windows" in sys_type.lower():
|
||||||
# system: window
|
# system: window
|
||||||
exec_result = os.popen(f"mount -o anon {provider_uri} {mount_path}")
|
exec_result = os.popen(f"mount -o anon {provider_uri} {mount_path}")
|
||||||
result = exec_result.read()
|
result = exec_result.read()
|
||||||
@@ -113,6 +113,8 @@ def _mount_nfs_uri(provider_uri, mount_path, auto_mount: bool = False):
|
|||||||
# system: linux/Unix/Mac
|
# system: linux/Unix/Mac
|
||||||
# check mount
|
# check mount
|
||||||
_remote_uri = provider_uri[:-1] if provider_uri.endswith("/") else provider_uri
|
_remote_uri = provider_uri[:-1] if provider_uri.endswith("/") else provider_uri
|
||||||
|
# `mount a /b/c` is different from `mount a /b/c/`. So we convert it into string to make sure handling it accurately
|
||||||
|
mount_path = str(mount_path)
|
||||||
_mount_path = mount_path[:-1] if mount_path.endswith("/") else mount_path
|
_mount_path = mount_path[:-1] if mount_path.endswith("/") else mount_path
|
||||||
_check_level_num = 2
|
_check_level_num = 2
|
||||||
_is_mount = False
|
_is_mount = False
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ def get_exchange(
|
|||||||
close_cost: float = 0.0025,
|
close_cost: float = 0.0025,
|
||||||
min_cost: float = 5.0,
|
min_cost: float = 5.0,
|
||||||
limit_threshold: Union[Tuple[str, str], float, None] = None,
|
limit_threshold: Union[Tuple[str, str], float, None] = None,
|
||||||
deal_price: Union[str, Tuple[str], List[str]] = None,
|
deal_price: Union[str, Tuple[str, str], List[str]] = None,
|
||||||
**kwargs: Any,
|
**kwargs: Any,
|
||||||
) -> Exchange:
|
) -> Exchange:
|
||||||
"""get_exchange
|
"""get_exchange
|
||||||
@@ -70,10 +70,10 @@ def get_exchange(
|
|||||||
min_cost : float
|
min_cost : float
|
||||||
min transaction cost. It is an absolute amount of cost instead of a ratio of your order's deal amount.
|
min transaction cost. It is an absolute amount of cost instead of a ratio of your order's deal amount.
|
||||||
e.g. You must pay at least 5 yuan of commission regardless of your order's deal amount.
|
e.g. You must pay at least 5 yuan of commission regardless of your order's deal amount.
|
||||||
deal_price: Union[str, Tuple[str], List[str]]
|
deal_price: Union[str, Tuple[str, str], List[str]]
|
||||||
The `deal_price` supports following two types of input
|
The `deal_price` supports following two types of input
|
||||||
- <deal_price> : str
|
- <deal_price> : str
|
||||||
- (<buy_price>, <sell_price>): Tuple[str] or List[str]
|
- (<buy_price>, <sell_price>): Tuple[str, str] or List[str]
|
||||||
|
|
||||||
<deal_price>, <buy_price> or <sell_price> := <price>
|
<deal_price>, <buy_price> or <sell_price> := <price>
|
||||||
<price> := str
|
<price> := str
|
||||||
|
|||||||
@@ -4,10 +4,11 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from abc import abstractmethod
|
from abc import abstractmethod
|
||||||
|
from datetime import time
|
||||||
from enum import IntEnum
|
from enum import IntEnum
|
||||||
|
|
||||||
# try to fix circular imports when enabling type hints
|
# try to fix circular imports when enabling type hints
|
||||||
from typing import Generic, List, TYPE_CHECKING, Any, ClassVar, Optional, Tuple, TypeVar, Union, cast
|
from typing import TYPE_CHECKING, Any, ClassVar, Generic, List, Optional, Tuple, TypeVar, Union, cast
|
||||||
|
|
||||||
from qlib.backtest.utils import TradeCalendarManager
|
from qlib.backtest.utils import TradeCalendarManager
|
||||||
from qlib.data.data import Cal
|
from qlib.data.data import Cal
|
||||||
@@ -23,7 +24,6 @@ from dataclasses import dataclass
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
|
|
||||||
DecisionType = TypeVar("DecisionType")
|
DecisionType = TypeVar("DecisionType")
|
||||||
|
|
||||||
|
|
||||||
@@ -182,8 +182,8 @@ class OrderHelper:
|
|||||||
return Order(
|
return Order(
|
||||||
stock_id=code,
|
stock_id=code,
|
||||||
amount=amount,
|
amount=amount,
|
||||||
start_time=start_time if start_time is not None else pd.Timestamp(start_time),
|
start_time=None if start_time is None else pd.Timestamp(start_time),
|
||||||
end_time=end_time if end_time is not None else pd.Timestamp(end_time),
|
end_time=None if end_time is None else pd.Timestamp(end_time),
|
||||||
direction=direction,
|
direction=direction,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -249,7 +249,7 @@ class IdxTradeRange(TradeRange):
|
|||||||
class TradeRangeByTime(TradeRange):
|
class TradeRangeByTime(TradeRange):
|
||||||
"""This is a helper function for make decisions"""
|
"""This is a helper function for make decisions"""
|
||||||
|
|
||||||
def __init__(self, start_time: str, end_time: str) -> None:
|
def __init__(self, start_time: str | time, end_time: str | time) -> None:
|
||||||
"""
|
"""
|
||||||
This is a callable class.
|
This is a callable class.
|
||||||
|
|
||||||
@@ -259,13 +259,13 @@ class TradeRangeByTime(TradeRange):
|
|||||||
|
|
||||||
Parameters
|
Parameters
|
||||||
----------
|
----------
|
||||||
start_time : str
|
start_time : str | time
|
||||||
e.g. "9:30"
|
e.g. "9:30"
|
||||||
end_time : str
|
end_time : str | time
|
||||||
e.g. "14:30"
|
e.g. "14:30"
|
||||||
"""
|
"""
|
||||||
self.start_time = pd.Timestamp(start_time).time()
|
self.start_time = pd.Timestamp(start_time).time() if isinstance(start_time, str) else start_time
|
||||||
self.end_time = pd.Timestamp(end_time).time()
|
self.end_time = pd.Timestamp(end_time).time() if isinstance(end_time, str) else end_time
|
||||||
assert self.start_time < self.end_time
|
assert self.start_time < self.end_time
|
||||||
|
|
||||||
def __call__(self, trade_calendar: TradeCalendarManager) -> Tuple[int, int]:
|
def __call__(self, trade_calendar: TradeCalendarManager) -> Tuple[int, int]:
|
||||||
@@ -535,7 +535,12 @@ class TradeDecisionWO(BaseTradeDecision[Order]):
|
|||||||
Besides, the time_range is also included.
|
Besides, the time_range is also included.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, order_list: List[object], strategy: BaseStrategy, trade_range: Tuple[int, int] = None) -> None:
|
def __init__(
|
||||||
|
self,
|
||||||
|
order_list: List[Order],
|
||||||
|
strategy: BaseStrategy,
|
||||||
|
trade_range: Union[Tuple[int, int], TradeRange] = None,
|
||||||
|
) -> None:
|
||||||
super().__init__(strategy, trade_range=trade_range)
|
super().__init__(strategy, trade_range=trade_range)
|
||||||
self.order_list = cast(List[Order], order_list)
|
self.order_list = cast(List[Order], order_list)
|
||||||
start, end = strategy.trade_calendar.get_step_time()
|
start, end = strategy.trade_calendar.get_step_time()
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ class Exchange:
|
|||||||
start_time: Union[pd.Timestamp, str] = None,
|
start_time: Union[pd.Timestamp, str] = None,
|
||||||
end_time: Union[pd.Timestamp, str] = None,
|
end_time: Union[pd.Timestamp, str] = None,
|
||||||
codes: Union[list, str] = "all",
|
codes: Union[list, str] = "all",
|
||||||
deal_price: Union[str, Tuple[str], List[str]] = None,
|
deal_price: Union[str, Tuple[str, str], List[str]] = None,
|
||||||
subscribe_fields: list = [],
|
subscribe_fields: list = [],
|
||||||
limit_threshold: Union[Tuple[str, str], float, None] = None,
|
limit_threshold: Union[Tuple[str, str], float, None] = None,
|
||||||
volume_threshold: Union[tuple, dict] = None,
|
volume_threshold: Union[tuple, dict] = None,
|
||||||
@@ -448,9 +448,9 @@ class Exchange:
|
|||||||
start_time: pd.Timestamp,
|
start_time: pd.Timestamp,
|
||||||
end_time: pd.Timestamp,
|
end_time: pd.Timestamp,
|
||||||
method: Optional[str] = "sum",
|
method: Optional[str] = "sum",
|
||||||
) -> float:
|
) -> Union[None, int, float, bool, IndexData]:
|
||||||
"""get the total deal volume of stock with `stock_id` between the time interval [start_time, end_time)"""
|
"""get the total deal volume of stock with `stock_id` between the time interval [start_time, end_time)"""
|
||||||
return cast(float, self.quote.get_data(stock_id, start_time, end_time, field="$volume", method=method))
|
return self.quote.get_data(stock_id, start_time, end_time, field="$volume", method=method)
|
||||||
|
|
||||||
def get_deal_price(
|
def get_deal_price(
|
||||||
self,
|
self,
|
||||||
@@ -459,7 +459,7 @@ class Exchange:
|
|||||||
end_time: pd.Timestamp,
|
end_time: pd.Timestamp,
|
||||||
direction: OrderDir,
|
direction: OrderDir,
|
||||||
method: Optional[str] = "ts_data_last",
|
method: Optional[str] = "ts_data_last",
|
||||||
) -> float:
|
) -> Union[None, int, float, bool, IndexData]:
|
||||||
if direction == OrderDir.SELL:
|
if direction == OrderDir.SELL:
|
||||||
pstr = self.sell_price
|
pstr = self.sell_price
|
||||||
elif direction == OrderDir.BUY:
|
elif direction == OrderDir.BUY:
|
||||||
@@ -472,7 +472,7 @@ class Exchange:
|
|||||||
self.logger.warning(f"(stock_id:{stock_id}, trade_time:{(start_time, end_time)}, {pstr}): {deal_price}!!!")
|
self.logger.warning(f"(stock_id:{stock_id}, trade_time:{(start_time, end_time)}, {pstr}): {deal_price}!!!")
|
||||||
self.logger.warning(f"setting deal_price to close price")
|
self.logger.warning(f"setting deal_price to close price")
|
||||||
deal_price = self.get_close(stock_id, start_time, end_time, method)
|
deal_price = self.get_close(stock_id, start_time, end_time, method)
|
||||||
return cast(float, deal_price)
|
return deal_price
|
||||||
|
|
||||||
def get_factor(
|
def get_factor(
|
||||||
self,
|
self,
|
||||||
@@ -832,8 +832,11 @@ class Exchange:
|
|||||||
:param dealt_order_amount: the dealt order amount dict with the format of {stock_id: float}
|
:param dealt_order_amount: the dealt order amount dict with the format of {stock_id: float}
|
||||||
:return: trade_price, trade_val, trade_cost
|
:return: trade_price, trade_val, trade_cost
|
||||||
"""
|
"""
|
||||||
trade_price = self.get_deal_price(order.stock_id, order.start_time, order.end_time, direction=order.direction)
|
trade_price = cast(
|
||||||
total_trade_val = self.get_volume(order.stock_id, order.start_time, order.end_time) * trade_price
|
float,
|
||||||
|
self.get_deal_price(order.stock_id, order.start_time, order.end_time, direction=order.direction),
|
||||||
|
)
|
||||||
|
total_trade_val = cast(float, self.get_volume(order.stock_id, order.start_time, order.end_time)) * trade_price
|
||||||
order.factor = self.get_factor(order.stock_id, order.start_time, order.end_time)
|
order.factor = self.get_factor(order.stock_id, order.start_time, order.end_time)
|
||||||
order.deal_amount = order.amount # set to full amount and clip it step by step
|
order.deal_amount = order.amount # set to full amount and clip it step by step
|
||||||
# Clipping amount first
|
# Clipping amount first
|
||||||
|
|||||||
@@ -484,6 +484,7 @@ class NestedExecutor(BaseExecutor):
|
|||||||
inner_exe_res :
|
inner_exe_res :
|
||||||
the execution result of inner task
|
the execution result of inner task
|
||||||
"""
|
"""
|
||||||
|
self.inner_strategy.post_exe_step(inner_exe_res)
|
||||||
|
|
||||||
def get_all_executors(self) -> List[BaseExecutor]:
|
def get_all_executors(self) -> List[BaseExecutor]:
|
||||||
"""get all executors, including self and inner_executor.get_all_executors()"""
|
"""get all executors, including self and inner_executor.get_all_executors()"""
|
||||||
|
|||||||
@@ -203,8 +203,14 @@ class MTSDatasetH(DatasetH):
|
|||||||
|
|
||||||
def _prepare_seg(self, slc, **kwargs):
|
def _prepare_seg(self, slc, **kwargs):
|
||||||
fn = _get_date_parse_fn(self._index[0][1])
|
fn = _get_date_parse_fn(self._index[0][1])
|
||||||
start_date = fn(slc.start)
|
if isinstance(slc, slice):
|
||||||
end_date = fn(slc.stop)
|
start, stop = slc.start, slc.stop
|
||||||
|
elif isinstance(slc, (list, tuple)):
|
||||||
|
start, stop = slc
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(f"This type of input is not supported")
|
||||||
|
start_date = pd.Timestamp(fn(start))
|
||||||
|
end_date = pd.Timestamp(fn(stop))
|
||||||
obj = copy.copy(self) # shallow copy
|
obj = copy.copy(self) # shallow copy
|
||||||
# NOTE: Seriable will disable copy `self._data` so we manually assign them here
|
# NOTE: Seriable will disable copy `self._data` so we manually assign them here
|
||||||
obj._data = self._data # reference (no copy)
|
obj._data = self._data # reference (no copy)
|
||||||
|
|||||||
@@ -259,79 +259,119 @@ class Alpha158(DataHandlerLP):
|
|||||||
def use(x):
|
def use(x):
|
||||||
return x not in exclude and (include is None or x in include)
|
return x not in exclude and (include is None or x in include)
|
||||||
|
|
||||||
|
# Some factor ref: https://guorn.com/static/upload/file/3/134065454575605.pdf
|
||||||
if use("ROC"):
|
if use("ROC"):
|
||||||
|
# https://www.investopedia.com/terms/r/rateofchange.asp
|
||||||
|
# Rate of change, the price change in the past d days, divided by latest close price to remove unit
|
||||||
fields += ["Ref($close, %d)/$close" % d for d in windows]
|
fields += ["Ref($close, %d)/$close" % d for d in windows]
|
||||||
names += ["ROC%d" % d for d in windows]
|
names += ["ROC%d" % d for d in windows]
|
||||||
if use("MA"):
|
if use("MA"):
|
||||||
|
# https://www.investopedia.com/ask/answers/071414/whats-difference-between-moving-average-and-weighted-moving-average.asp
|
||||||
|
# Simple Moving Average, the simple moving average in the past d days, divided by latest close price to remove unit
|
||||||
fields += ["Mean($close, %d)/$close" % d for d in windows]
|
fields += ["Mean($close, %d)/$close" % d for d in windows]
|
||||||
names += ["MA%d" % d for d in windows]
|
names += ["MA%d" % d for d in windows]
|
||||||
if use("STD"):
|
if use("STD"):
|
||||||
|
# The standard diviation of close price for the past d days, divided by latest close price to remove unit
|
||||||
fields += ["Std($close, %d)/$close" % d for d in windows]
|
fields += ["Std($close, %d)/$close" % d for d in windows]
|
||||||
names += ["STD%d" % d for d in windows]
|
names += ["STD%d" % d for d in windows]
|
||||||
if use("BETA"):
|
if use("BETA"):
|
||||||
|
# The rate of close price change in the past d days, divided by latest close price to remove unit
|
||||||
|
# For example, price increase 10 dollar per day in the past d days, then Slope will be 10.
|
||||||
fields += ["Slope($close, %d)/$close" % d for d in windows]
|
fields += ["Slope($close, %d)/$close" % d for d in windows]
|
||||||
names += ["BETA%d" % d for d in windows]
|
names += ["BETA%d" % d for d in windows]
|
||||||
if use("RSQR"):
|
if use("RSQR"):
|
||||||
|
# The R-sqaure value of linear regression for the past d days, represent the trend linear
|
||||||
fields += ["Rsquare($close, %d)" % d for d in windows]
|
fields += ["Rsquare($close, %d)" % d for d in windows]
|
||||||
names += ["RSQR%d" % d for d in windows]
|
names += ["RSQR%d" % d for d in windows]
|
||||||
if use("RESI"):
|
if use("RESI"):
|
||||||
|
# The redisdual for linear regression for the past d days, represent the trend linearity for past d days.
|
||||||
fields += ["Resi($close, %d)/$close" % d for d in windows]
|
fields += ["Resi($close, %d)/$close" % d for d in windows]
|
||||||
names += ["RESI%d" % d for d in windows]
|
names += ["RESI%d" % d for d in windows]
|
||||||
if use("MAX"):
|
if use("MAX"):
|
||||||
|
# The max price for past d days, divided by latest close price to remove unit
|
||||||
fields += ["Max($high, %d)/$close" % d for d in windows]
|
fields += ["Max($high, %d)/$close" % d for d in windows]
|
||||||
names += ["MAX%d" % d for d in windows]
|
names += ["MAX%d" % d for d in windows]
|
||||||
if use("LOW"):
|
if use("LOW"):
|
||||||
|
# The low price for past d days, divided by latest close price to remove unit
|
||||||
fields += ["Min($low, %d)/$close" % d for d in windows]
|
fields += ["Min($low, %d)/$close" % d for d in windows]
|
||||||
names += ["MIN%d" % d for d in windows]
|
names += ["MIN%d" % d for d in windows]
|
||||||
if use("QTLU"):
|
if use("QTLU"):
|
||||||
|
# The 80% quantile of past d day's close price, divided by latest close price to remove unit
|
||||||
|
# Used with MIN and MAX
|
||||||
fields += ["Quantile($close, %d, 0.8)/$close" % d for d in windows]
|
fields += ["Quantile($close, %d, 0.8)/$close" % d for d in windows]
|
||||||
names += ["QTLU%d" % d for d in windows]
|
names += ["QTLU%d" % d for d in windows]
|
||||||
if use("QTLD"):
|
if use("QTLD"):
|
||||||
|
# The 20% quantile of past d day's close price, divided by latest close price to remove unit
|
||||||
fields += ["Quantile($close, %d, 0.2)/$close" % d for d in windows]
|
fields += ["Quantile($close, %d, 0.2)/$close" % d for d in windows]
|
||||||
names += ["QTLD%d" % d for d in windows]
|
names += ["QTLD%d" % d for d in windows]
|
||||||
if use("RANK"):
|
if use("RANK"):
|
||||||
|
# Get the percentile of current close price in past d day's close price.
|
||||||
|
# Represent the current price level comparing to past N days, add additional information to moving average.
|
||||||
fields += ["Rank($close, %d)" % d for d in windows]
|
fields += ["Rank($close, %d)" % d for d in windows]
|
||||||
names += ["RANK%d" % d for d in windows]
|
names += ["RANK%d" % d for d in windows]
|
||||||
if use("RSV"):
|
if use("RSV"):
|
||||||
|
# Represent the price position between upper and lower resistent price for past d days.
|
||||||
fields += ["($close-Min($low, %d))/(Max($high, %d)-Min($low, %d)+1e-12)" % (d, d, d) for d in windows]
|
fields += ["($close-Min($low, %d))/(Max($high, %d)-Min($low, %d)+1e-12)" % (d, d, d) for d in windows]
|
||||||
names += ["RSV%d" % d for d in windows]
|
names += ["RSV%d" % d for d in windows]
|
||||||
if use("IMAX"):
|
if use("IMAX"):
|
||||||
|
# The number of days between current date and previous highest price date.
|
||||||
|
# Part of Aroon Indicator https://www.investopedia.com/terms/a/aroon.asp
|
||||||
|
# The indicator measures the time between highs and the time between lows over a time period.
|
||||||
|
# The idea is that strong uptrends will regularly see new highs, and strong downtrends will regularly see new lows.
|
||||||
fields += ["IdxMax($high, %d)/%d" % (d, d) for d in windows]
|
fields += ["IdxMax($high, %d)/%d" % (d, d) for d in windows]
|
||||||
names += ["IMAX%d" % d for d in windows]
|
names += ["IMAX%d" % d for d in windows]
|
||||||
if use("IMIN"):
|
if use("IMIN"):
|
||||||
|
# The number of days between current date and previous lowest price date.
|
||||||
|
# Part of Aroon Indicator https://www.investopedia.com/terms/a/aroon.asp
|
||||||
|
# The indicator measures the time between highs and the time between lows over a time period.
|
||||||
|
# The idea is that strong uptrends will regularly see new highs, and strong downtrends will regularly see new lows.
|
||||||
fields += ["IdxMin($low, %d)/%d" % (d, d) for d in windows]
|
fields += ["IdxMin($low, %d)/%d" % (d, d) for d in windows]
|
||||||
names += ["IMIN%d" % d for d in windows]
|
names += ["IMIN%d" % d for d in windows]
|
||||||
if use("IMXD"):
|
if use("IMXD"):
|
||||||
|
# The time period between previous lowest-price date occur after highest price date.
|
||||||
|
# Large value suggest downward momemtum.
|
||||||
fields += ["(IdxMax($high, %d)-IdxMin($low, %d))/%d" % (d, d, d) for d in windows]
|
fields += ["(IdxMax($high, %d)-IdxMin($low, %d))/%d" % (d, d, d) for d in windows]
|
||||||
names += ["IMXD%d" % d for d in windows]
|
names += ["IMXD%d" % d for d in windows]
|
||||||
if use("CORR"):
|
if use("CORR"):
|
||||||
|
# The correlation between absolute close price and log scaled trading volume
|
||||||
fields += ["Corr($close, Log($volume+1), %d)" % d for d in windows]
|
fields += ["Corr($close, Log($volume+1), %d)" % d for d in windows]
|
||||||
names += ["CORR%d" % d for d in windows]
|
names += ["CORR%d" % d for d in windows]
|
||||||
if use("CORD"):
|
if use("CORD"):
|
||||||
|
# The correlation between price change ratio and volume change ratio
|
||||||
fields += ["Corr($close/Ref($close,1), Log($volume/Ref($volume, 1)+1), %d)" % d for d in windows]
|
fields += ["Corr($close/Ref($close,1), Log($volume/Ref($volume, 1)+1), %d)" % d for d in windows]
|
||||||
names += ["CORD%d" % d for d in windows]
|
names += ["CORD%d" % d for d in windows]
|
||||||
if use("CNTP"):
|
if use("CNTP"):
|
||||||
|
# The percentage of days in past d days that price go up.
|
||||||
fields += ["Mean($close>Ref($close, 1), %d)" % d for d in windows]
|
fields += ["Mean($close>Ref($close, 1), %d)" % d for d in windows]
|
||||||
names += ["CNTP%d" % d for d in windows]
|
names += ["CNTP%d" % d for d in windows]
|
||||||
if use("CNTN"):
|
if use("CNTN"):
|
||||||
|
# The percentage of days in past d days that price go down.
|
||||||
fields += ["Mean($close<Ref($close, 1), %d)" % d for d in windows]
|
fields += ["Mean($close<Ref($close, 1), %d)" % d for d in windows]
|
||||||
names += ["CNTN%d" % d for d in windows]
|
names += ["CNTN%d" % d for d in windows]
|
||||||
if use("CNTD"):
|
if use("CNTD"):
|
||||||
|
# The diff between past up day and past down day
|
||||||
fields += ["Mean($close>Ref($close, 1), %d)-Mean($close<Ref($close, 1), %d)" % (d, d) for d in windows]
|
fields += ["Mean($close>Ref($close, 1), %d)-Mean($close<Ref($close, 1), %d)" % (d, d) for d in windows]
|
||||||
names += ["CNTD%d" % d for d in windows]
|
names += ["CNTD%d" % d for d in windows]
|
||||||
if use("SUMP"):
|
if use("SUMP"):
|
||||||
|
# The total gain / the absolute total price changed
|
||||||
|
# Similar to RSI indicator. https://www.investopedia.com/terms/r/rsi.asp
|
||||||
fields += [
|
fields += [
|
||||||
"Sum(Greater($close-Ref($close, 1), 0), %d)/(Sum(Abs($close-Ref($close, 1)), %d)+1e-12)" % (d, d)
|
"Sum(Greater($close-Ref($close, 1), 0), %d)/(Sum(Abs($close-Ref($close, 1)), %d)+1e-12)" % (d, d)
|
||||||
for d in windows
|
for d in windows
|
||||||
]
|
]
|
||||||
names += ["SUMP%d" % d for d in windows]
|
names += ["SUMP%d" % d for d in windows]
|
||||||
if use("SUMN"):
|
if use("SUMN"):
|
||||||
|
# The total lose / the absolute total price changed
|
||||||
|
# Can be derived from SUMP by SUMN = 1 - SUMP
|
||||||
|
# Similar to RSI indicator. https://www.investopedia.com/terms/r/rsi.asp
|
||||||
fields += [
|
fields += [
|
||||||
"Sum(Greater(Ref($close, 1)-$close, 0), %d)/(Sum(Abs($close-Ref($close, 1)), %d)+1e-12)" % (d, d)
|
"Sum(Greater(Ref($close, 1)-$close, 0), %d)/(Sum(Abs($close-Ref($close, 1)), %d)+1e-12)" % (d, d)
|
||||||
for d in windows
|
for d in windows
|
||||||
]
|
]
|
||||||
names += ["SUMN%d" % d for d in windows]
|
names += ["SUMN%d" % d for d in windows]
|
||||||
if use("SUMD"):
|
if use("SUMD"):
|
||||||
|
# The diff ratio between total gain and total lose
|
||||||
|
# Similar to RSI indicator. https://www.investopedia.com/terms/r/rsi.asp
|
||||||
fields += [
|
fields += [
|
||||||
"(Sum(Greater($close-Ref($close, 1), 0), %d)-Sum(Greater(Ref($close, 1)-$close, 0), %d))"
|
"(Sum(Greater($close-Ref($close, 1), 0), %d)-Sum(Greater(Ref($close, 1)-$close, 0), %d))"
|
||||||
"/(Sum(Abs($close-Ref($close, 1)), %d)+1e-12)" % (d, d, d)
|
"/(Sum(Abs($close-Ref($close, 1)), %d)+1e-12)" % (d, d, d)
|
||||||
@@ -339,12 +379,15 @@ class Alpha158(DataHandlerLP):
|
|||||||
]
|
]
|
||||||
names += ["SUMD%d" % d for d in windows]
|
names += ["SUMD%d" % d for d in windows]
|
||||||
if use("VMA"):
|
if use("VMA"):
|
||||||
|
# Simple Volume Moving average: https://www.barchart.com/education/technical-indicators/volume_moving_average
|
||||||
fields += ["Mean($volume, %d)/($volume+1e-12)" % d for d in windows]
|
fields += ["Mean($volume, %d)/($volume+1e-12)" % d for d in windows]
|
||||||
names += ["VMA%d" % d for d in windows]
|
names += ["VMA%d" % d for d in windows]
|
||||||
if use("VSTD"):
|
if use("VSTD"):
|
||||||
|
# The standard deviation for volume in past d days.
|
||||||
fields += ["Std($volume, %d)/($volume+1e-12)" % d for d in windows]
|
fields += ["Std($volume, %d)/($volume+1e-12)" % d for d in windows]
|
||||||
names += ["VSTD%d" % d for d in windows]
|
names += ["VSTD%d" % d for d in windows]
|
||||||
if use("WVMA"):
|
if use("WVMA"):
|
||||||
|
# The volume weighted price change volatility
|
||||||
fields += [
|
fields += [
|
||||||
"Std(Abs($close/Ref($close, 1)-1)*$volume, %d)/(Mean(Abs($close/Ref($close, 1)-1)*$volume, %d)+1e-12)"
|
"Std(Abs($close/Ref($close, 1)-1)*$volume, %d)/(Mean(Abs($close/Ref($close, 1)-1)*$volume, %d)+1e-12)"
|
||||||
% (d, d)
|
% (d, d)
|
||||||
@@ -352,6 +395,7 @@ class Alpha158(DataHandlerLP):
|
|||||||
]
|
]
|
||||||
names += ["WVMA%d" % d for d in windows]
|
names += ["WVMA%d" % d for d in windows]
|
||||||
if use("VSUMP"):
|
if use("VSUMP"):
|
||||||
|
# The total volume increase / the absolute total volume changed
|
||||||
fields += [
|
fields += [
|
||||||
"Sum(Greater($volume-Ref($volume, 1), 0), %d)/(Sum(Abs($volume-Ref($volume, 1)), %d)+1e-12)"
|
"Sum(Greater($volume-Ref($volume, 1), 0), %d)/(Sum(Abs($volume-Ref($volume, 1)), %d)+1e-12)"
|
||||||
% (d, d)
|
% (d, d)
|
||||||
@@ -359,6 +403,8 @@ class Alpha158(DataHandlerLP):
|
|||||||
]
|
]
|
||||||
names += ["VSUMP%d" % d for d in windows]
|
names += ["VSUMP%d" % d for d in windows]
|
||||||
if use("VSUMN"):
|
if use("VSUMN"):
|
||||||
|
# The total volume increase / the absolute total volume changed
|
||||||
|
# Can be derived from VSUMP by VSUMN = 1 - VSUMP
|
||||||
fields += [
|
fields += [
|
||||||
"Sum(Greater(Ref($volume, 1)-$volume, 0), %d)/(Sum(Abs($volume-Ref($volume, 1)), %d)+1e-12)"
|
"Sum(Greater(Ref($volume, 1)-$volume, 0), %d)/(Sum(Abs($volume-Ref($volume, 1)), %d)+1e-12)"
|
||||||
% (d, d)
|
% (d, d)
|
||||||
@@ -366,6 +412,8 @@ class Alpha158(DataHandlerLP):
|
|||||||
]
|
]
|
||||||
names += ["VSUMN%d" % d for d in windows]
|
names += ["VSUMN%d" % d for d in windows]
|
||||||
if use("VSUMD"):
|
if use("VSUMD"):
|
||||||
|
# The diff ratio between total volume increase and total volume decrease
|
||||||
|
# RSI indicator for volume
|
||||||
fields += [
|
fields += [
|
||||||
"(Sum(Greater($volume-Ref($volume, 1), 0), %d)-Sum(Greater(Ref($volume, 1)-$volume, 0), %d))"
|
"(Sum(Greater($volume-Ref($volume, 1), 0), %d)-Sum(Greater(Ref($volume, 1)-$volume, 0), %d))"
|
||||||
"/(Sum(Abs($volume-Ref($volume, 1)), %d)+1e-12)" % (d, d, d)
|
"/(Sum(Abs($volume-Ref($volume, 1)), %d)+1e-12)" % (d, d, d)
|
||||||
|
|||||||
@@ -137,8 +137,7 @@ class HighFreqBacktestHandler(DataHandler):
|
|||||||
names = []
|
names = []
|
||||||
|
|
||||||
template_if = "If(IsNull({1}), {0}, {1})"
|
template_if = "If(IsNull({1}), {0}, {1})"
|
||||||
template_paused = "Select(Gt($hx_paused_num, 1.001), {0})"
|
template_paused = "Select(Gt($paused_num, 1.001), {0})"
|
||||||
# template_paused = "{0}"
|
|
||||||
template_fillnan = "FFillNan({0})"
|
template_fillnan = "FFillNan({0})"
|
||||||
fields += [
|
fields += [
|
||||||
template_fillnan.format(template_paused.format("$close")),
|
template_fillnan.format(template_paused.format("$close")),
|
||||||
@@ -162,3 +161,249 @@ class HighFreqBacktestHandler(DataHandler):
|
|||||||
names += ["$factor0"]
|
names += ["$factor0"]
|
||||||
|
|
||||||
return fields, names
|
return fields, names
|
||||||
|
|
||||||
|
|
||||||
|
class HighFreqOrderHandler(DataHandlerLP):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
instruments="csi300",
|
||||||
|
start_time=None,
|
||||||
|
end_time=None,
|
||||||
|
infer_processors=[],
|
||||||
|
learn_processors=[],
|
||||||
|
fit_start_time=None,
|
||||||
|
fit_end_time=None,
|
||||||
|
drop_raw=True,
|
||||||
|
):
|
||||||
|
def check_transform_proc(proc_l):
|
||||||
|
new_l = []
|
||||||
|
for p in proc_l:
|
||||||
|
p["kwargs"].update(
|
||||||
|
{
|
||||||
|
"fit_start_time": fit_start_time,
|
||||||
|
"fit_end_time": fit_end_time,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
new_l.append(p)
|
||||||
|
return new_l
|
||||||
|
|
||||||
|
infer_processors = check_transform_proc(infer_processors)
|
||||||
|
learn_processors = check_transform_proc(learn_processors)
|
||||||
|
|
||||||
|
data_loader = {
|
||||||
|
"class": "QlibDataLoader",
|
||||||
|
"kwargs": {
|
||||||
|
"config": self.get_feature_config(),
|
||||||
|
"swap_level": False,
|
||||||
|
"freq": "1min",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
super().__init__(
|
||||||
|
instruments=instruments,
|
||||||
|
start_time=start_time,
|
||||||
|
end_time=end_time,
|
||||||
|
data_loader=data_loader,
|
||||||
|
infer_processors=infer_processors,
|
||||||
|
learn_processors=learn_processors,
|
||||||
|
drop_raw=drop_raw,
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_feature_config(self):
|
||||||
|
fields = []
|
||||||
|
names = []
|
||||||
|
|
||||||
|
template_if = "If(IsNull({1}), {0}, {1})"
|
||||||
|
template_ifinf = "If(IsInf({1}), {0}, {1})"
|
||||||
|
template_paused = "Select(Gt($paused_num, 1.001), {0})"
|
||||||
|
|
||||||
|
def get_normalized_price_feature(price_field, shift=0):
|
||||||
|
# norm with the close price of 237th minute of yesterday.
|
||||||
|
if shift == 0:
|
||||||
|
template_norm = "{0}/DayLast(Ref({1}, 243))"
|
||||||
|
else:
|
||||||
|
template_norm = "Ref({0}, " + str(shift) + ")/DayLast(Ref({1}, 243))"
|
||||||
|
|
||||||
|
template_fillnan = "FFillNan({0})"
|
||||||
|
# calculate -> ffill -> remove paused
|
||||||
|
feature_ops = template_paused.format(
|
||||||
|
template_fillnan.format(
|
||||||
|
template_norm.format(template_if.format("$close", price_field), template_fillnan.format("$close"))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return feature_ops
|
||||||
|
|
||||||
|
def get_normalized_vwap_price_feature(price_field, shift=0):
|
||||||
|
# norm with the close price of 237th minute of yesterday.
|
||||||
|
if shift == 0:
|
||||||
|
template_norm = "{0}/DayLast(Ref({1}, 243))"
|
||||||
|
else:
|
||||||
|
template_norm = "Ref({0}, " + str(shift) + ")/DayLast(Ref({1}, 243))"
|
||||||
|
|
||||||
|
template_fillnan = "FFillNan({0})"
|
||||||
|
# calculate -> ffill -> remove paused
|
||||||
|
feature_ops = template_paused.format(
|
||||||
|
template_fillnan.format(
|
||||||
|
template_norm.format(
|
||||||
|
template_if.format("$close", template_ifinf.format("$close", price_field)),
|
||||||
|
template_fillnan.format("$close"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return feature_ops
|
||||||
|
|
||||||
|
fields += [get_normalized_price_feature("$open", 0)]
|
||||||
|
fields += [get_normalized_price_feature("$high", 0)]
|
||||||
|
fields += [get_normalized_price_feature("$low", 0)]
|
||||||
|
fields += [get_normalized_price_feature("$close", 0)]
|
||||||
|
fields += [get_normalized_vwap_price_feature("$vwap", 0)]
|
||||||
|
names += ["$open", "$high", "$low", "$close", "$vwap"]
|
||||||
|
|
||||||
|
fields += [get_normalized_price_feature("$open", 240)]
|
||||||
|
fields += [get_normalized_price_feature("$high", 240)]
|
||||||
|
fields += [get_normalized_price_feature("$low", 240)]
|
||||||
|
fields += [get_normalized_price_feature("$close", 240)]
|
||||||
|
fields += [get_normalized_vwap_price_feature("$vwap", 240)]
|
||||||
|
names += ["$open_1", "$high_1", "$low_1", "$close_1", "$vwap_1"]
|
||||||
|
|
||||||
|
fields += [get_normalized_price_feature("$bid", 0)]
|
||||||
|
fields += [get_normalized_price_feature("$ask", 0)]
|
||||||
|
names += ["$bid", "$ask"]
|
||||||
|
|
||||||
|
fields += [get_normalized_price_feature("$bid", 240)]
|
||||||
|
fields += [get_normalized_price_feature("$ask", 240)]
|
||||||
|
names += ["$bid_1", "$ask_1"]
|
||||||
|
|
||||||
|
# calculate and fill nan with 0
|
||||||
|
|
||||||
|
def get_volume_feature(volume_field, shift=0):
|
||||||
|
template_gzero = "If(Ge({0}, 0), {0}, 0)"
|
||||||
|
if shift == 0:
|
||||||
|
feature_ops = template_gzero.format(
|
||||||
|
template_paused.format(
|
||||||
|
"If(IsInf({0}), 0, {0})".format(
|
||||||
|
"If(IsNull({0}), 0, {0})".format(
|
||||||
|
"{0}/Ref(DayLast(Mean({0}, 7200)), 240)".format(volume_field)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
feature_ops = template_gzero.format(
|
||||||
|
template_paused.format(
|
||||||
|
"If(IsInf({0}), 0, {0})".format(
|
||||||
|
"If(IsNull({0}), 0, {0})".format(
|
||||||
|
f"Ref({{0}}, {shift})/Ref(DayLast(Mean({{0}}, 7200)), 240)".format(volume_field)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return feature_ops
|
||||||
|
|
||||||
|
fields += [get_volume_feature("$volume", 0)]
|
||||||
|
names += ["$volume"]
|
||||||
|
|
||||||
|
fields += [get_volume_feature("$volume", 240)]
|
||||||
|
names += ["$volume_1"]
|
||||||
|
|
||||||
|
fields += [get_volume_feature("$bidV", 0)]
|
||||||
|
fields += [get_volume_feature("$bidV1", 0)]
|
||||||
|
fields += [get_volume_feature("$bidV3", 0)]
|
||||||
|
fields += [get_volume_feature("$bidV5", 0)]
|
||||||
|
fields += [get_volume_feature("$askV", 0)]
|
||||||
|
fields += [get_volume_feature("$askV1", 0)]
|
||||||
|
fields += [get_volume_feature("$askV3", 0)]
|
||||||
|
fields += [get_volume_feature("$askV5", 0)]
|
||||||
|
names += ["$bidV", "$bidV1", "$bidV3", "$bidV5", "$askV", "$askV1", "$askV3", "$askV5"]
|
||||||
|
|
||||||
|
fields += [get_volume_feature("$bidV", 240)]
|
||||||
|
fields += [get_volume_feature("$bidV1", 240)]
|
||||||
|
fields += [get_volume_feature("$bidV3", 240)]
|
||||||
|
fields += [get_volume_feature("$bidV5", 240)]
|
||||||
|
fields += [get_volume_feature("$askV", 240)]
|
||||||
|
fields += [get_volume_feature("$askV1", 240)]
|
||||||
|
fields += [get_volume_feature("$askV3", 240)]
|
||||||
|
fields += [get_volume_feature("$askV5", 240)]
|
||||||
|
names += ["$bidV_1", "$bidV1_1", "$bidV3_1", "$bidV5_1", "$askV_1", "$askV1_1", "$askV3_1", "$askV5_1"]
|
||||||
|
|
||||||
|
return fields, names
|
||||||
|
|
||||||
|
|
||||||
|
class HighFreqBacktestOrderHandler(DataHandler):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
instruments="csi300",
|
||||||
|
start_time=None,
|
||||||
|
end_time=None,
|
||||||
|
):
|
||||||
|
data_loader = {
|
||||||
|
"class": "QlibDataLoader",
|
||||||
|
"kwargs": {
|
||||||
|
"config": self.get_feature_config(),
|
||||||
|
"swap_level": False,
|
||||||
|
"freq": "1min",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
super().__init__(
|
||||||
|
instruments=instruments,
|
||||||
|
start_time=start_time,
|
||||||
|
end_time=end_time,
|
||||||
|
data_loader=data_loader,
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_feature_config(self):
|
||||||
|
fields = []
|
||||||
|
names = []
|
||||||
|
|
||||||
|
template_if = "If(IsNull({1}), {0}, {1})"
|
||||||
|
template_paused = "Select(Gt($hx_paused_num, 1.001), {0})"
|
||||||
|
# template_paused = "{0}"
|
||||||
|
template_fillnan = "FFillNan({0})"
|
||||||
|
fields += [
|
||||||
|
template_fillnan.format(template_paused.format("$close")),
|
||||||
|
]
|
||||||
|
names += ["$close0"]
|
||||||
|
|
||||||
|
fields += [
|
||||||
|
template_paused.format(
|
||||||
|
template_if.format(
|
||||||
|
template_fillnan.format("$close"),
|
||||||
|
"$vwap",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
names += ["$vwap0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$volume"))]
|
||||||
|
names += ["$volume0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$bid"))]
|
||||||
|
names += ["$bid0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$bidV"))]
|
||||||
|
names += ["$bidV0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$ask"))]
|
||||||
|
names += ["$ask0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$askV"))]
|
||||||
|
names += ["$askV0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("($bid + $ask) / 2"))]
|
||||||
|
names += ["$median0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$factor"))]
|
||||||
|
names += ["$factor0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$downlimitmarket"))]
|
||||||
|
names += ["$downlimitmarket0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$uplimitmarket"))]
|
||||||
|
names += ["$uplimitmarket0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$highmarket"))]
|
||||||
|
names += ["$highmarket0"]
|
||||||
|
|
||||||
|
fields += [template_paused.format("If(IsNull({0}), 0, {0})".format("$lowmarket"))]
|
||||||
|
names += ["$lowmarket0"]
|
||||||
|
|
||||||
|
return fields, names
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ class DEnsembleModel(Model, FeatureInt):
|
|||||||
if sample_ratios is None: # the default values for sample_ratios
|
if sample_ratios is None: # the default values for sample_ratios
|
||||||
sample_ratios = [0.8, 0.7, 0.6, 0.5, 0.4]
|
sample_ratios = [0.8, 0.7, 0.6, 0.5, 0.4]
|
||||||
if sub_weights is None: # the default values for sub_weights
|
if sub_weights is None: # the default values for sub_weights
|
||||||
sub_weights = [1.0, 0.2, 0.2, 0.2, 0.2, 0.2]
|
sub_weights = [1] * self.num_models
|
||||||
if not len(sample_ratios) == bins_fs:
|
if not len(sample_ratios) == bins_fs:
|
||||||
raise ValueError("The length of sample_ratios should be equal to bins_fs.")
|
raise ValueError("The length of sample_ratios should be equal to bins_fs.")
|
||||||
self.sample_ratios = sample_ratios
|
self.sample_ratios = sample_ratios
|
||||||
@@ -87,7 +87,9 @@ class DEnsembleModel(Model, FeatureInt):
|
|||||||
loss_curve = self.retrieve_loss_curve(model_k, df_train, features)
|
loss_curve = self.retrieve_loss_curve(model_k, df_train, features)
|
||||||
pred_k = self.predict_sub(model_k, df_train, features)
|
pred_k = self.predict_sub(model_k, df_train, features)
|
||||||
pred_sub.iloc[:, k] = pred_k
|
pred_sub.iloc[:, k] = pred_k
|
||||||
pred_ensemble = pred_sub.iloc[:, : k + 1].mean(axis=1)
|
pred_ensemble = (pred_sub.iloc[:, : k + 1] * self.sub_weights[0 : k + 1]).sum(axis=1) / np.sum(
|
||||||
|
self.sub_weights[0 : k + 1]
|
||||||
|
)
|
||||||
loss_values = pd.Series(self.get_loss(y_train.values.squeeze(), pred_ensemble.values))
|
loss_values = pd.Series(self.get_loss(y_train.values.squeeze(), pred_ensemble.values))
|
||||||
|
|
||||||
if self.enable_sr:
|
if self.enable_sr:
|
||||||
@@ -159,8 +161,8 @@ class DEnsembleModel(Model, FeatureInt):
|
|||||||
h["bins"] = pd.cut(h["h_value"], self.bins_sr)
|
h["bins"] = pd.cut(h["h_value"], self.bins_sr)
|
||||||
h_avg = h.groupby("bins")["h_value"].mean()
|
h_avg = h.groupby("bins")["h_value"].mean()
|
||||||
weights = pd.Series(np.zeros(N, dtype=float))
|
weights = pd.Series(np.zeros(N, dtype=float))
|
||||||
for i_b, b in enumerate(h_avg.index):
|
for b in h_avg.index:
|
||||||
weights[h["bins"] == b] = 1.0 / (self.decay**k_th * h_avg[i_b] + 0.1)
|
weights[h["bins"] == b] = 1.0 / (self.decay**k_th * h_avg[b] + 0.1)
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
def feature_selection(self, df_train, loss_values):
|
def feature_selection(self, df_train, loss_values):
|
||||||
@@ -246,6 +248,7 @@ class DEnsembleModel(Model, FeatureInt):
|
|||||||
pd.Series(submodel.predict(x_test.loc[:, feat_sub].values), index=x_test.index)
|
pd.Series(submodel.predict(x_test.loc[:, feat_sub].values), index=x_test.index)
|
||||||
* self.sub_weights[i_sub]
|
* self.sub_weights[i_sub]
|
||||||
)
|
)
|
||||||
|
pred = pred / np.sum(self.sub_weights)
|
||||||
return pred
|
return pred
|
||||||
|
|
||||||
def predict_sub(self, submodel, df_data, features):
|
def predict_sub(self, submodel, df_data, features):
|
||||||
|
|||||||
@@ -104,9 +104,9 @@ class TopkDropoutStrategy(BaseSignalStrategy):
|
|||||||
only_tradable : bool
|
only_tradable : bool
|
||||||
will the strategy only consider the tradable stock when buying and selling.
|
will the strategy only consider the tradable stock when buying and selling.
|
||||||
if only_tradable:
|
if only_tradable:
|
||||||
strategy will make buy sell decision without checking the tradable state of the stock.
|
|
||||||
else:
|
|
||||||
strategy will make decision with the tradable state of the stock info and avoid buy and sell them.
|
strategy will make decision with the tradable state of the stock info and avoid buy and sell them.
|
||||||
|
else:
|
||||||
|
strategy will make buy sell decision without checking the tradable state of the stock.
|
||||||
"""
|
"""
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
self.topk = topk
|
self.topk = topk
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ except ValueError:
|
|||||||
|
|
||||||
np.seterr(invalid="ignore")
|
np.seterr(invalid="ignore")
|
||||||
|
|
||||||
|
|
||||||
#################### Element-Wise Operator ####################
|
#################### Element-Wise Operator ####################
|
||||||
|
|
||||||
|
|
||||||
@@ -62,6 +63,39 @@ class ElemOperator(ExpressionOps):
|
|||||||
return self.feature.get_extended_window_size()
|
return self.feature.get_extended_window_size()
|
||||||
|
|
||||||
|
|
||||||
|
class ChangeInstrument(ElemOperator):
|
||||||
|
"""Change Instrument Operator
|
||||||
|
In some case, one may want to change to another instrument when calculating, for example, to
|
||||||
|
calculate beta of a stock with respect to a market index.
|
||||||
|
This would require changing the calculation of features from the stock (original instrument) to
|
||||||
|
the index (reference instrument)
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
instrument: new instrument for which the downstream operations should be performed upon.
|
||||||
|
i.e., SH000300 (CSI300 index), or ^GPSC (SP500 index).
|
||||||
|
|
||||||
|
feature: the feature to be calculated for the new instrument.
|
||||||
|
Returns
|
||||||
|
----------
|
||||||
|
Expression
|
||||||
|
feature operation output
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, instrument, feature):
|
||||||
|
self.instrument = instrument
|
||||||
|
self.feature = feature
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return "{}('{}',{})".format(type(self).__name__, self.instrument, self.feature)
|
||||||
|
|
||||||
|
def load(self, instrument, start_index, end_index, *args):
|
||||||
|
# the first `instrument` is ignored
|
||||||
|
return super().load(self.instrument, start_index, end_index, *args)
|
||||||
|
|
||||||
|
def _load_internal(self, instrument, start_index, end_index, *args):
|
||||||
|
return self.feature.load(instrument, start_index, end_index, *args)
|
||||||
|
|
||||||
|
|
||||||
class NpElemOperator(ElemOperator):
|
class NpElemOperator(ElemOperator):
|
||||||
"""Numpy Element-wise Operator
|
"""Numpy Element-wise Operator
|
||||||
|
|
||||||
@@ -1535,6 +1569,7 @@ class TResample(ElemOperator):
|
|||||||
|
|
||||||
TOpsList = [TResample]
|
TOpsList = [TResample]
|
||||||
OpsList = [
|
OpsList = [
|
||||||
|
ChangeInstrument,
|
||||||
Rolling,
|
Rolling,
|
||||||
Ref,
|
Ref,
|
||||||
Max,
|
Max,
|
||||||
|
|||||||
@@ -102,11 +102,22 @@ class FileCalendarStorage(FileStorageMixin, CalendarStorage):
|
|||||||
self._freq_file_cache = freq
|
self._freq_file_cache = freq
|
||||||
return self._freq_file_cache
|
return self._freq_file_cache
|
||||||
|
|
||||||
def _read_calendar(self, skip_rows: int = 0, n_rows: int = None) -> List[CalVT]:
|
def _read_calendar(self) -> List[CalVT]:
|
||||||
|
# NOTE:
|
||||||
|
# if we want to accelerate partial reading calendar
|
||||||
|
# we can add parameters like `skip_rows: int = 0, n_rows: int = None` to the interface.
|
||||||
|
# Currently, it is not supported for the txt-based calendar
|
||||||
|
|
||||||
if not self.uri.exists():
|
if not self.uri.exists():
|
||||||
self._write_calendar(values=[])
|
self._write_calendar(values=[])
|
||||||
with self.uri.open("rb") as fp:
|
|
||||||
return [str(x) for x in np.loadtxt(fp, str, skiprows=skip_rows, max_rows=n_rows, encoding="utf-8")]
|
with self.uri.open("r") as fp:
|
||||||
|
res = []
|
||||||
|
for line in fp.readlines():
|
||||||
|
line = line.strip()
|
||||||
|
if len(line) > 0:
|
||||||
|
res.append(line)
|
||||||
|
return res
|
||||||
|
|
||||||
def _write_calendar(self, values: Iterable[CalVT], mode: str = "wb"):
|
def _write_calendar(self, values: Iterable[CalVT], mode: str = "wb"):
|
||||||
with self.uri.open(mode=mode) as fp:
|
with self.uri.open(mode=mode) as fp:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Generic, TYPE_CHECKING, TypeVar
|
from typing import Optional, TYPE_CHECKING, Generic, TypeVar
|
||||||
|
|
||||||
from qlib.typehint import final
|
from qlib.typehint import final
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ AuxInfoType = TypeVar("AuxInfoType")
|
|||||||
class AuxiliaryInfoCollector(Generic[StateType, AuxInfoType]):
|
class AuxiliaryInfoCollector(Generic[StateType, AuxInfoType]):
|
||||||
"""Override this class to collect customized auxiliary information from environment."""
|
"""Override this class to collect customized auxiliary information from environment."""
|
||||||
|
|
||||||
env: EnvWrapper | None = None
|
env: Optional[EnvWrapper] = None
|
||||||
|
|
||||||
@final
|
@final
|
||||||
def __call__(self, simulator_state: StateType) -> AuxInfoType:
|
def __call__(self, simulator_state: StateType) -> AuxInfoType:
|
||||||
|
|||||||
58
qlib/rl/data/exchange_wrapper.py
Normal file
58
qlib/rl/data/exchange_wrapper.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
# Copyright (c) Microsoft Corporation.
|
||||||
|
# Licensed under the MIT License.
|
||||||
|
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from qlib.backtest import Exchange, Order
|
||||||
|
from .pickle_styled import IntradayBacktestData
|
||||||
|
|
||||||
|
|
||||||
|
class QlibIntradayBacktestData(IntradayBacktestData):
|
||||||
|
"""Backtest data for Qlib simulator"""
|
||||||
|
|
||||||
|
def __init__(self, order: Order, exchange: Exchange, start_time: pd.Timestamp, end_time: pd.Timestamp) -> None:
|
||||||
|
super(QlibIntradayBacktestData, self).__init__()
|
||||||
|
self._order = order
|
||||||
|
self._exchange = exchange
|
||||||
|
self._start_time = start_time
|
||||||
|
self._end_time = end_time
|
||||||
|
|
||||||
|
self._deal_price = cast(
|
||||||
|
pd.Series,
|
||||||
|
self._exchange.get_deal_price(
|
||||||
|
self._order.stock_id,
|
||||||
|
self._start_time,
|
||||||
|
self._end_time,
|
||||||
|
direction=self._order.direction,
|
||||||
|
method=None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self._volume = cast(
|
||||||
|
pd.Series,
|
||||||
|
self._exchange.get_volume(
|
||||||
|
self._order.stock_id,
|
||||||
|
self._start_time,
|
||||||
|
self._end_time,
|
||||||
|
method=None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return (
|
||||||
|
f"Order: {self._order}, Exchange: {self._exchange}, "
|
||||||
|
f"Start time: {self._start_time}, End time: {self._end_time}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def __len__(self) -> int:
|
||||||
|
return len(self._deal_price)
|
||||||
|
|
||||||
|
def get_deal_price(self) -> pd.Series:
|
||||||
|
return self._deal_price
|
||||||
|
|
||||||
|
def get_volume(self) -> pd.Series:
|
||||||
|
return self._volume
|
||||||
|
|
||||||
|
def get_time_index(self) -> pd.DatetimeIndex:
|
||||||
|
return pd.DatetimeIndex([e[1] for e in list(self._exchange.quote_df.index)])
|
||||||
@@ -19,19 +19,19 @@ This file shows resemblence to qlib.backtest.high_performance_ds. We might merge
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from abc import abstractmethod
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from typing import List, Sequence, cast
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import List, Sequence, cast
|
||||||
|
|
||||||
import cachetools
|
import cachetools
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from cachetools.keys import hashkey
|
from cachetools.keys import hashkey
|
||||||
|
|
||||||
from qlib.backtest.decision import OrderDir, Order
|
from qlib.backtest.decision import Order, OrderDir
|
||||||
from qlib.typehint import Literal
|
from qlib.typehint import Literal
|
||||||
|
|
||||||
|
|
||||||
DealPriceType = Literal["bid_or_ask", "bid_or_ask_fill", "close"]
|
DealPriceType = Literal["bid_or_ask", "bid_or_ask_fill", "close"]
|
||||||
"""Several ad-hoc deal price.
|
"""Several ad-hoc deal price.
|
||||||
``bid_or_ask``: If sell, use column ``$bid0``; if buy, use column ``$ask0``.
|
``bid_or_ask``: If sell, use column ``$bid0``; if buy, use column ``$ask0``.
|
||||||
@@ -40,7 +40,7 @@ DealPriceType = Literal["bid_or_ask", "bid_or_ask_fill", "close"]
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def _infer_processed_data_column_names(shape: int) -> list[str]:
|
def _infer_processed_data_column_names(shape: int) -> List[str]:
|
||||||
if shape == 16:
|
if shape == 16:
|
||||||
return [
|
return [
|
||||||
"$open",
|
"$open",
|
||||||
@@ -87,7 +87,36 @@ def _read_pickle(filename_without_suffix: Path) -> pd.DataFrame:
|
|||||||
|
|
||||||
|
|
||||||
class IntradayBacktestData:
|
class IntradayBacktestData:
|
||||||
"""Raw market data that is often used in backtesting (thus called BacktestData)."""
|
"""
|
||||||
|
Raw market data that is often used in backtesting (thus called BacktestData).
|
||||||
|
|
||||||
|
Base class for all types of backtest data. Currently, each type of simulator has its corresponding backtest
|
||||||
|
data type.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def __len__(self) -> int:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_deal_price(self) -> pd.Series:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_volume(self) -> pd.Series:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_time_index(self) -> pd.DatetimeIndex:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
|
class SimpleIntradayBacktestData(IntradayBacktestData):
|
||||||
|
"""Backtest data for simple simulator"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -95,8 +124,10 @@ class IntradayBacktestData:
|
|||||||
stock_id: str,
|
stock_id: str,
|
||||||
date: pd.Timestamp,
|
date: pd.Timestamp,
|
||||||
deal_price: DealPriceType = "close",
|
deal_price: DealPriceType = "close",
|
||||||
order_dir: int | None = None,
|
order_dir: int = None,
|
||||||
):
|
) -> None:
|
||||||
|
super(SimpleIntradayBacktestData, self).__init__()
|
||||||
|
|
||||||
backtest = _read_pickle(data_dir / stock_id)
|
backtest = _read_pickle(data_dir / stock_id)
|
||||||
backtest = backtest.loc[pd.IndexSlice[stock_id, :, date]]
|
backtest = backtest.loc[pd.IndexSlice[stock_id, :, date]]
|
||||||
|
|
||||||
@@ -105,13 +136,13 @@ class IntradayBacktestData:
|
|||||||
|
|
||||||
self.data: pd.DataFrame = backtest
|
self.data: pd.DataFrame = backtest
|
||||||
self.deal_price_type: DealPriceType = deal_price
|
self.deal_price_type: DealPriceType = deal_price
|
||||||
self.order_dir: int | None = order_dir
|
self.order_dir = order_dir
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self) -> str:
|
||||||
with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"):
|
with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"):
|
||||||
return f"{self.__class__.__name__}({self.data})"
|
return f"{self.__class__.__name__}({self.data})"
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self) -> int:
|
||||||
return len(self.data)
|
return len(self.data)
|
||||||
|
|
||||||
def get_deal_price(self) -> pd.Series:
|
def get_deal_price(self) -> pd.Series:
|
||||||
@@ -162,7 +193,14 @@ class IntradayProcessedData:
|
|||||||
"""Processed data for "yesterday".
|
"""Processed data for "yesterday".
|
||||||
Number of records must be ``time_length``, and columns must be ``feature_dim``."""
|
Number of records must be ``time_length``, and columns must be ``feature_dim``."""
|
||||||
|
|
||||||
def __init__(self, data_dir: Path, stock_id: str, date: pd.Timestamp, feature_dim: int, time_index: pd.Index):
|
def __init__(
|
||||||
|
self,
|
||||||
|
data_dir: Path,
|
||||||
|
stock_id: str,
|
||||||
|
date: pd.Timestamp,
|
||||||
|
feature_dim: int,
|
||||||
|
time_index: pd.Index,
|
||||||
|
) -> None:
|
||||||
proc = _read_pickle(data_dir / stock_id)
|
proc = _read_pickle(data_dir / stock_id)
|
||||||
# We have to infer the names here because,
|
# We have to infer the names here because,
|
||||||
# unfortunately they are not included in the original data.
|
# unfortunately they are not included in the original data.
|
||||||
@@ -190,16 +228,20 @@ class IntradayProcessedData:
|
|||||||
assert len(self.today.columns) == len(self.yesterday.columns) == feature_dim
|
assert len(self.today.columns) == len(self.yesterday.columns) == feature_dim
|
||||||
assert len(self.today) == len(self.yesterday) == time_length
|
assert len(self.today) == len(self.yesterday) == time_length
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self) -> str:
|
||||||
with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"):
|
with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"):
|
||||||
return f"{self.__class__.__name__}({self.today}, {self.yesterday})"
|
return f"{self.__class__.__name__}({self.today}, {self.yesterday})"
|
||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=100) # 100 * 50K = 5MB
|
@lru_cache(maxsize=100) # 100 * 50K = 5MB
|
||||||
def load_intraday_backtest_data(
|
def load_simple_intraday_backtest_data(
|
||||||
data_dir: Path, stock_id: str, date: pd.Timestamp, deal_price: DealPriceType = "close", order_dir: int | None = None
|
data_dir: Path,
|
||||||
) -> IntradayBacktestData:
|
stock_id: str,
|
||||||
return IntradayBacktestData(data_dir, stock_id, date, deal_price, order_dir)
|
date: pd.Timestamp,
|
||||||
|
deal_price: DealPriceType = "close",
|
||||||
|
order_dir: int = None,
|
||||||
|
) -> SimpleIntradayBacktestData:
|
||||||
|
return SimpleIntradayBacktestData(data_dir, stock_id, date, deal_price, order_dir)
|
||||||
|
|
||||||
|
|
||||||
@cachetools.cached( # type: ignore
|
@cachetools.cached( # type: ignore
|
||||||
@@ -207,13 +249,19 @@ def load_intraday_backtest_data(
|
|||||||
key=lambda data_dir, stock_id, date, _, __: hashkey(data_dir, stock_id, date),
|
key=lambda data_dir, stock_id, date, _, __: hashkey(data_dir, stock_id, date),
|
||||||
)
|
)
|
||||||
def load_intraday_processed_data(
|
def load_intraday_processed_data(
|
||||||
data_dir: Path, stock_id: str, date: pd.Timestamp, feature_dim: int, time_index: pd.Index
|
data_dir: Path,
|
||||||
|
stock_id: str,
|
||||||
|
date: pd.Timestamp,
|
||||||
|
feature_dim: int,
|
||||||
|
time_index: pd.Index,
|
||||||
) -> IntradayProcessedData:
|
) -> IntradayProcessedData:
|
||||||
return IntradayProcessedData(data_dir, stock_id, date, feature_dim, time_index)
|
return IntradayProcessedData(data_dir, stock_id, date, feature_dim, time_index)
|
||||||
|
|
||||||
|
|
||||||
def load_orders(
|
def load_orders(
|
||||||
order_path: Path, start_time: pd.Timestamp | None = None, end_time: pd.Timestamp | None = None
|
order_path: Path,
|
||||||
|
start_time: pd.Timestamp = None,
|
||||||
|
end_time: pd.Timestamp = None,
|
||||||
) -> Sequence[Order]:
|
) -> Sequence[Order]:
|
||||||
"""Load orders, and set start time and end time for the orders."""
|
"""Load orders, and set start time and end time for the orders."""
|
||||||
|
|
||||||
@@ -251,7 +299,7 @@ def load_orders(
|
|||||||
OrderDir(int(row["order_type"])),
|
OrderDir(int(row["order_type"])),
|
||||||
row["datetime"].replace(hour=start_time.hour, minute=start_time.minute, second=start_time.second),
|
row["datetime"].replace(hour=start_time.hour, minute=start_time.minute, second=start_time.second),
|
||||||
row["datetime"].replace(hour=end_time.hour, minute=end_time.minute, second=end_time.second),
|
row["datetime"].replace(hour=end_time.hour, minute=end_time.minute, second=end_time.second),
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
return orders
|
return orders
|
||||||
|
|||||||
4
qlib/rl/from_neutrader/__init__.py
Normal file
4
qlib/rl/from_neutrader/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# Copyright (c) Microsoft Corporation.
|
||||||
|
# Licensed under the MIT License.
|
||||||
|
|
||||||
|
# TODO: find a better way to organize contents under this module.
|
||||||
20
qlib/rl/from_neutrader/config.py
Normal file
20
qlib/rl/from_neutrader/config.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
# Copyright (c) Microsoft Corporation.
|
||||||
|
# Licensed under the MIT License.
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional, Tuple, Union
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: In the future we should merge the dataclass-based config with Qlib's dict-based config.
|
||||||
|
@dataclass
|
||||||
|
class ExchangeConfig:
|
||||||
|
limit_threshold: Union[float, Tuple[str, str]]
|
||||||
|
deal_price: Union[str, Tuple[str, str]]
|
||||||
|
volume_threshold: dict
|
||||||
|
open_cost: float = 0.0005
|
||||||
|
close_cost: float = 0.0015
|
||||||
|
min_cost: float = 5.0
|
||||||
|
trade_unit: Optional[float] = 100.0
|
||||||
|
cash_limit: Optional[Union[Path, float]] = None
|
||||||
|
generate_report: bool = False
|
||||||
109
qlib/rl/from_neutrader/feature.py
Normal file
109
qlib/rl/from_neutrader/feature.py
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
# Copyright (c) Microsoft Corporation.
|
||||||
|
# Licensed under the MIT License.
|
||||||
|
|
||||||
|
import collections
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
import qlib
|
||||||
|
from qlib.config import REG_CN
|
||||||
|
from qlib.contrib.ops.high_freq import BFillNan, Cut, Date, DayCumsum, DayLast, FFillNan, IsInf, IsNull, Select
|
||||||
|
from qlib.data.dataset import DatasetH
|
||||||
|
|
||||||
|
|
||||||
|
class LRUCache:
|
||||||
|
def __init__(self, pool_size: int = 200):
|
||||||
|
self.pool_size = pool_size
|
||||||
|
self.contents: dict = {}
|
||||||
|
self.keys: collections.deque = collections.deque()
|
||||||
|
|
||||||
|
def put(self, key, item):
|
||||||
|
if self.has(key):
|
||||||
|
self.keys.remove(key)
|
||||||
|
self.keys.append(key)
|
||||||
|
self.contents[key] = item
|
||||||
|
while len(self.contents) > self.pool_size:
|
||||||
|
self.contents.pop(self.keys.popleft())
|
||||||
|
|
||||||
|
def get(self, key):
|
||||||
|
return self.contents[key]
|
||||||
|
|
||||||
|
def has(self, key):
|
||||||
|
return key in self.contents
|
||||||
|
|
||||||
|
|
||||||
|
class DataWrapper:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
feature_dataset: DatasetH,
|
||||||
|
backtest_dataset: DatasetH,
|
||||||
|
columns_today: List[str],
|
||||||
|
columns_yesterday: List[str],
|
||||||
|
_internal: bool = False,
|
||||||
|
):
|
||||||
|
assert _internal, "Init function of data wrapper is for internal use only."
|
||||||
|
|
||||||
|
self.feature_dataset = feature_dataset
|
||||||
|
self.backtest_dataset = backtest_dataset
|
||||||
|
self.columns_today = columns_today
|
||||||
|
self.columns_yesterday = columns_yesterday
|
||||||
|
|
||||||
|
# TODO: We might have the chance to merge them.
|
||||||
|
self.feature_cache = LRUCache()
|
||||||
|
self.backtest_cache = LRUCache()
|
||||||
|
|
||||||
|
def get(self, stock_id: str, date: pd.Timestamp, backtest: bool = False) -> pd.DataFrame:
|
||||||
|
start_time, end_time = date.replace(hour=0, minute=0, second=0), date.replace(hour=23, minute=59, second=59)
|
||||||
|
|
||||||
|
if backtest:
|
||||||
|
dataset = self.backtest_dataset
|
||||||
|
cache = self.backtest_cache
|
||||||
|
else:
|
||||||
|
dataset = self.feature_dataset
|
||||||
|
cache = self.feature_cache
|
||||||
|
|
||||||
|
if cache.has((start_time, end_time, stock_id)):
|
||||||
|
return cache.get((start_time, end_time, stock_id))
|
||||||
|
data = dataset.handler.fetch(pd.IndexSlice[stock_id, start_time:end_time], level=None)
|
||||||
|
cache.put((start_time, end_time, stock_id), data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def init_qlib(config: dict, part: Optional[str] = None) -> None:
|
||||||
|
provider_uri_map = {
|
||||||
|
"day": config["provider_uri_day"].as_posix(),
|
||||||
|
"1min": config["provider_uri_1min"].as_posix(),
|
||||||
|
}
|
||||||
|
qlib.init(
|
||||||
|
region=REG_CN,
|
||||||
|
auto_mount=False,
|
||||||
|
custom_ops=[DayLast, FFillNan, BFillNan, Date, Select, IsNull, IsInf, Cut, DayCumsum],
|
||||||
|
expression_cache=None,
|
||||||
|
calendar_provider={
|
||||||
|
"class": "LocalCalendarProvider",
|
||||||
|
"module_path": "qlib.data.data",
|
||||||
|
"kwargs": {
|
||||||
|
"backend": {
|
||||||
|
"class": "FileCalendarStorage",
|
||||||
|
"module_path": "qlib.data.storage.file_storage",
|
||||||
|
"kwargs": {"provider_uri_map": provider_uri_map},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
feature_provider={
|
||||||
|
"class": "LocalFeatureProvider",
|
||||||
|
"module_path": "qlib.data.data",
|
||||||
|
"kwargs": {
|
||||||
|
"backend": {
|
||||||
|
"class": "FileFeatureStorage",
|
||||||
|
"module_path": "qlib.data.storage.file_storage",
|
||||||
|
"kwargs": {"provider_uri_map": provider_uri_map},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
provider_uri=provider_uri_map,
|
||||||
|
kernels=1,
|
||||||
|
redis_port=-1,
|
||||||
|
clear_mem_cache=False, # init_qlib will be called for multiple times. Keep the cache for improving performance
|
||||||
|
)
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import TYPE_CHECKING, TypeVar, Generic, Any
|
from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from qlib.typehint import final
|
from qlib.typehint import final
|
||||||
|
|
||||||
from .simulator import StateType, ActType
|
from .simulator import ActType, StateType
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from .utils.env_wrapper import EnvWrapper
|
from .utils.env_wrapper import EnvWrapper
|
||||||
@@ -40,7 +40,7 @@ class Interpreter:
|
|||||||
class StateInterpreter(Generic[StateType, ObsType], Interpreter):
|
class StateInterpreter(Generic[StateType, ObsType], Interpreter):
|
||||||
"""State Interpreter that interpret execution result of qlib executor into rl env state"""
|
"""State Interpreter that interpret execution result of qlib executor into rl env state"""
|
||||||
|
|
||||||
env: EnvWrapper | None = None
|
env: Optional[EnvWrapper] = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def observation_space(self) -> gym.Space:
|
def observation_space(self) -> gym.Space:
|
||||||
@@ -74,7 +74,7 @@ class StateInterpreter(Generic[StateType, ObsType], Interpreter):
|
|||||||
class ActionInterpreter(Generic[StateType, PolicyActType, ActType], Interpreter):
|
class ActionInterpreter(Generic[StateType, PolicyActType, ActType], Interpreter):
|
||||||
"""Action Interpreter that interpret rl agent action into qlib orders"""
|
"""Action Interpreter that interpret rl agent action into qlib orders"""
|
||||||
|
|
||||||
env: "EnvWrapper" | None = None
|
env: Optional[EnvWrapper] = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def action_space(self) -> gym.Space:
|
def action_space(self) -> gym.Space:
|
||||||
@@ -141,10 +141,10 @@ def _gym_space_contains(space: gym.Space, x: Any) -> None:
|
|||||||
|
|
||||||
|
|
||||||
class GymSpaceValidationError(Exception):
|
class GymSpaceValidationError(Exception):
|
||||||
def __init__(self, message: str, space: gym.Space, x: Any):
|
def __init__(self, message: str, space: gym.Space, x: Any) -> None:
|
||||||
self.message = message
|
self.message = message
|
||||||
self.space = space
|
self.space = space
|
||||||
self.x = x
|
self.x = x
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self) -> str:
|
||||||
return f"{self.message}\n Space: {self.space}\n Sample: {self.x}"
|
return f"{self.message}\n Space: {self.space}\n Sample: {self.x}"
|
||||||
|
|||||||
@@ -5,15 +5,15 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import math
|
import math
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, cast
|
from typing import Any, List, cast
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from gym import spaces
|
from gym import spaces
|
||||||
|
|
||||||
from qlib.constant import EPS
|
from qlib.constant import EPS
|
||||||
from qlib.rl.interpreter import StateInterpreter, ActionInterpreter
|
|
||||||
from qlib.rl.data import pickle_styled
|
from qlib.rl.data import pickle_styled
|
||||||
|
from qlib.rl.interpreter import ActionInterpreter, StateInterpreter
|
||||||
from qlib.typehint import TypedDict
|
from qlib.typehint import TypedDict
|
||||||
|
|
||||||
from .simulator_simple import SAOEState
|
from .simulator_simple import SAOEState
|
||||||
@@ -99,18 +99,18 @@ class FullHistoryStateInterpreter(StateInterpreter[SAOEState, FullHistoryObs]):
|
|||||||
"data_processed": self._mask_future_info(processed.today, state.cur_time),
|
"data_processed": self._mask_future_info(processed.today, state.cur_time),
|
||||||
"data_processed_prev": processed.yesterday,
|
"data_processed_prev": processed.yesterday,
|
||||||
"acquiring": state.order.direction == state.order.BUY,
|
"acquiring": state.order.direction == state.order.BUY,
|
||||||
"cur_tick": min(np.sum(state.ticks_index < state.cur_time), self.data_ticks - 1),
|
"cur_tick": min(int(np.sum(state.ticks_index < state.cur_time)), self.data_ticks - 1),
|
||||||
"cur_step": min(self.env.status["cur_step"], self.max_step - 1),
|
"cur_step": min(self.env.status["cur_step"], self.max_step - 1),
|
||||||
"num_step": self.max_step,
|
"num_step": self.max_step,
|
||||||
"target": state.order.amount,
|
"target": state.order.amount,
|
||||||
"position": state.position,
|
"position": state.position,
|
||||||
"position_history": position_history[: self.max_step],
|
"position_history": position_history[: self.max_step],
|
||||||
}
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def observation_space(self):
|
def observation_space(self) -> spaces.Dict:
|
||||||
space = {
|
space = {
|
||||||
"data_processed": spaces.Box(-np.inf, np.inf, shape=(self.data_ticks, self.data_dim)),
|
"data_processed": spaces.Box(-np.inf, np.inf, shape=(self.data_ticks, self.data_dim)),
|
||||||
"data_processed_prev": spaces.Box(-np.inf, np.inf, shape=(self.data_ticks, self.data_dim)),
|
"data_processed_prev": spaces.Box(-np.inf, np.inf, shape=(self.data_ticks, self.data_dim)),
|
||||||
@@ -147,11 +147,11 @@ class CurrentStepStateInterpreter(StateInterpreter[SAOEState, CurrentStateObs]):
|
|||||||
The key list is not full. You can add more if more information is needed by your policy.
|
The key list is not full. You can add more if more information is needed by your policy.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, max_step: int):
|
def __init__(self, max_step: int) -> None:
|
||||||
self.max_step = max_step
|
self.max_step = max_step
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def observation_space(self):
|
def observation_space(self) -> spaces.Dict:
|
||||||
space = {
|
space = {
|
||||||
"acquiring": spaces.Discrete(2),
|
"acquiring": spaces.Discrete(2),
|
||||||
"cur_step": spaces.Box(0, self.max_step - 1, shape=(), dtype=np.int32),
|
"cur_step": spaces.Box(0, self.max_step - 1, shape=(), dtype=np.int32),
|
||||||
@@ -165,13 +165,11 @@ class CurrentStepStateInterpreter(StateInterpreter[SAOEState, CurrentStateObs]):
|
|||||||
assert self.env is not None
|
assert self.env is not None
|
||||||
assert self.env.status["cur_step"] <= self.max_step
|
assert self.env.status["cur_step"] <= self.max_step
|
||||||
obs = CurrentStateObs(
|
obs = CurrentStateObs(
|
||||||
{
|
acquiring=state.order.direction == state.order.BUY,
|
||||||
"acquiring": state.order.direction == state.order.BUY,
|
cur_step=self.env.status["cur_step"],
|
||||||
"cur_step": self.env.status["cur_step"],
|
num_step=self.max_step,
|
||||||
"num_step": self.max_step,
|
target=state.order.amount,
|
||||||
"target": state.order.amount,
|
position=state.position,
|
||||||
"position": state.position,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
return obs
|
return obs
|
||||||
|
|
||||||
@@ -188,7 +186,7 @@ class CategoricalActionInterpreter(ActionInterpreter[SAOEState, int, float]):
|
|||||||
i.e., $[0, 1/n, 2/n, \\ldots, n/n]$.
|
i.e., $[0, 1/n, 2/n, \\ldots, n/n]$.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, values: int | list[float]):
|
def __init__(self, values: int | List[float]) -> None:
|
||||||
if isinstance(values, int):
|
if isinstance(values, int):
|
||||||
values = [i / values for i in range(0, values + 1)]
|
values = [i / values for i in range(0, values + 1)]
|
||||||
self.action_values = values
|
self.action_values = values
|
||||||
@@ -203,7 +201,7 @@ class CategoricalActionInterpreter(ActionInterpreter[SAOEState, int, float]):
|
|||||||
|
|
||||||
|
|
||||||
class TwapRelativeActionInterpreter(ActionInterpreter[SAOEState, float, float]):
|
class TwapRelativeActionInterpreter(ActionInterpreter[SAOEState, float, float]):
|
||||||
"""Convert a continous ratio to deal amount.
|
"""Convert a continuous ratio to deal amount.
|
||||||
|
|
||||||
The ratio is relative to TWAP on the remainder of the day.
|
The ratio is relative to TWAP on the remainder of the day.
|
||||||
For example, there are 5 steps left, and the left position is 300.
|
For example, there are 5 steps left, and the left position is 300.
|
||||||
|
|||||||
@@ -3,13 +3,14 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import cast
|
from typing import List, Tuple, cast
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
from tianshou.data import Batch
|
from tianshou.data import Batch
|
||||||
|
|
||||||
from qlib.typehint import Literal
|
from qlib.typehint import Literal
|
||||||
|
|
||||||
from .interpreter import FullHistoryObs
|
from .interpreter import FullHistoryObs
|
||||||
|
|
||||||
__all__ = ["Recurrent"]
|
__all__ = ["Recurrent"]
|
||||||
@@ -18,7 +19,7 @@ __all__ = ["Recurrent"]
|
|||||||
class Recurrent(nn.Module):
|
class Recurrent(nn.Module):
|
||||||
"""The network architecture proposed in `OPD <https://seqml.github.io/opd/opd_aaai21_supplement.pdf>`_.
|
"""The network architecture proposed in `OPD <https://seqml.github.io/opd/opd_aaai21_supplement.pdf>`_.
|
||||||
|
|
||||||
At every timestep the input of policy network is divided into two parts,
|
At every time step the input of policy network is divided into two parts,
|
||||||
the public variables and the private variables. which are handled by ``raw_rnn``
|
the public variables and the private variables. which are handled by ``raw_rnn``
|
||||||
and ``pri_rnn`` in this network, respectively.
|
and ``pri_rnn`` in this network, respectively.
|
||||||
|
|
||||||
@@ -33,7 +34,7 @@ class Recurrent(nn.Module):
|
|||||||
output_dim: int = 32,
|
output_dim: int = 32,
|
||||||
rnn_type: Literal["rnn", "lstm", "gru"] = "gru",
|
rnn_type: Literal["rnn", "lstm", "gru"] = "gru",
|
||||||
rnn_num_layers: int = 1,
|
rnn_num_layers: int = 1,
|
||||||
):
|
) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.hidden_dim = hidden_dim
|
self.hidden_dim = hidden_dim
|
||||||
@@ -62,10 +63,10 @@ class Recurrent(nn.Module):
|
|||||||
nn.ReLU(),
|
nn.ReLU(),
|
||||||
)
|
)
|
||||||
|
|
||||||
def _init_extra_branches(self):
|
def _init_extra_branches(self) -> None:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def _source_features(self, obs: FullHistoryObs, device: torch.device) -> tuple[list[torch.Tensor], torch.Tensor]:
|
def _source_features(self, obs: FullHistoryObs, device: torch.device) -> Tuple[List[torch.Tensor], torch.Tensor]:
|
||||||
bs, _, data_dim = obs["data_processed"].size()
|
bs, _, data_dim = obs["data_processed"].size()
|
||||||
data = torch.cat((torch.zeros(bs, 1, data_dim, device=device), obs["data_processed"]), 1)
|
data = torch.cat((torch.zeros(bs, 1, data_dim, device=device), obs["data_processed"]), 1)
|
||||||
cur_step = obs["cur_step"].long()
|
cur_step = obs["cur_step"].long()
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
# Copyright (c) Microsoft Corporation.
|
# Copyright (c) Microsoft Corporation.
|
||||||
# Licensed under the MIT License.
|
# Licensed under the MIT License.
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional, cast
|
from typing import Any, Dict, Generator, Iterable, Optional, Tuple, cast
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import gym
|
import gym
|
||||||
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
from gym.spaces import Discrete
|
from gym.spaces import Discrete
|
||||||
from tianshou.data import Batch, to_torch
|
from tianshou.data import Batch, ReplayBuffer, to_torch
|
||||||
from tianshou.policy import PPOPolicy, BasePolicy
|
from tianshou.policy import BasePolicy, PPOPolicy
|
||||||
|
|
||||||
__all__ = ["AllOne", "PPO"]
|
__all__ = ["AllOne", "PPO"]
|
||||||
|
|
||||||
@@ -18,29 +19,39 @@ __all__ = ["AllOne", "PPO"]
|
|||||||
# baselines #
|
# baselines #
|
||||||
|
|
||||||
|
|
||||||
class NonlearnablePolicy(BasePolicy):
|
class NonLearnablePolicy(BasePolicy):
|
||||||
"""Tianshou's BasePolicy with empty ``learn`` and ``process_fn``.
|
"""Tianshou's BasePolicy with empty ``learn`` and ``process_fn``.
|
||||||
|
|
||||||
This could be moved outside in future.
|
This could be moved outside in future.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, obs_space: gym.Space, action_space: gym.Space):
|
def __init__(self, obs_space: gym.Space, action_space: gym.Space) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
def learn(self, batch, batch_size, repeat):
|
def learn(self, batch: Batch, **kwargs: Any) -> Dict[str, Any]:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def process_fn(self, batch, buffer, indice):
|
def process_fn(
|
||||||
|
self,
|
||||||
|
batch: Batch,
|
||||||
|
buffer: ReplayBuffer,
|
||||||
|
indices: np.ndarray,
|
||||||
|
) -> Batch:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class AllOne(NonlearnablePolicy):
|
class AllOne(NonLearnablePolicy):
|
||||||
"""Forward returns a batch full of 1.
|
"""Forward returns a batch full of 1.
|
||||||
|
|
||||||
Useful when implementing some baselines (e.g., TWAP).
|
Useful when implementing some baselines (e.g., TWAP).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def forward(self, batch, state=None, **kwargs):
|
def forward(
|
||||||
|
self,
|
||||||
|
batch: Batch,
|
||||||
|
state: dict | Batch | np.ndarray = None,
|
||||||
|
**kwargs: Any,
|
||||||
|
) -> Batch:
|
||||||
return Batch(act=np.full(len(batch), 1.0), state=state)
|
return Batch(act=np.full(len(batch), 1.0), state=state)
|
||||||
|
|
||||||
|
|
||||||
@@ -48,24 +59,34 @@ class AllOne(NonlearnablePolicy):
|
|||||||
|
|
||||||
|
|
||||||
class PPOActor(nn.Module):
|
class PPOActor(nn.Module):
|
||||||
def __init__(self, extractor: nn.Module, action_dim: int):
|
def __init__(self, extractor: nn.Module, action_dim: int) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.extractor = extractor
|
self.extractor = extractor
|
||||||
self.layer_out = nn.Sequential(nn.Linear(cast(int, extractor.output_dim), action_dim), nn.Softmax(dim=-1))
|
self.layer_out = nn.Sequential(nn.Linear(cast(int, extractor.output_dim), action_dim), nn.Softmax(dim=-1))
|
||||||
|
|
||||||
def forward(self, obs, state=None, info={}):
|
def forward(
|
||||||
|
self,
|
||||||
|
obs: torch.Tensor,
|
||||||
|
state: torch.Tensor = None,
|
||||||
|
info: dict = {},
|
||||||
|
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
||||||
feature = self.extractor(to_torch(obs, device=auto_device(self)))
|
feature = self.extractor(to_torch(obs, device=auto_device(self)))
|
||||||
out = self.layer_out(feature)
|
out = self.layer_out(feature)
|
||||||
return out, state
|
return out, state
|
||||||
|
|
||||||
|
|
||||||
class PPOCritic(nn.Module):
|
class PPOCritic(nn.Module):
|
||||||
def __init__(self, extractor: nn.Module):
|
def __init__(self, extractor: nn.Module) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.extractor = extractor
|
self.extractor = extractor
|
||||||
self.value_out = nn.Linear(cast(int, extractor.output_dim), 1)
|
self.value_out = nn.Linear(cast(int, extractor.output_dim), 1)
|
||||||
|
|
||||||
def forward(self, obs, state=None, info={}):
|
def forward(
|
||||||
|
self,
|
||||||
|
obs: torch.Tensor,
|
||||||
|
state: torch.Tensor = None,
|
||||||
|
info: dict = {},
|
||||||
|
) -> torch.Tensor:
|
||||||
feature = self.extractor(to_torch(obs, device=auto_device(self)))
|
feature = self.extractor(to_torch(obs, device=auto_device(self)))
|
||||||
return self.value_out(feature).squeeze(dim=-1)
|
return self.value_out(feature).squeeze(dim=-1)
|
||||||
|
|
||||||
@@ -93,18 +114,20 @@ class PPO(PPOPolicy):
|
|||||||
max_grad_norm: float = 100.0,
|
max_grad_norm: float = 100.0,
|
||||||
reward_normalization: bool = True,
|
reward_normalization: bool = True,
|
||||||
eps_clip: float = 0.3,
|
eps_clip: float = 0.3,
|
||||||
value_clip: float = True,
|
value_clip: bool = True,
|
||||||
vf_coef: float = 1.0,
|
vf_coef: float = 1.0,
|
||||||
gae_lambda: float = 1.0,
|
gae_lambda: float = 1.0,
|
||||||
max_batchsize: int = 256,
|
max_batch_size: int = 256,
|
||||||
deterministic_eval: bool = True,
|
deterministic_eval: bool = True,
|
||||||
weight_file: Optional[Path] = None,
|
weight_file: Optional[Path] = None,
|
||||||
):
|
) -> None:
|
||||||
assert isinstance(action_space, Discrete)
|
assert isinstance(action_space, Discrete)
|
||||||
actor = PPOActor(network, action_space.n)
|
actor = PPOActor(network, action_space.n)
|
||||||
critic = PPOCritic(network)
|
critic = PPOCritic(network)
|
||||||
optimizer = torch.optim.Adam(
|
optimizer = torch.optim.Adam(
|
||||||
chain_dedup(actor.parameters(), critic.parameters()), lr=lr, weight_decay=weight_decay
|
chain_dedup(actor.parameters(), critic.parameters()),
|
||||||
|
lr=lr,
|
||||||
|
weight_decay=weight_decay,
|
||||||
)
|
)
|
||||||
super().__init__(
|
super().__init__(
|
||||||
actor,
|
actor,
|
||||||
@@ -118,7 +141,7 @@ class PPO(PPOPolicy):
|
|||||||
value_clip=value_clip,
|
value_clip=value_clip,
|
||||||
vf_coef=vf_coef,
|
vf_coef=vf_coef,
|
||||||
gae_lambda=gae_lambda,
|
gae_lambda=gae_lambda,
|
||||||
max_batchsize=max_batchsize,
|
max_batchsize=max_batch_size,
|
||||||
deterministic_eval=deterministic_eval,
|
deterministic_eval=deterministic_eval,
|
||||||
observation_space=obs_space,
|
observation_space=obs_space,
|
||||||
action_space=action_space,
|
action_space=action_space,
|
||||||
@@ -136,7 +159,7 @@ def auto_device(module: nn.Module) -> torch.device:
|
|||||||
return torch.device("cpu") # fallback to cpu
|
return torch.device("cpu") # fallback to cpu
|
||||||
|
|
||||||
|
|
||||||
def load_weight(policy, path):
|
def load_weight(policy: nn.Module, path: Path) -> None:
|
||||||
assert isinstance(policy, nn.Module), "Policy has to be an nn.Module to load weight."
|
assert isinstance(policy, nn.Module), "Policy has to be an nn.Module to load weight."
|
||||||
loaded_weight = torch.load(path, map_location="cpu")
|
loaded_weight = torch.load(path, map_location="cpu")
|
||||||
try:
|
try:
|
||||||
@@ -149,7 +172,7 @@ def load_weight(policy, path):
|
|||||||
policy.load_state_dict(loaded_weight)
|
policy.load_state_dict(loaded_weight)
|
||||||
|
|
||||||
|
|
||||||
def chain_dedup(*iterables):
|
def chain_dedup(*iterables: Iterable) -> Generator[Any, None, None]:
|
||||||
seen = set()
|
seen = set()
|
||||||
for iterable in iterables:
|
for iterable in iterables:
|
||||||
for i in iterable:
|
for i in iterable:
|
||||||
|
|||||||
@@ -6,9 +6,10 @@ from __future__ import annotations
|
|||||||
from typing import cast
|
from typing import cast
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from qlib.rl.reward import Reward
|
from qlib.rl.reward import Reward
|
||||||
|
|
||||||
from .simulator_simple import SAOEState, SAOEMetrics
|
from .simulator_simple import SAOEMetrics, SAOEState
|
||||||
|
|
||||||
__all__ = ["PAPenaltyReward"]
|
__all__ = ["PAPenaltyReward"]
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,424 @@
|
|||||||
# Copyright (c) Microsoft Corporation.
|
# Copyright (c) Microsoft Corporation.
|
||||||
# Licensed under the MIT License.
|
# Licensed under the MIT License.
|
||||||
|
|
||||||
"""Placeholder for qlib-based simulator."""
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Callable, cast, Generator, List, Optional, Tuple
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from qlib.backtest.decision import BaseTradeDecision, Order, OrderHelper, TradeDecisionWO, TradeRange, TradeRangeByTime
|
||||||
|
from qlib.backtest.executor import BaseExecutor, NestedExecutor
|
||||||
|
from qlib.backtest.utils import CommonInfrastructure
|
||||||
|
from qlib.constant import EPS
|
||||||
|
from qlib.rl.data.exchange_wrapper import QlibIntradayBacktestData
|
||||||
|
from qlib.rl.from_neutrader.config import ExchangeConfig
|
||||||
|
from qlib.rl.from_neutrader.feature import init_qlib
|
||||||
|
from qlib.rl.order_execution.simulator_simple import SAOEMetrics, SAOEState
|
||||||
|
from qlib.rl.order_execution.utils import (
|
||||||
|
dataframe_append,
|
||||||
|
get_common_infra,
|
||||||
|
get_portfolio_and_indicator,
|
||||||
|
get_ticks_slice,
|
||||||
|
price_advantage,
|
||||||
|
)
|
||||||
|
from qlib.rl.simulator import Simulator
|
||||||
|
from qlib.strategy.base import BaseStrategy
|
||||||
|
|
||||||
|
|
||||||
|
class DecomposedStrategy(BaseStrategy):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
self.execute_order: Optional[Order] = None
|
||||||
|
self.execute_result: List[Tuple[Order, float, float, float]] = []
|
||||||
|
|
||||||
|
def generate_trade_decision(self, execute_result: list = None) -> Generator[Any, Any, BaseTradeDecision]:
|
||||||
|
# Once the following line is executed, this DecomposedStrategy (self) will be yielded to the outside
|
||||||
|
# of the entire executor, and the execution will be suspended. When the execution is resumed by `send()`,
|
||||||
|
# the sent item will be captured by `exec_vol`. The outside policy could communicate with the inner
|
||||||
|
# level strategy through this way.
|
||||||
|
exec_vol = yield self
|
||||||
|
|
||||||
|
oh = self.trade_exchange.get_order_helper()
|
||||||
|
order = oh.create(self._order.stock_id, exec_vol, self._order.direction)
|
||||||
|
|
||||||
|
self.execute_order = order
|
||||||
|
|
||||||
|
return TradeDecisionWO([order], self)
|
||||||
|
|
||||||
|
def alter_outer_trade_decision(self, outer_trade_decision: BaseTradeDecision) -> BaseTradeDecision:
|
||||||
|
return outer_trade_decision
|
||||||
|
|
||||||
|
def post_exe_step(self, execute_result: list) -> None:
|
||||||
|
self.execute_result = execute_result
|
||||||
|
|
||||||
|
def reset(self, outer_trade_decision: TradeDecisionWO = None, **kwargs: Any) -> None:
|
||||||
|
super().reset(outer_trade_decision=outer_trade_decision, **kwargs)
|
||||||
|
if outer_trade_decision is not None:
|
||||||
|
order_list = outer_trade_decision.order_list
|
||||||
|
assert len(order_list) == 1
|
||||||
|
self._order = order_list[0]
|
||||||
|
|
||||||
|
|
||||||
|
class SingleOrderStrategy(BaseStrategy):
|
||||||
|
# this logic is copied from FileOrderStrategy
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
common_infra: CommonInfrastructure,
|
||||||
|
order: Order,
|
||||||
|
trade_range: TradeRange,
|
||||||
|
instrument: str,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(common_infra=common_infra)
|
||||||
|
self._order = order
|
||||||
|
self._trade_range = trade_range
|
||||||
|
self._instrument = instrument
|
||||||
|
|
||||||
|
def alter_outer_trade_decision(self, outer_trade_decision: BaseTradeDecision) -> BaseTradeDecision:
|
||||||
|
return outer_trade_decision
|
||||||
|
|
||||||
|
def generate_trade_decision(self, execute_result: list = None) -> TradeDecisionWO:
|
||||||
|
oh: OrderHelper = self.common_infra.get("trade_exchange").get_order_helper()
|
||||||
|
order_list = [
|
||||||
|
oh.create(
|
||||||
|
code=self._instrument,
|
||||||
|
amount=self._order.amount,
|
||||||
|
direction=self._order.direction,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
return TradeDecisionWO(order_list, self, self._trade_range)
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: move these to the configuration files
|
||||||
|
FINEST_GRANULARITY = "1min"
|
||||||
|
COARSEST_GRANULARITY = "1day"
|
||||||
|
|
||||||
|
|
||||||
|
class StateMaintainer:
|
||||||
|
"""
|
||||||
|
Maintain states of the environment.
|
||||||
|
|
||||||
|
Example usage::
|
||||||
|
|
||||||
|
maintainer = StateMaintainer(...) # in reset
|
||||||
|
maintainer.update(...) # in step
|
||||||
|
# get states in get_state from maintainer
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, order: Order, time_per_step: str, tick_index: pd.DatetimeIndex, twap_price: float) -> None:
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
self.position = order.amount
|
||||||
|
self._order = order
|
||||||
|
self._time_per_step = time_per_step
|
||||||
|
self._tick_index = tick_index
|
||||||
|
self._twap_price = twap_price
|
||||||
|
|
||||||
|
metric_keys = list(SAOEMetrics.__annotations__.keys()) # pylint: disable=no-member
|
||||||
|
self.history_exec = pd.DataFrame(columns=metric_keys).set_index("datetime")
|
||||||
|
self.history_steps = pd.DataFrame(columns=metric_keys).set_index("datetime")
|
||||||
|
self.metrics: Optional[SAOEMetrics] = None
|
||||||
|
|
||||||
|
def update(
|
||||||
|
self,
|
||||||
|
inner_executor: BaseExecutor,
|
||||||
|
inner_strategy: DecomposedStrategy,
|
||||||
|
done: bool,
|
||||||
|
all_indicators: dict,
|
||||||
|
) -> None:
|
||||||
|
execute_order = inner_strategy.execute_order
|
||||||
|
execute_result = inner_strategy.execute_result
|
||||||
|
exec_vol = np.array([e[0].deal_amount for e in execute_result])
|
||||||
|
num_step = len(execute_result)
|
||||||
|
|
||||||
|
assert execute_order is not None
|
||||||
|
|
||||||
|
if num_step == 0:
|
||||||
|
market_volume = np.array([])
|
||||||
|
market_price = np.array([])
|
||||||
|
datetime_list = pd.DatetimeIndex([])
|
||||||
|
else:
|
||||||
|
market_volume = np.array(
|
||||||
|
inner_executor.trade_exchange.get_volume(
|
||||||
|
execute_order.stock_id,
|
||||||
|
execute_result[0][0].start_time,
|
||||||
|
execute_result[-1][0].start_time,
|
||||||
|
method=None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
trade_value = all_indicators[FINEST_GRANULARITY].iloc[-num_step:]["value"].values
|
||||||
|
deal_amount = all_indicators[FINEST_GRANULARITY].iloc[-num_step:]["deal_amount"].values
|
||||||
|
market_price = trade_value / deal_amount
|
||||||
|
|
||||||
|
datetime_list = all_indicators[FINEST_GRANULARITY].index[-num_step:]
|
||||||
|
|
||||||
|
assert market_price.shape == market_volume.shape == exec_vol.shape
|
||||||
|
|
||||||
|
self.history_exec = dataframe_append(
|
||||||
|
self.history_exec,
|
||||||
|
self._collect_multi_order_metric(
|
||||||
|
order=self._order,
|
||||||
|
datetime=datetime_list,
|
||||||
|
market_vol=market_volume,
|
||||||
|
market_price=market_price,
|
||||||
|
exec_vol=exec_vol,
|
||||||
|
pa=all_indicators[self._time_per_step].iloc[-1]["pa"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.history_steps = dataframe_append(
|
||||||
|
self.history_steps,
|
||||||
|
[
|
||||||
|
self._collect_single_order_metric(
|
||||||
|
execute_order,
|
||||||
|
execute_order.start_time,
|
||||||
|
market_volume,
|
||||||
|
market_price,
|
||||||
|
exec_vol.sum(),
|
||||||
|
exec_vol,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
if done:
|
||||||
|
self.metrics = self._collect_single_order_metric(
|
||||||
|
self._order,
|
||||||
|
self._tick_index[0], # start time
|
||||||
|
self.history_exec["market_volume"],
|
||||||
|
self.history_exec["market_price"],
|
||||||
|
self.history_steps["amount"].sum(),
|
||||||
|
self.history_exec["deal_amount"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# TODO: check whether we need this. Can we get this information from Account?
|
||||||
|
# Do this at the end
|
||||||
|
self.position -= exec_vol.sum()
|
||||||
|
|
||||||
|
def _collect_multi_order_metric(
|
||||||
|
self,
|
||||||
|
order: Order,
|
||||||
|
datetime: pd.Timestamp,
|
||||||
|
market_vol: np.ndarray,
|
||||||
|
market_price: np.ndarray,
|
||||||
|
exec_vol: np.ndarray,
|
||||||
|
pa: float,
|
||||||
|
) -> SAOEMetrics:
|
||||||
|
return SAOEMetrics(
|
||||||
|
# It should have the same keys with SAOEMetrics,
|
||||||
|
# but the values do not necessarily have the annotated type.
|
||||||
|
# Some values could be vectorized (e.g., exec_vol).
|
||||||
|
stock_id=order.stock_id,
|
||||||
|
datetime=datetime,
|
||||||
|
direction=order.direction,
|
||||||
|
market_volume=market_vol,
|
||||||
|
market_price=market_price,
|
||||||
|
amount=exec_vol,
|
||||||
|
inner_amount=exec_vol,
|
||||||
|
deal_amount=exec_vol,
|
||||||
|
trade_price=market_price,
|
||||||
|
trade_value=market_price * exec_vol,
|
||||||
|
position=self.position - np.cumsum(exec_vol),
|
||||||
|
ffr=exec_vol / order.amount,
|
||||||
|
pa=pa,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _collect_single_order_metric(
|
||||||
|
self,
|
||||||
|
order: Order,
|
||||||
|
datetime: pd.Timestamp,
|
||||||
|
market_vol: np.ndarray,
|
||||||
|
market_price: np.ndarray,
|
||||||
|
amount: float, # intended to trade such amount
|
||||||
|
exec_vol: np.ndarray,
|
||||||
|
) -> SAOEMetrics:
|
||||||
|
assert len(market_vol) == len(market_price) == len(exec_vol)
|
||||||
|
|
||||||
|
if np.abs(np.sum(exec_vol)) < EPS:
|
||||||
|
exec_avg_price = 0.0
|
||||||
|
else:
|
||||||
|
exec_avg_price = cast(float, np.average(market_price, weights=exec_vol)) # could be nan
|
||||||
|
if hasattr(exec_avg_price, "item"): # could be numpy scalar
|
||||||
|
exec_avg_price = exec_avg_price.item() # type: ignore
|
||||||
|
|
||||||
|
exec_sum = exec_vol.sum()
|
||||||
|
return SAOEMetrics(
|
||||||
|
stock_id=order.stock_id,
|
||||||
|
datetime=datetime,
|
||||||
|
direction=order.direction,
|
||||||
|
market_volume=market_vol.sum(),
|
||||||
|
market_price=market_price.mean() if len(market_price) > 0 else np.nan,
|
||||||
|
amount=amount,
|
||||||
|
inner_amount=exec_sum,
|
||||||
|
deal_amount=exec_sum, # in this simulator, there's no other restrictions
|
||||||
|
trade_price=exec_avg_price,
|
||||||
|
trade_value=float(np.sum(market_price * exec_vol)),
|
||||||
|
position=self.position - exec_sum,
|
||||||
|
ffr=float(exec_sum / order.amount),
|
||||||
|
pa=price_advantage(exec_avg_price, self._twap_price, order.direction),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SingleAssetOrderExecutionQlib(Simulator[Order, SAOEState, float]):
|
||||||
|
"""Single-asset order execution (SAOE) simulator which is implemented based on Qlib backtest tools.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
order (Order):
|
||||||
|
The seed to start an SAOE simulator is an order.
|
||||||
|
time_per_step (str):
|
||||||
|
A string to describe the time granularity of each step. Current support "1min", "30min", and "1day"
|
||||||
|
qlib_config (dict):
|
||||||
|
Configuration used to initialize Qlib.
|
||||||
|
inner_executor_fn (Callable[[str, CommonInfrastructure], BaseExecutor]):
|
||||||
|
Function used to get the inner level executor.
|
||||||
|
exchange_config (ExchangeConfig):
|
||||||
|
Configuration used to create the Exchange instance.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
order: Order,
|
||||||
|
time_per_step: str, # "1min", "30min", "1day"
|
||||||
|
qlib_config: dict,
|
||||||
|
inner_executor_fn: Callable[[str, CommonInfrastructure], BaseExecutor],
|
||||||
|
exchange_config: ExchangeConfig,
|
||||||
|
) -> None:
|
||||||
|
assert time_per_step in ("1min", "30min", "1day")
|
||||||
|
|
||||||
|
super().__init__(initial=order)
|
||||||
|
|
||||||
|
assert order.start_time.date() == order.end_time.date(), "Start date and end date must be the same."
|
||||||
|
|
||||||
|
self._order = order
|
||||||
|
self._order_date = pd.Timestamp(order.start_time.date())
|
||||||
|
self._trade_range = TradeRangeByTime(order.start_time.time(), order.end_time.time())
|
||||||
|
self._qlib_config = qlib_config
|
||||||
|
self._inner_executor_fn = inner_executor_fn
|
||||||
|
self._exchange_config = exchange_config
|
||||||
|
|
||||||
|
self._time_per_step = time_per_step
|
||||||
|
self._ticks_per_step = int(pd.Timedelta(time_per_step).total_seconds() // 60)
|
||||||
|
|
||||||
|
self._executor: Optional[NestedExecutor] = None
|
||||||
|
self._collect_data_loop: Optional[Generator] = None
|
||||||
|
|
||||||
|
self._done = False
|
||||||
|
|
||||||
|
self._inner_strategy = DecomposedStrategy()
|
||||||
|
|
||||||
|
self.reset(self._order)
|
||||||
|
|
||||||
|
def reset(self, order: Order) -> None:
|
||||||
|
instrument = order.stock_id
|
||||||
|
|
||||||
|
# TODO: Check this logic. Make sure we need to do this every time we reset the simulator.
|
||||||
|
init_qlib(self._qlib_config, instrument)
|
||||||
|
|
||||||
|
common_infra = get_common_infra(
|
||||||
|
self._exchange_config,
|
||||||
|
trade_date=pd.Timestamp(self._order_date),
|
||||||
|
codes=[instrument],
|
||||||
|
)
|
||||||
|
|
||||||
|
# TODO: We can leverage interfaces like (https://tinyurl.com/y8f8fhv4) to create trading environment.
|
||||||
|
# TODO: By aligning the interface to create environments with Qlib, it will be easier to share the config and
|
||||||
|
# TODO: code between backtesting and training.
|
||||||
|
self._inner_executor = self._inner_executor_fn(self._time_per_step, common_infra)
|
||||||
|
self._executor = NestedExecutor(
|
||||||
|
time_per_step=COARSEST_GRANULARITY,
|
||||||
|
inner_executor=self._inner_executor,
|
||||||
|
inner_strategy=self._inner_strategy,
|
||||||
|
track_data=True,
|
||||||
|
common_infra=common_infra,
|
||||||
|
)
|
||||||
|
|
||||||
|
exchange = self._inner_executor.trade_exchange
|
||||||
|
self._ticks_index = pd.DatetimeIndex([e[1] for e in list(exchange.quote_df.index)])
|
||||||
|
self._ticks_for_order = get_ticks_slice(
|
||||||
|
self._ticks_index,
|
||||||
|
self._order.start_time,
|
||||||
|
self._order.end_time,
|
||||||
|
include_end=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
self._backtest_data = QlibIntradayBacktestData(
|
||||||
|
order=self._order,
|
||||||
|
exchange=exchange,
|
||||||
|
start_time=self._ticks_for_order[0],
|
||||||
|
end_time=self._ticks_for_order[-1],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.twap_price = self._backtest_data.get_deal_price().mean()
|
||||||
|
|
||||||
|
top_strategy = SingleOrderStrategy(common_infra, order, self._trade_range, instrument)
|
||||||
|
self._executor.reset(start_time=pd.Timestamp(self._order_date), end_time=pd.Timestamp(self._order_date))
|
||||||
|
top_strategy.reset(level_infra=self._executor.get_level_infra())
|
||||||
|
|
||||||
|
self._collect_data_loop = self._executor.collect_data(top_strategy.generate_trade_decision(), level=0)
|
||||||
|
assert isinstance(self._collect_data_loop, Generator)
|
||||||
|
|
||||||
|
self._iter_strategy(action=None)
|
||||||
|
self._done = False
|
||||||
|
|
||||||
|
self._maintainer = StateMaintainer(
|
||||||
|
order=self._order,
|
||||||
|
time_per_step=self._time_per_step,
|
||||||
|
tick_index=self._ticks_index,
|
||||||
|
twap_price=self.twap_price,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _iter_strategy(self, action: float = None) -> DecomposedStrategy:
|
||||||
|
"""Iterate the _collect_data_loop until we get the next yield DecomposedStrategy."""
|
||||||
|
assert self._collect_data_loop is not None
|
||||||
|
|
||||||
|
strategy = next(self._collect_data_loop) if action is None else self._collect_data_loop.send(action)
|
||||||
|
while not isinstance(strategy, DecomposedStrategy):
|
||||||
|
strategy = next(self._collect_data_loop) if action is None else self._collect_data_loop.send(action)
|
||||||
|
assert isinstance(strategy, DecomposedStrategy)
|
||||||
|
return strategy
|
||||||
|
|
||||||
|
def step(self, action: float) -> None:
|
||||||
|
"""Execute one step or SAOE.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
action (float):
|
||||||
|
The amount you wish to deal. The simulator doesn't guarantee all the amount to be successfully dealt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
assert not self._done, "Simulator has already done!"
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._iter_strategy(action=action)
|
||||||
|
except StopIteration:
|
||||||
|
self._done = True
|
||||||
|
|
||||||
|
assert self._executor is not None
|
||||||
|
_, all_indicators = get_portfolio_and_indicator(self._executor)
|
||||||
|
|
||||||
|
self._maintainer.update(
|
||||||
|
inner_executor=self._inner_executor,
|
||||||
|
inner_strategy=self._inner_strategy,
|
||||||
|
done=self._done,
|
||||||
|
all_indicators=all_indicators,
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_state(self) -> SAOEState:
|
||||||
|
return SAOEState(
|
||||||
|
order=self._order,
|
||||||
|
cur_time=self._inner_executor.trade_calendar.get_step_time()[0],
|
||||||
|
position=self._maintainer.position,
|
||||||
|
history_exec=self._maintainer.history_exec,
|
||||||
|
history_steps=self._maintainer.history_steps,
|
||||||
|
metrics=self._maintainer.metrics,
|
||||||
|
backtest_data=self._backtest_data,
|
||||||
|
ticks_per_step=self._ticks_per_step,
|
||||||
|
ticks_index=self._ticks_index,
|
||||||
|
ticks_for_order=self._ticks_for_order,
|
||||||
|
)
|
||||||
|
|
||||||
|
def done(self) -> bool:
|
||||||
|
return self._done
|
||||||
|
|||||||
@@ -4,18 +4,20 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import NamedTuple, Any, TypeVar, cast
|
from typing import Any, NamedTuple, Optional, TypeVar, cast
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from qlib.backtest.decision import Order, OrderDir
|
from qlib.backtest.decision import Order, OrderDir
|
||||||
from qlib.constant import EPS
|
from qlib.constant import EPS
|
||||||
|
from qlib.rl.data.pickle_styled import DealPriceType, IntradayBacktestData, load_simple_intraday_backtest_data
|
||||||
from qlib.rl.simulator import Simulator
|
from qlib.rl.simulator import Simulator
|
||||||
from qlib.rl.data.pickle_styled import IntradayBacktestData, load_intraday_backtest_data, DealPriceType
|
|
||||||
from qlib.rl.utils import LogLevel
|
from qlib.rl.utils import LogLevel
|
||||||
from qlib.typehint import TypedDict
|
from qlib.typehint import TypedDict
|
||||||
|
|
||||||
|
# TODO: Integrating Qlib's native data with simulator_simple
|
||||||
|
|
||||||
__all__ = ["SAOEMetrics", "SAOEState", "SingleAssetOrderExecution"]
|
__all__ = ["SAOEMetrics", "SAOEState", "SingleAssetOrderExecution"]
|
||||||
|
|
||||||
ONE_SEC = pd.Timedelta("1s") # use 1 second to exclude the right interval point
|
ONE_SEC = pd.Timedelta("1s") # use 1 second to exclude the right interval point
|
||||||
@@ -33,40 +35,40 @@ class SAOEMetrics(TypedDict):
|
|||||||
|
|
||||||
stock_id: str
|
stock_id: str
|
||||||
"""Stock ID of this record."""
|
"""Stock ID of this record."""
|
||||||
datetime: pd.Timestamp
|
datetime: pd.Timestamp | pd.DatetimeIndex # TODO: check this
|
||||||
"""Datetime of this record (this is index in the dataframe)."""
|
"""Datetime of this record (this is index in the dataframe)."""
|
||||||
direction: int
|
direction: int
|
||||||
"""Direction of the order. 0 for sell, 1 for buy."""
|
"""Direction of the order. 0 for sell, 1 for buy."""
|
||||||
|
|
||||||
# Market information.
|
# Market information.
|
||||||
market_volume: float
|
market_volume: np.ndarray | float
|
||||||
"""(total) market volume traded in the period."""
|
"""(total) market volume traded in the period."""
|
||||||
market_price: float
|
market_price: np.ndarray | float
|
||||||
"""Deal price. If it's a period of time, this is the average market deal price."""
|
"""Deal price. If it's a period of time, this is the average market deal price."""
|
||||||
|
|
||||||
# Strategy records.
|
# Strategy records.
|
||||||
|
|
||||||
amount: float
|
amount: np.ndarray | float
|
||||||
"""Total amount (volume) strategy intends to trade."""
|
"""Total amount (volume) strategy intends to trade."""
|
||||||
inner_amount: float
|
inner_amount: np.ndarray | float
|
||||||
"""Total amount that the lower-level strategy intends to trade
|
"""Total amount that the lower-level strategy intends to trade
|
||||||
(might be larger than amount, e.g., to ensure ffr)."""
|
(might be larger than amount, e.g., to ensure ffr)."""
|
||||||
|
|
||||||
deal_amount: float
|
deal_amount: np.ndarray | float
|
||||||
"""Amount that successfully takes effect (must be less than inner_amount)."""
|
"""Amount that successfully takes effect (must be less than inner_amount)."""
|
||||||
trade_price: float
|
trade_price: np.ndarray | float
|
||||||
"""The average deal price for this strategy."""
|
"""The average deal price for this strategy."""
|
||||||
trade_value: float
|
trade_value: np.ndarray | float
|
||||||
"""Total worth of trading. In the simple simulaton, trade_value = deal_amount * price."""
|
"""Total worth of trading. In the simple simulation, trade_value = deal_amount * price."""
|
||||||
position: float
|
position: np.ndarray | float
|
||||||
"""Position left after this "period"."""
|
"""Position left after this "period"."""
|
||||||
|
|
||||||
# Accumulated metrics
|
# Accumulated metrics
|
||||||
|
|
||||||
ffr: float
|
ffr: np.ndarray | float
|
||||||
"""Completed how much percent of the daily order."""
|
"""Completed how much percent of the daily order."""
|
||||||
|
|
||||||
pa: float
|
pa: np.ndarray | float
|
||||||
"""Price advantage compared to baseline (i.e., trade with baseline market price).
|
"""Price advantage compared to baseline (i.e., trade with baseline market price).
|
||||||
The baseline is trade price when using TWAP strategy to execute this order.
|
The baseline is trade price when using TWAP strategy to execute this order.
|
||||||
Please note that there could be data leak here).
|
Please note that there could be data leak here).
|
||||||
@@ -87,7 +89,7 @@ class SAOEState(NamedTuple):
|
|||||||
history_steps: pd.DataFrame
|
history_steps: pd.DataFrame
|
||||||
"""See :attr:`SingleAssetOrderExecution.history_steps`."""
|
"""See :attr:`SingleAssetOrderExecution.history_steps`."""
|
||||||
|
|
||||||
metrics: SAOEMetrics | None
|
metrics: Optional[SAOEMetrics]
|
||||||
"""Daily metric, only available when the trading is in "done" state."""
|
"""Daily metric, only available when the trading is in "done" state."""
|
||||||
|
|
||||||
backtest_data: IntradayBacktestData
|
backtest_data: IntradayBacktestData
|
||||||
@@ -114,13 +116,13 @@ class SingleAssetOrderExecution(Simulator[Order, SAOEState, float]):
|
|||||||
If such fine granularity is not needed, use ``ticks_per_step`` to
|
If such fine granularity is not needed, use ``ticks_per_step`` to
|
||||||
lengthen the ticks for each step.
|
lengthen the ticks for each step.
|
||||||
|
|
||||||
In each step, the traded amount are "equally" splitted to each tick,
|
In each step, the traded amount are "equally" separated to each tick,
|
||||||
then bounded by volume maximum exeuction volume (i.e., ``vol_threshold``),
|
then bounded by volume maximum execution volume (i.e., ``vol_threshold``),
|
||||||
and if it's the last step, try to ensure all the amount to be executed.
|
and if it's the last step, try to ensure all the amount to be executed.
|
||||||
|
|
||||||
Parameters
|
Parameters
|
||||||
----------
|
----------
|
||||||
initial
|
order
|
||||||
The seed to start an SAOE simulator is an order.
|
The seed to start an SAOE simulator is an order.
|
||||||
ticks_per_step
|
ticks_per_step
|
||||||
How many ticks per step.
|
How many ticks per step.
|
||||||
@@ -140,7 +142,7 @@ class SingleAssetOrderExecution(Simulator[Order, SAOEState, float]):
|
|||||||
See :class:`SAOEMetrics` for available columns.
|
See :class:`SAOEMetrics` for available columns.
|
||||||
Index is ``datetime``, which is the **starting** time of each step."""
|
Index is ``datetime``, which is the **starting** time of each step."""
|
||||||
|
|
||||||
metrics: SAOEMetrics | None
|
metrics: Optional[SAOEMetrics]
|
||||||
"""Metrics. Only available when done."""
|
"""Metrics. Only available when done."""
|
||||||
|
|
||||||
twap_price: float
|
twap_price: float
|
||||||
@@ -159,15 +161,21 @@ class SingleAssetOrderExecution(Simulator[Order, SAOEState, float]):
|
|||||||
data_dir: Path,
|
data_dir: Path,
|
||||||
ticks_per_step: int = 30,
|
ticks_per_step: int = 30,
|
||||||
deal_price_type: DealPriceType = "close",
|
deal_price_type: DealPriceType = "close",
|
||||||
vol_threshold: float | None = None,
|
vol_threshold: Optional[float] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
super().__init__(initial=order)
|
||||||
|
|
||||||
self.order = order
|
self.order = order
|
||||||
self.ticks_per_step: int = ticks_per_step
|
self.ticks_per_step: int = ticks_per_step
|
||||||
self.deal_price_type = deal_price_type
|
self.deal_price_type = deal_price_type
|
||||||
self.vol_threshold = vol_threshold
|
self.vol_threshold = vol_threshold
|
||||||
self.data_dir = data_dir
|
self.data_dir = data_dir
|
||||||
self.backtest_data = load_intraday_backtest_data(
|
self.backtest_data = load_simple_intraday_backtest_data(
|
||||||
self.data_dir, order.stock_id, pd.Timestamp(order.start_time.date()), self.deal_price_type, order.direction
|
self.data_dir,
|
||||||
|
order.stock_id,
|
||||||
|
pd.Timestamp(order.start_time.date()),
|
||||||
|
self.deal_price_type,
|
||||||
|
order.direction,
|
||||||
)
|
)
|
||||||
|
|
||||||
self.ticks_index = self.backtest_data.get_time_index()
|
self.ticks_index = self.backtest_data.get_time_index()
|
||||||
@@ -188,9 +196,9 @@ class SingleAssetOrderExecution(Simulator[Order, SAOEState, float]):
|
|||||||
self.history_steps = pd.DataFrame(columns=metric_keys).set_index("datetime")
|
self.history_steps = pd.DataFrame(columns=metric_keys).set_index("datetime")
|
||||||
self.metrics = None
|
self.metrics = None
|
||||||
|
|
||||||
self.market_price: np.ndarray | None = None
|
self.market_price: Optional[np.ndarray] = None
|
||||||
self.market_vol: np.ndarray | None = None
|
self.market_vol: Optional[np.ndarray] = None
|
||||||
self.market_vol_limit: np.ndarray | None = None
|
self.market_vol_limit: Optional[np.ndarray] = None
|
||||||
|
|
||||||
def step(self, amount: float) -> None:
|
def step(self, amount: float) -> None:
|
||||||
"""Execute one step or SAOE.
|
"""Execute one step or SAOE.
|
||||||
@@ -205,7 +213,8 @@ class SingleAssetOrderExecution(Simulator[Order, SAOEState, float]):
|
|||||||
|
|
||||||
self.market_price = self.market_vol = None # avoid misuse
|
self.market_price = self.market_vol = None # avoid misuse
|
||||||
exec_vol = self._split_exec_vol(amount)
|
exec_vol = self._split_exec_vol(amount)
|
||||||
assert self.market_price is not None and self.market_vol is not None
|
assert self.market_price is not None
|
||||||
|
assert self.market_vol is not None
|
||||||
|
|
||||||
ticks_position = self.position - np.cumsum(exec_vol)
|
ticks_position = self.position - np.cumsum(exec_vol)
|
||||||
|
|
||||||
@@ -363,7 +372,7 @@ class SingleAssetOrderExecution(Simulator[Order, SAOEState, float]):
|
|||||||
inner_amount=exec_vol.sum(),
|
inner_amount=exec_vol.sum(),
|
||||||
deal_amount=exec_vol.sum(), # in this simulator, there's no other restrictions
|
deal_amount=exec_vol.sum(), # in this simulator, there's no other restrictions
|
||||||
trade_price=exec_avg_price,
|
trade_price=exec_avg_price,
|
||||||
trade_value=np.sum(market_price * exec_vol),
|
trade_value=float(np.sum(market_price * exec_vol)),
|
||||||
position=self.position,
|
position=self.position,
|
||||||
ffr=float(exec_vol.sum() / self.order.amount),
|
ffr=float(exec_vol.sum() / self.order.amount),
|
||||||
pa=price_advantage(exec_avg_price, self.twap_price, self.order.direction),
|
pa=price_advantage(exec_avg_price, self.twap_price, self.order.direction),
|
||||||
@@ -386,7 +395,9 @@ _float_or_ndarray = TypeVar("_float_or_ndarray", float, np.ndarray)
|
|||||||
|
|
||||||
|
|
||||||
def price_advantage(
|
def price_advantage(
|
||||||
exec_price: _float_or_ndarray, baseline_price: float, direction: OrderDir | int
|
exec_price: _float_or_ndarray,
|
||||||
|
baseline_price: float,
|
||||||
|
direction: OrderDir | int,
|
||||||
) -> _float_or_ndarray:
|
) -> _float_or_ndarray:
|
||||||
if baseline_price == 0: # something is wrong with data. Should be nan here
|
if baseline_price == 0: # something is wrong with data. Should be nan here
|
||||||
if isinstance(exec_price, float):
|
if isinstance(exec_price, float):
|
||||||
|
|||||||
111
qlib/rl/order_execution/utils.py
Normal file
111
qlib/rl/order_execution/utils.py
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
# Copyright (c) Microsoft Corporation.
|
||||||
|
# Licensed under the MIT License.
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, List, Tuple, cast
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from qlib.backtest import CommonInfrastructure, get_exchange
|
||||||
|
from qlib.backtest.account import Account
|
||||||
|
from qlib.backtest.decision import OrderDir
|
||||||
|
from qlib.backtest.executor import BaseExecutor
|
||||||
|
from qlib.rl.from_neutrader.config import ExchangeConfig
|
||||||
|
from qlib.rl.order_execution.simulator_simple import ONE_SEC, _float_or_ndarray
|
||||||
|
from qlib.utils.time import Freq
|
||||||
|
|
||||||
|
|
||||||
|
def get_common_infra(
|
||||||
|
config: ExchangeConfig,
|
||||||
|
trade_date: pd.Timestamp,
|
||||||
|
codes: List[str],
|
||||||
|
cash_limit: float = None,
|
||||||
|
) -> CommonInfrastructure:
|
||||||
|
# need to specify a range here for acceleration
|
||||||
|
if cash_limit is None:
|
||||||
|
trade_account = Account(init_cash=int(1e12), benchmark_config={}, pos_type="InfPosition")
|
||||||
|
else:
|
||||||
|
trade_account = Account(
|
||||||
|
init_cash=cash_limit,
|
||||||
|
benchmark_config={},
|
||||||
|
pos_type="Position",
|
||||||
|
position_dict={code: {"amount": 1e12, "price": 1.0} for code in codes},
|
||||||
|
)
|
||||||
|
|
||||||
|
exchange = get_exchange(
|
||||||
|
codes=codes,
|
||||||
|
freq="1min",
|
||||||
|
limit_threshold=config.limit_threshold,
|
||||||
|
deal_price=config.deal_price,
|
||||||
|
open_cost=config.open_cost,
|
||||||
|
close_cost=config.close_cost,
|
||||||
|
min_cost=config.min_cost if config.trade_unit is not None else 0,
|
||||||
|
start_time=trade_date,
|
||||||
|
end_time=trade_date + pd.DateOffset(1),
|
||||||
|
trade_unit=config.trade_unit,
|
||||||
|
volume_threshold=config.volume_threshold,
|
||||||
|
)
|
||||||
|
|
||||||
|
return CommonInfrastructure(trade_account=trade_account, trade_exchange=exchange)
|
||||||
|
|
||||||
|
|
||||||
|
def get_ticks_slice(
|
||||||
|
ticks_index: pd.DatetimeIndex,
|
||||||
|
start: pd.Timestamp,
|
||||||
|
end: pd.Timestamp,
|
||||||
|
include_end: bool = False,
|
||||||
|
) -> pd.DatetimeIndex:
|
||||||
|
if not include_end:
|
||||||
|
end = end - ONE_SEC
|
||||||
|
return ticks_index[ticks_index.slice_indexer(start, end)]
|
||||||
|
|
||||||
|
|
||||||
|
def dataframe_append(df: pd.DataFrame, other: Any) -> pd.DataFrame:
|
||||||
|
# dataframe.append is deprecated
|
||||||
|
other_df = pd.DataFrame(other).set_index("datetime")
|
||||||
|
other_df.index.name = "datetime"
|
||||||
|
|
||||||
|
res = pd.concat([df, other_df], axis=0)
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
def price_advantage(
|
||||||
|
exec_price: _float_or_ndarray,
|
||||||
|
baseline_price: float,
|
||||||
|
direction: OrderDir | int,
|
||||||
|
) -> _float_or_ndarray:
|
||||||
|
if baseline_price == 0: # something is wrong with data. Should be nan here
|
||||||
|
if isinstance(exec_price, float):
|
||||||
|
return 0.0
|
||||||
|
else:
|
||||||
|
return np.zeros_like(exec_price)
|
||||||
|
if direction == OrderDir.BUY:
|
||||||
|
res = (1 - exec_price / baseline_price) * 10000
|
||||||
|
elif direction == OrderDir.SELL:
|
||||||
|
res = (exec_price / baseline_price - 1) * 10000
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unexpected order direction: {direction}")
|
||||||
|
res_wo_nan: np.ndarray = np.nan_to_num(res, nan=0.0)
|
||||||
|
if res_wo_nan.size == 1:
|
||||||
|
return res_wo_nan.item()
|
||||||
|
else:
|
||||||
|
return cast(_float_or_ndarray, res_wo_nan)
|
||||||
|
|
||||||
|
|
||||||
|
def get_portfolio_and_indicator(executor: BaseExecutor) -> Tuple[dict, dict]:
|
||||||
|
all_executors = executor.get_all_executors()
|
||||||
|
all_portfolio_metrics = {
|
||||||
|
"{}{}".format(*Freq.parse(_executor.time_per_step)): _executor.trade_account.get_portfolio_metrics()
|
||||||
|
for _executor in all_executors
|
||||||
|
if _executor.trade_account.is_port_metr_enabled()
|
||||||
|
}
|
||||||
|
|
||||||
|
all_indicators = {}
|
||||||
|
for _executor in all_executors:
|
||||||
|
key = "{}{}".format(*Freq.parse(_executor.time_per_step))
|
||||||
|
all_indicators[key] = _executor.trade_account.get_trade_indicator().generate_trade_indicators_dataframe()
|
||||||
|
all_indicators[key + "_obj"] = _executor.trade_account.get_trade_indicator()
|
||||||
|
|
||||||
|
return all_portfolio_metrics, all_indicators
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Generic, Any, TypeVar, TYPE_CHECKING
|
from typing import TYPE_CHECKING, Any, Dict, Generic, Optional, Tuple, TypeVar
|
||||||
|
|
||||||
from qlib.typehint import final
|
from qlib.typehint import final
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ class Reward(Generic[SimulatorState]):
|
|||||||
Subclass should implement ``reward(simulator_state)`` to implement their own reward calculation recipe.
|
Subclass should implement ``reward(simulator_state)`` to implement their own reward calculation recipe.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
env: EnvWrapper | None = None
|
env: Optional[EnvWrapper] = None
|
||||||
|
|
||||||
@final
|
@final
|
||||||
def __call__(self, simulator_state: SimulatorState) -> float:
|
def __call__(self, simulator_state: SimulatorState) -> float:
|
||||||
@@ -30,14 +30,15 @@ class Reward(Generic[SimulatorState]):
|
|||||||
"""Implement this method for your own reward."""
|
"""Implement this method for your own reward."""
|
||||||
raise NotImplementedError("Implement reward calculation recipe in `reward()`.")
|
raise NotImplementedError("Implement reward calculation recipe in `reward()`.")
|
||||||
|
|
||||||
def log(self, name, value):
|
def log(self, name: str, value: Any) -> None:
|
||||||
|
assert self.env is not None
|
||||||
self.env.logger.add_scalar(name, value)
|
self.env.logger.add_scalar(name, value)
|
||||||
|
|
||||||
|
|
||||||
class RewardCombination(Reward):
|
class RewardCombination(Reward):
|
||||||
"""Combination of multiple reward."""
|
"""Combination of multiple reward."""
|
||||||
|
|
||||||
def __init__(self, rewards: dict[str, tuple[Reward, float]]):
|
def __init__(self, rewards: Dict[str, Tuple[Reward, float]]) -> None:
|
||||||
self.rewards = rewards
|
self.rewards = rewards
|
||||||
|
|
||||||
def reward(self, simulator_state: Any) -> float:
|
def reward(self, simulator_state: Any) -> float:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import TypeVar, Generic, Any, TYPE_CHECKING
|
from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar
|
||||||
|
|
||||||
from .seed import InitialStateType
|
from .seed import InitialStateType
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ class Simulator(Generic[InitialStateType, StateType, ActType]):
|
|||||||
Simulators are discouraged to use this, because it's prone to induce errors.
|
Simulators are discouraged to use this, because it's prone to induce errors.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
env: EnvWrapper | None = None
|
env: Optional[EnvWrapper] = None
|
||||||
|
|
||||||
def __init__(self, initial: InitialStateType, **kwargs: Any) -> None:
|
def __init__(self, initial: InitialStateType, **kwargs: Any) -> None:
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -3,17 +3,17 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Callable, Sequence, cast, Any
|
from typing import Any, Callable, Sequence, cast
|
||||||
|
|
||||||
from tianshou.policy import BasePolicy
|
from tianshou.policy import BasePolicy
|
||||||
|
|
||||||
from qlib.rl.simulator import InitialStateType, Simulator
|
from qlib.rl.interpreter import ActionInterpreter, StateInterpreter
|
||||||
from qlib.rl.interpreter import StateInterpreter, ActionInterpreter
|
|
||||||
from qlib.rl.reward import Reward
|
from qlib.rl.reward import Reward
|
||||||
|
from qlib.rl.simulator import InitialStateType, Simulator
|
||||||
from qlib.rl.utils import FiniteEnvType, LogWriter
|
from qlib.rl.utils import FiniteEnvType, LogWriter
|
||||||
|
|
||||||
from .vessel import TrainingVessel
|
|
||||||
from .trainer import Trainer
|
from .trainer import Trainer
|
||||||
|
from .vessel import TrainingVessel
|
||||||
|
|
||||||
|
|
||||||
def train(
|
def train(
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import shutil
|
|||||||
import time
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, TYPE_CHECKING
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ from __future__ import annotations
|
|||||||
import copy
|
import copy
|
||||||
from contextlib import AbstractContextManager, contextmanager
|
from contextlib import AbstractContextManager, contextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Iterable, TypeVar, Sequence, cast
|
from typing import Any, Iterable, Sequence, TypeVar, cast
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
from qlib.rl.simulator import InitialStateType
|
|
||||||
from qlib.rl.utils import EnvWrapper, FiniteEnvType, LogCollector, LogWriter, LogBuffer, vectorize_env, LogLevel
|
|
||||||
from qlib.log import get_module_logger
|
from qlib.log import get_module_logger
|
||||||
|
from qlib.rl.simulator import InitialStateType
|
||||||
|
from qlib.rl.utils import EnvWrapper, FiniteEnvType, LogBuffer, LogCollector, LogLevel, LogWriter, vectorize_env
|
||||||
from qlib.rl.utils.finite_env import FiniteVectorEnv
|
from qlib.rl.utils.finite_env import FiniteVectorEnv
|
||||||
from qlib.typehint import Literal
|
from qlib.typehint import Literal
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import weakref
|
import weakref
|
||||||
from typing import Callable, ContextManager, Generic, Iterable, TYPE_CHECKING, Sequence, Any, TypeVar, cast, Dict
|
from typing import TYPE_CHECKING, Any, Callable, ContextManager, Dict, Generic, Iterable, Sequence, TypeVar, cast
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from tianshou.data import Collector, VectorReplayBuffer
|
from tianshou.data import Collector, VectorReplayBuffer
|
||||||
@@ -12,12 +12,11 @@ from tianshou.env import BaseVectorEnv
|
|||||||
from tianshou.policy import BasePolicy
|
from tianshou.policy import BasePolicy
|
||||||
|
|
||||||
from qlib.constant import INF
|
from qlib.constant import INF
|
||||||
from qlib.rl.interpreter import StateType, ActType, ObsType, PolicyActType
|
|
||||||
from qlib.rl.simulator import InitialStateType, Simulator
|
|
||||||
from qlib.rl.interpreter import StateInterpreter, ActionInterpreter
|
|
||||||
from qlib.rl.reward import Reward
|
|
||||||
from qlib.rl.utils import DataQueue
|
|
||||||
from qlib.log import get_module_logger
|
from qlib.log import get_module_logger
|
||||||
|
from qlib.rl.interpreter import ActionInterpreter, ActType, ObsType, PolicyActType, StateInterpreter, StateType
|
||||||
|
from qlib.rl.reward import Reward
|
||||||
|
from qlib.rl.simulator import InitialStateType, Simulator
|
||||||
|
from qlib.rl.utils import DataQueue
|
||||||
from qlib.rl.utils.finite_env import FiniteVectorEnv
|
from qlib.rl.utils.finite_env import FiniteVectorEnv
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@@ -209,6 +208,9 @@ class TrainingVessel(TrainingVesselBase):
|
|||||||
order = np.random.permutation(len(collection))
|
order = np.random.permutation(len(collection))
|
||||||
res = [collection[o] for o in order[:size]]
|
res = [collection[o] for o in order[:size]]
|
||||||
_logger.info(
|
_logger.info(
|
||||||
"Fast running in development mode. Cut %s initial states from %d to %d.", name, len(collection), len(res)
|
"Fast running in development mode. Cut %s initial states from %d to %d.",
|
||||||
|
name,
|
||||||
|
len(collection),
|
||||||
|
len(res),
|
||||||
)
|
)
|
||||||
return res
|
return res
|
||||||
|
|||||||
@@ -1,7 +1,21 @@
|
|||||||
# Copyright (c) Microsoft Corporation.
|
# Copyright (c) Microsoft Corporation.
|
||||||
# Licensed under the MIT License.
|
# Licensed under the MIT License.
|
||||||
|
|
||||||
from .data_queue import *
|
from .data_queue import DataQueue
|
||||||
from .env_wrapper import *
|
from .env_wrapper import EnvWrapper, EnvWrapperStatus
|
||||||
from .finite_env import *
|
from .finite_env import FiniteEnvType, vectorize_env
|
||||||
from .log import *
|
from .log import ConsoleWriter, CsvWriter, LogBuffer, LogCollector, LogLevel, LogWriter
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"LogLevel",
|
||||||
|
"DataQueue",
|
||||||
|
"EnvWrapper",
|
||||||
|
"FiniteEnvType",
|
||||||
|
"LogCollector",
|
||||||
|
"LogWriter",
|
||||||
|
"vectorize_env",
|
||||||
|
"ConsoleWriter",
|
||||||
|
"CsvWriter",
|
||||||
|
"EnvWrapperStatus",
|
||||||
|
"LogBuffer",
|
||||||
|
]
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
# Copyright (c) Microsoft Corporation.
|
# Copyright (c) Microsoft Corporation.
|
||||||
# Licensed under the MIT License.
|
# Licensed under the MIT License.
|
||||||
|
|
||||||
import os
|
from __future__ import annotations
|
||||||
|
|
||||||
import multiprocessing
|
import multiprocessing
|
||||||
|
import os
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import warnings
|
import warnings
|
||||||
from queue import Empty
|
from queue import Empty
|
||||||
from typing import TypeVar, Generic, Sequence, cast
|
from typing import Any, Generator, Generic, Sequence, TypeVar, cast
|
||||||
|
|
||||||
from qlib.log import get_module_logger
|
from qlib.log import get_module_logger
|
||||||
|
|
||||||
@@ -60,7 +62,7 @@ class DataQueue(Generic[T]):
|
|||||||
shuffle: bool = True,
|
shuffle: bool = True,
|
||||||
producer_num_workers: int = 0,
|
producer_num_workers: int = 0,
|
||||||
queue_maxsize: int = 0,
|
queue_maxsize: int = 0,
|
||||||
):
|
) -> None:
|
||||||
if queue_maxsize == 0:
|
if queue_maxsize == 0:
|
||||||
if os.cpu_count() is not None:
|
if os.cpu_count() is not None:
|
||||||
queue_maxsize = cast(int, os.cpu_count())
|
queue_maxsize = cast(int, os.cpu_count())
|
||||||
@@ -78,14 +80,14 @@ class DataQueue(Generic[T]):
|
|||||||
self._queue: multiprocessing.Queue = multiprocessing.Queue(maxsize=queue_maxsize)
|
self._queue: multiprocessing.Queue = multiprocessing.Queue(maxsize=queue_maxsize)
|
||||||
self._done = multiprocessing.Value("i", 0)
|
self._done = multiprocessing.Value("i", 0)
|
||||||
|
|
||||||
def __enter__(self):
|
def __enter__(self) -> DataQueue:
|
||||||
self.activate()
|
self.activate()
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||||
self.cleanup()
|
self.cleanup()
|
||||||
|
|
||||||
def cleanup(self):
|
def cleanup(self) -> None:
|
||||||
with self._done.get_lock():
|
with self._done.get_lock():
|
||||||
self._done.value += 1
|
self._done.value += 1
|
||||||
for repeat in range(500):
|
for repeat in range(500):
|
||||||
@@ -105,7 +107,7 @@ class DataQueue(Generic[T]):
|
|||||||
break
|
break
|
||||||
_logger.debug(f"Remaining items in queue collection done. Empty: {self._queue.empty()}")
|
_logger.debug(f"Remaining items in queue collection done. Empty: {self._queue.empty()}")
|
||||||
|
|
||||||
def get(self, block=True):
|
def get(self, block: bool = True) -> Any:
|
||||||
if not hasattr(self, "_first_get"):
|
if not hasattr(self, "_first_get"):
|
||||||
self._first_get = True
|
self._first_get = True
|
||||||
if self._first_get:
|
if self._first_get:
|
||||||
@@ -120,17 +122,17 @@ class DataQueue(Generic[T]):
|
|||||||
if self._done.value:
|
if self._done.value:
|
||||||
raise StopIteration # pylint: disable=raise-missing-from
|
raise StopIteration # pylint: disable=raise-missing-from
|
||||||
|
|
||||||
def put(self, obj, block=True, timeout=None):
|
def put(self, obj: Any, block: bool = True, timeout: int = None) -> None:
|
||||||
return self._queue.put(obj, block=block, timeout=timeout)
|
self._queue.put(obj, block=block, timeout=timeout)
|
||||||
|
|
||||||
def mark_as_done(self):
|
def mark_as_done(self) -> None:
|
||||||
with self._done.get_lock():
|
with self._done.get_lock():
|
||||||
self._done.value = 1
|
self._done.value = 1
|
||||||
|
|
||||||
def done(self):
|
def done(self) -> int:
|
||||||
return self._done.value
|
return self._done.value
|
||||||
|
|
||||||
def activate(self):
|
def activate(self) -> DataQueue:
|
||||||
if self._activated:
|
if self._activated:
|
||||||
raise ValueError("DataQueue can not activate twice.")
|
raise ValueError("DataQueue can not activate twice.")
|
||||||
thread = threading.Thread(target=self._producer, daemon=True)
|
thread = threading.Thread(target=self._producer, daemon=True)
|
||||||
@@ -138,20 +140,20 @@ class DataQueue(Generic[T]):
|
|||||||
self._activated = True
|
self._activated = True
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def __del__(self):
|
def __del__(self) -> None:
|
||||||
_logger.debug(f"__del__ of {__name__}.DataQueue")
|
_logger.debug(f"__del__ of {__name__}.DataQueue")
|
||||||
self.cleanup()
|
self.cleanup()
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self) -> Generator[Any, None, None]:
|
||||||
if not self._activated:
|
if not self._activated:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"Need to call activate() to launch a daemon worker "
|
"Need to call activate() to launch a daemon worker "
|
||||||
"to produce data into data queue before using it. "
|
"to produce data into data queue before using it. "
|
||||||
"You probably have forgotten to use the DataQueue in a with block."
|
"You probably have forgotten to use the DataQueue in a with block.",
|
||||||
)
|
)
|
||||||
return self._consumer()
|
return self._consumer()
|
||||||
|
|
||||||
def _consumer(self):
|
def _consumer(self) -> Generator[Any, None, None]:
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
yield self.get()
|
yield self.get()
|
||||||
@@ -159,7 +161,7 @@ class DataQueue(Generic[T]):
|
|||||||
_logger.debug("Data consumer timed-out from get.")
|
_logger.debug("Data consumer timed-out from get.")
|
||||||
return
|
return
|
||||||
|
|
||||||
def _producer(self):
|
def _producer(self) -> None:
|
||||||
# pytorch dataloader is used here only because we need its sampler and multi-processing
|
# pytorch dataloader is used here only because we need its sampler and multi-processing
|
||||||
from torch.utils.data import DataLoader, Dataset # pylint: disable=import-outside-toplevel
|
from torch.utils.data import DataLoader, Dataset # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
|||||||
@@ -4,14 +4,15 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import weakref
|
import weakref
|
||||||
from typing import Callable, Any, Iterable, Iterator, Generic, cast
|
from typing import Any, Callable, Dict, Generic, Iterable, Iterator, Optional, Tuple, cast
|
||||||
|
|
||||||
import gym
|
import gym
|
||||||
|
from gym import Space
|
||||||
|
|
||||||
from qlib.rl.aux_info import AuxiliaryInfoCollector
|
from qlib.rl.aux_info import AuxiliaryInfoCollector
|
||||||
from qlib.rl.simulator import Simulator, InitialStateType, StateType, ActType
|
from qlib.rl.interpreter import ActionInterpreter, ObsType, PolicyActType, StateInterpreter
|
||||||
from qlib.rl.interpreter import StateInterpreter, ActionInterpreter, PolicyActType, ObsType
|
|
||||||
from qlib.rl.reward import Reward
|
from qlib.rl.reward import Reward
|
||||||
|
from qlib.rl.simulator import ActType, InitialStateType, Simulator, StateType
|
||||||
from qlib.typehint import TypedDict
|
from qlib.typehint import TypedDict
|
||||||
|
|
||||||
from .finite_env import generate_nan_observation
|
from .finite_env import generate_nan_observation
|
||||||
@@ -28,7 +29,7 @@ class InfoDict(TypedDict):
|
|||||||
|
|
||||||
aux_info: dict
|
aux_info: dict
|
||||||
"""Any information depends on auxiliary info collector."""
|
"""Any information depends on auxiliary info collector."""
|
||||||
log: dict[str, Any]
|
log: Dict[str, Any]
|
||||||
"""Collected by LogCollector."""
|
"""Collected by LogCollector."""
|
||||||
|
|
||||||
|
|
||||||
@@ -42,14 +43,15 @@ class EnvWrapperStatus(TypedDict):
|
|||||||
|
|
||||||
cur_step: int
|
cur_step: int
|
||||||
done: bool
|
done: bool
|
||||||
initial_state: Any | None
|
initial_state: Optional[Any]
|
||||||
obs_history: list
|
obs_history: list
|
||||||
action_history: list
|
action_history: list
|
||||||
reward_history: list
|
reward_history: list
|
||||||
|
|
||||||
|
|
||||||
class EnvWrapper(
|
class EnvWrapper(
|
||||||
gym.Env[ObsType, PolicyActType], Generic[InitialStateType, StateType, ActType, ObsType, PolicyActType]
|
gym.Env[ObsType, PolicyActType],
|
||||||
|
Generic[InitialStateType, StateType, ActType, ObsType, PolicyActType],
|
||||||
):
|
):
|
||||||
"""Qlib-based RL environment, subclassing ``gym.Env``.
|
"""Qlib-based RL environment, subclassing ``gym.Env``.
|
||||||
A wrapper of components, including simulator, state-interpreter, action-interpreter, reward.
|
A wrapper of components, including simulator, state-interpreter, action-interpreter, reward.
|
||||||
@@ -97,11 +99,11 @@ class EnvWrapper(
|
|||||||
simulator_fn: Callable[..., Simulator[InitialStateType, StateType, ActType]],
|
simulator_fn: Callable[..., Simulator[InitialStateType, StateType, ActType]],
|
||||||
state_interpreter: StateInterpreter[StateType, ObsType],
|
state_interpreter: StateInterpreter[StateType, ObsType],
|
||||||
action_interpreter: ActionInterpreter[StateType, PolicyActType, ActType],
|
action_interpreter: ActionInterpreter[StateType, PolicyActType, ActType],
|
||||||
seed_iterator: Iterable[InitialStateType] | None,
|
seed_iterator: Optional[Iterable[InitialStateType]],
|
||||||
reward_fn: Reward | None = None,
|
reward_fn: Reward = None,
|
||||||
aux_info_collector: AuxiliaryInfoCollector[StateType, Any] | None = None,
|
aux_info_collector: AuxiliaryInfoCollector[StateType, Any] = None,
|
||||||
logger: LogCollector | None = None,
|
logger: LogCollector = None,
|
||||||
):
|
) -> None:
|
||||||
# Assign weak reference to wrapper.
|
# Assign weak reference to wrapper.
|
||||||
#
|
#
|
||||||
# Use weak reference here, because:
|
# Use weak reference here, because:
|
||||||
@@ -135,11 +137,11 @@ class EnvWrapper(
|
|||||||
self.status: EnvWrapperStatus = cast(EnvWrapperStatus, None)
|
self.status: EnvWrapperStatus = cast(EnvWrapperStatus, None)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def action_space(self):
|
def action_space(self) -> Space:
|
||||||
return self.action_interpreter.action_space
|
return self.action_interpreter.action_space
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def observation_space(self):
|
def observation_space(self) -> Space:
|
||||||
return self.state_interpreter.observation_space
|
return self.state_interpreter.observation_space
|
||||||
|
|
||||||
def reset(self, **kwargs: Any) -> ObsType:
|
def reset(self, **kwargs: Any) -> ObsType:
|
||||||
@@ -191,7 +193,7 @@ class EnvWrapper(
|
|||||||
self.seed_iterator = None
|
self.seed_iterator = None
|
||||||
return generate_nan_observation(self.observation_space)
|
return generate_nan_observation(self.observation_space)
|
||||||
|
|
||||||
def step(self, policy_action: PolicyActType, **kwargs: Any) -> tuple[ObsType, float, bool, InfoDict]:
|
def step(self, policy_action: PolicyActType, **kwargs: Any) -> Tuple[ObsType, float, bool, InfoDict]:
|
||||||
"""Environment step.
|
"""Environment step.
|
||||||
|
|
||||||
See the code along with comments to get a sequence of things happening here.
|
See the code along with comments to get a sequence of things happening here.
|
||||||
@@ -245,5 +247,5 @@ class EnvWrapper(
|
|||||||
info_dict = InfoDict(log=self.logger.logs(), aux_info=aux_info)
|
info_dict = InfoDict(log=self.logger.logs(), aux_info=aux_info)
|
||||||
return obs, rew, done, info_dict
|
return obs, rew, done, info_dict
|
||||||
|
|
||||||
def render(self):
|
def render(self, mode: str = "human") -> None:
|
||||||
raise NotImplementedError("Render is not implemented in EnvWrapper.")
|
raise NotImplementedError("Render is not implemented in EnvWrapper.")
|
||||||
|
|||||||
@@ -11,11 +11,10 @@ from __future__ import annotations
|
|||||||
import copy
|
import copy
|
||||||
import warnings
|
import warnings
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
|
from typing import Any, Callable, cast, Dict, Generator, List, Optional, Set, Tuple, Type, Union
|
||||||
|
|
||||||
import gym
|
import gym
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from typing import Any, Set, Callable, Type
|
|
||||||
|
|
||||||
from tianshou.env import BaseVectorEnv, DummyVectorEnv, ShmemVectorEnv, SubprocVectorEnv
|
from tianshou.env import BaseVectorEnv, DummyVectorEnv, ShmemVectorEnv, SubprocVectorEnv
|
||||||
|
|
||||||
from qlib.typehint import Literal
|
from qlib.typehint import Literal
|
||||||
@@ -32,11 +31,11 @@ __all__ = [
|
|||||||
"vectorize_env",
|
"vectorize_env",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
FiniteEnvType = Literal["dummy", "subproc", "shmem"]
|
FiniteEnvType = Literal["dummy", "subproc", "shmem"]
|
||||||
|
T = Union[dict, list, tuple, np.ndarray]
|
||||||
|
|
||||||
|
|
||||||
def fill_invalid(obj):
|
def fill_invalid(obj: int | float | bool | T) -> T:
|
||||||
if isinstance(obj, (int, float, bool)):
|
if isinstance(obj, (int, float, bool)):
|
||||||
return fill_invalid(np.array(obj))
|
return fill_invalid(np.array(obj))
|
||||||
if hasattr(obj, "dtype"):
|
if hasattr(obj, "dtype"):
|
||||||
@@ -55,11 +54,11 @@ def fill_invalid(obj):
|
|||||||
raise ValueError(f"Unsupported value to fill with invalid: {obj}")
|
raise ValueError(f"Unsupported value to fill with invalid: {obj}")
|
||||||
|
|
||||||
|
|
||||||
def is_invalid(arr):
|
def is_invalid(arr: int | float | bool | T) -> bool:
|
||||||
if hasattr(arr, "dtype"):
|
if isinstance(arr, np.ndarray):
|
||||||
if np.issubdtype(arr.dtype, np.floating):
|
if np.issubdtype(arr.dtype, np.floating):
|
||||||
return np.isnan(arr).all()
|
return np.isnan(arr).all()
|
||||||
return (np.iinfo(arr.dtype).max == arr).all()
|
return cast(bool, cast(np.ndarray, np.iinfo(arr.dtype).max == arr).all())
|
||||||
if isinstance(arr, dict):
|
if isinstance(arr, dict):
|
||||||
return all(is_invalid(o) for o in arr.values())
|
return all(is_invalid(o) for o in arr.values())
|
||||||
if isinstance(arr, (list, tuple)):
|
if isinstance(arr, (list, tuple)):
|
||||||
@@ -140,44 +139,44 @@ class FiniteVectorEnv(BaseVectorEnv):
|
|||||||
|
|
||||||
self._collector_guarded: bool = False
|
self._collector_guarded: bool = False
|
||||||
|
|
||||||
def _reset_alive_envs(self):
|
def _reset_alive_envs(self) -> None:
|
||||||
if not self._alive_env_ids:
|
if not self._alive_env_ids:
|
||||||
# starting or running out
|
# starting or running out
|
||||||
self._alive_env_ids = set(range(self.env_num))
|
self._alive_env_ids = set(range(self.env_num))
|
||||||
|
|
||||||
# to workaround with tianshou's buffer and batch
|
# to workaround with tianshou's buffer and batch
|
||||||
def _set_default_obs(self, obs):
|
def _set_default_obs(self, obs: Any) -> None:
|
||||||
if obs is not None and self._default_obs is None:
|
if obs is not None and self._default_obs is None:
|
||||||
self._default_obs = copy.deepcopy(obs)
|
self._default_obs = copy.deepcopy(obs)
|
||||||
|
|
||||||
def _set_default_info(self, info):
|
def _set_default_info(self, info: Any) -> None:
|
||||||
if info is not None and self._default_info is None:
|
if info is not None and self._default_info is None:
|
||||||
self._default_info = copy.deepcopy(info)
|
self._default_info = copy.deepcopy(info)
|
||||||
|
|
||||||
def _set_default_rew(self, rew):
|
def _set_default_rew(self, rew: Any) -> None:
|
||||||
if rew is not None and self._default_rew is None:
|
if rew is not None and self._default_rew is None:
|
||||||
self._default_rew = copy.deepcopy(rew)
|
self._default_rew = copy.deepcopy(rew)
|
||||||
|
|
||||||
def _get_default_obs(self):
|
def _get_default_obs(self) -> Any:
|
||||||
return copy.deepcopy(self._default_obs)
|
return copy.deepcopy(self._default_obs)
|
||||||
|
|
||||||
def _get_default_info(self):
|
def _get_default_info(self) -> Any:
|
||||||
return copy.deepcopy(self._default_info)
|
return copy.deepcopy(self._default_info)
|
||||||
|
|
||||||
def _get_default_rew(self):
|
def _get_default_rew(self) -> Any:
|
||||||
return copy.deepcopy(self._default_rew)
|
return copy.deepcopy(self._default_rew)
|
||||||
|
|
||||||
# END
|
# END
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _postproc_env_obs(obs):
|
def _postproc_env_obs(obs: Any) -> Optional[Any]:
|
||||||
# reserved for shmem vector env to restore empty observation
|
# reserved for shmem vector env to restore empty observation
|
||||||
if obs is None or check_nan_observation(obs):
|
if obs is None or check_nan_observation(obs):
|
||||||
return None
|
return None
|
||||||
return obs
|
return obs
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def collector_guard(self):
|
def collector_guard(self) -> Generator[FiniteVectorEnv, None, None]:
|
||||||
"""Guard the collector. Recommended to guard every collect.
|
"""Guard the collector. Recommended to guard every collect.
|
||||||
|
|
||||||
This guard is for two purposes.
|
This guard is for two purposes.
|
||||||
@@ -207,7 +206,10 @@ class FiniteVectorEnv(BaseVectorEnv):
|
|||||||
for logger in self._logger:
|
for logger in self._logger:
|
||||||
logger.on_env_all_done()
|
logger.on_env_all_done()
|
||||||
|
|
||||||
def reset(self, id=None):
|
def reset(
|
||||||
|
self,
|
||||||
|
id: int | List[int] | np.ndarray | None = None,
|
||||||
|
) -> np.ndarray:
|
||||||
assert not self._zombie
|
assert not self._zombie
|
||||||
|
|
||||||
# Check whether it's guarded by collector_guard()
|
# Check whether it's guarded by collector_guard()
|
||||||
@@ -219,23 +221,23 @@ class FiniteVectorEnv(BaseVectorEnv):
|
|||||||
RuntimeWarning,
|
RuntimeWarning,
|
||||||
)
|
)
|
||||||
|
|
||||||
id = self._wrap_id(id)
|
wrapped_id = self._wrap_id(id)
|
||||||
self._reset_alive_envs()
|
self._reset_alive_envs()
|
||||||
|
|
||||||
# ask super to reset alive envs and remap to current index
|
# ask super to reset alive envs and remap to current index
|
||||||
request_id = list(filter(lambda i: i in self._alive_env_ids, id))
|
request_id = [i for i in wrapped_id if i in self._alive_env_ids]
|
||||||
obs = [None] * len(id)
|
obs = [None] * len(wrapped_id)
|
||||||
id2idx = {i: k for k, i in enumerate(id)}
|
id2idx = {i: k for k, i in enumerate(wrapped_id)}
|
||||||
if request_id:
|
if request_id:
|
||||||
for i, o in zip(request_id, super().reset(request_id)):
|
for i, o in zip(request_id, super().reset(request_id)):
|
||||||
obs[id2idx[i]] = self._postproc_env_obs(o)
|
obs[id2idx[i]] = self._postproc_env_obs(o)
|
||||||
|
|
||||||
for i, o in zip(id, obs):
|
for i, o in zip(wrapped_id, obs):
|
||||||
if o is None and i in self._alive_env_ids:
|
if o is None and i in self._alive_env_ids:
|
||||||
self._alive_env_ids.remove(i)
|
self._alive_env_ids.remove(i)
|
||||||
|
|
||||||
# logging
|
# logging
|
||||||
for i, o in zip(id, obs):
|
for i, o in zip(wrapped_id, obs):
|
||||||
if i in self._alive_env_ids:
|
if i in self._alive_env_ids:
|
||||||
for logger in self._logger:
|
for logger in self._logger:
|
||||||
logger.on_env_reset(i, obs)
|
logger.on_env_reset(i, obs)
|
||||||
@@ -248,19 +250,23 @@ class FiniteVectorEnv(BaseVectorEnv):
|
|||||||
obs[i] = self._get_default_obs()
|
obs[i] = self._get_default_obs()
|
||||||
|
|
||||||
if not self._alive_env_ids:
|
if not self._alive_env_ids:
|
||||||
# comment this line so that the env becomes indisposable
|
# comment this line so that the env becomes indispensable
|
||||||
# self.reset()
|
# self.reset()
|
||||||
self._zombie = True
|
self._zombie = True
|
||||||
raise StopIteration
|
raise StopIteration
|
||||||
|
|
||||||
return np.stack(obs)
|
return np.stack(obs)
|
||||||
|
|
||||||
def step(self, action, id=None):
|
def step(
|
||||||
|
self,
|
||||||
|
action: np.ndarray,
|
||||||
|
id: int | List[int] | np.ndarray | None = None,
|
||||||
|
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
||||||
assert not self._zombie
|
assert not self._zombie
|
||||||
id = self._wrap_id(id)
|
wrapped_id = self._wrap_id(id)
|
||||||
id2idx = {i: k for k, i in enumerate(id)}
|
id2idx = {i: k for k, i in enumerate(wrapped_id)}
|
||||||
request_id = list(filter(lambda i: i in self._alive_env_ids, id))
|
request_id = list(filter(lambda i: i in self._alive_env_ids, wrapped_id))
|
||||||
result = [[None, None, False, None] for _ in range(len(id))]
|
result = [[None, None, False, None] for _ in range(len(wrapped_id))]
|
||||||
|
|
||||||
# ask super to step alive envs and remap to current index
|
# ask super to step alive envs and remap to current index
|
||||||
if request_id:
|
if request_id:
|
||||||
@@ -270,7 +276,7 @@ class FiniteVectorEnv(BaseVectorEnv):
|
|||||||
result[id2idx[i]][0] = self._postproc_env_obs(result[id2idx[i]][0])
|
result[id2idx[i]][0] = self._postproc_env_obs(result[id2idx[i]][0])
|
||||||
|
|
||||||
# logging
|
# logging
|
||||||
for i, r in zip(id, result):
|
for i, r in zip(wrapped_id, result):
|
||||||
if i in self._alive_env_ids:
|
if i in self._alive_env_ids:
|
||||||
for logger in self._logger:
|
for logger in self._logger:
|
||||||
logger.on_env_step(i, *r)
|
logger.on_env_step(i, *r)
|
||||||
@@ -287,7 +293,8 @@ class FiniteVectorEnv(BaseVectorEnv):
|
|||||||
if r[3] is None:
|
if r[3] is None:
|
||||||
result[i][3] = self._get_default_info()
|
result[i][3] = self._get_default_info()
|
||||||
|
|
||||||
return list(map(np.stack, zip(*result)))
|
ret = list(map(np.stack, zip(*result)))
|
||||||
|
return cast(Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], ret)
|
||||||
|
|
||||||
|
|
||||||
class FiniteDummyVectorEnv(FiniteVectorEnv, DummyVectorEnv):
|
class FiniteDummyVectorEnv(FiniteVectorEnv, DummyVectorEnv):
|
||||||
@@ -306,7 +313,7 @@ def vectorize_env(
|
|||||||
env_factory: Callable[..., gym.Env],
|
env_factory: Callable[..., gym.Env],
|
||||||
env_type: FiniteEnvType,
|
env_type: FiniteEnvType,
|
||||||
concurrency: int,
|
concurrency: int,
|
||||||
logger: LogWriter | list[LogWriter],
|
logger: LogWriter | List[LogWriter],
|
||||||
) -> FiniteVectorEnv:
|
) -> FiniteVectorEnv:
|
||||||
"""Helper function to create a vector env. Can be used to replace usual VectorEnv.
|
"""Helper function to create a vector env. Can be used to replace usual VectorEnv.
|
||||||
|
|
||||||
@@ -350,7 +357,7 @@ def vectorize_env(
|
|||||||
def env_factory(): ...
|
def env_factory(): ...
|
||||||
vectorize_env(env_factory, ...)
|
vectorize_env(env_factory, ...)
|
||||||
"""
|
"""
|
||||||
env_type_cls_mapping: dict[str, Type[FiniteVectorEnv]] = {
|
env_type_cls_mapping: Dict[str, Type[FiniteVectorEnv]] = {
|
||||||
"dummy": FiniteDummyVectorEnv,
|
"dummy": FiniteDummyVectorEnv,
|
||||||
"subproc": FiniteSubprocVectorEnv,
|
"subproc": FiniteSubprocVectorEnv,
|
||||||
"shmem": FiniteShmemVectorEnv,
|
"shmem": FiniteShmemVectorEnv,
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import logging
|
|||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from enum import IntEnum
|
from enum import IntEnum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, TypeVar, Generic, Set, TYPE_CHECKING, Sequence, Callable
|
from typing import TYPE_CHECKING, Any, Callable, Dict, Generic, List, Sequence, Set, Tuple, TypeVar
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -65,13 +65,13 @@ class LogCollector:
|
|||||||
``min_loglevel`` is for optimization purposes: to avoid too much traffic on networks / in pipe.
|
``min_loglevel`` is for optimization purposes: to avoid too much traffic on networks / in pipe.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_logged: dict[str, tuple[int, Any]]
|
_logged: Dict[str, Tuple[int, Any]]
|
||||||
_min_loglevel: int
|
_min_loglevel: int
|
||||||
|
|
||||||
def __init__(self, min_loglevel: int | LogLevel = LogLevel.PERIODIC):
|
def __init__(self, min_loglevel: int | LogLevel = LogLevel.PERIODIC) -> None:
|
||||||
self._min_loglevel = int(min_loglevel)
|
self._min_loglevel = int(min_loglevel)
|
||||||
|
|
||||||
def reset(self):
|
def reset(self) -> None:
|
||||||
"""Clear all collected contents."""
|
"""Clear all collected contents."""
|
||||||
self._logged = {}
|
self._logged = {}
|
||||||
|
|
||||||
@@ -104,7 +104,10 @@ class LogCollector:
|
|||||||
self._add_metric(name, scalar, loglevel)
|
self._add_metric(name, scalar, loglevel)
|
||||||
|
|
||||||
def add_array(
|
def add_array(
|
||||||
self, name: str, array: np.ndarray | pd.DataFrame | pd.Series, loglevel: int | LogLevel = LogLevel.PERIODIC
|
self,
|
||||||
|
name: str,
|
||||||
|
array: np.ndarray | pd.DataFrame | pd.Series,
|
||||||
|
loglevel: int | LogLevel = LogLevel.PERIODIC,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Add an array with name into logging."""
|
"""Add an array with name into logging."""
|
||||||
if loglevel < self._min_loglevel:
|
if loglevel < self._min_loglevel:
|
||||||
@@ -127,7 +130,7 @@ class LogCollector:
|
|||||||
|
|
||||||
self._add_metric(name, obj, loglevel)
|
self._add_metric(name, obj, loglevel)
|
||||||
|
|
||||||
def logs(self) -> dict[str, np.ndarray]:
|
def logs(self) -> Dict[str, np.ndarray]:
|
||||||
return {key: np.asanyarray(value, dtype="object") for key, value in self._logged.items()}
|
return {key: np.asanyarray(value, dtype="object") for key, value in self._logged.items()}
|
||||||
|
|
||||||
|
|
||||||
@@ -154,16 +157,16 @@ class LogWriter(Generic[ObsType, ActType]):
|
|||||||
active_env_ids: Set[int]
|
active_env_ids: Set[int]
|
||||||
"""Active environment ids in vector env."""
|
"""Active environment ids in vector env."""
|
||||||
|
|
||||||
episode_lengths: dict[int, int]
|
episode_lengths: Dict[int, int]
|
||||||
"""Map from environment id to episode length."""
|
"""Map from environment id to episode length."""
|
||||||
|
|
||||||
episode_rewards: dict[int, list[float]]
|
episode_rewards: Dict[int, List[float]]
|
||||||
"""Map from environment id to episode total reward."""
|
"""Map from environment id to episode total reward."""
|
||||||
|
|
||||||
episode_logs: dict[int, list]
|
episode_logs: Dict[int, list]
|
||||||
"""Map from environment id to episode logs."""
|
"""Map from environment id to episode logs."""
|
||||||
|
|
||||||
def __init__(self, loglevel: int | LogLevel = LogLevel.PERIODIC):
|
def __init__(self, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None:
|
||||||
self.loglevel = loglevel
|
self.loglevel = loglevel
|
||||||
|
|
||||||
self.global_step = 0
|
self.global_step = 0
|
||||||
@@ -207,11 +210,12 @@ class LogWriter(Generic[ObsType, ActType]):
|
|||||||
# These are runtime infos.
|
# These are runtime infos.
|
||||||
# Though they are loaded, I don't think it really helps.
|
# Though they are loaded, I don't think it really helps.
|
||||||
self.active_env_ids = state_dict["active_env_ids"]
|
self.active_env_ids = state_dict["active_env_ids"]
|
||||||
self.episode_lenghts = state_dict["episode_lengths"]
|
self.episode_lengths = state_dict["episode_lengths"]
|
||||||
self.episode_rewards = state_dict["episode_rewards"]
|
self.episode_rewards = state_dict["episode_rewards"]
|
||||||
self.episode_logs = state_dict["episode_logs"]
|
self.episode_logs = state_dict["episode_logs"]
|
||||||
|
|
||||||
def aggregation(self, array: Sequence[Any], name: str | None = None) -> Any:
|
@staticmethod
|
||||||
|
def aggregation(array: Sequence[Any], name: str | None = None) -> Any:
|
||||||
"""Aggregation function from step-wise to episode-wise.
|
"""Aggregation function from step-wise to episode-wise.
|
||||||
|
|
||||||
If it's a sequence of float, take the mean.
|
If it's a sequence of float, take the mean.
|
||||||
@@ -229,7 +233,7 @@ class LogWriter(Generic[ObsType, ActType]):
|
|||||||
else:
|
else:
|
||||||
return array[0]
|
return array[0]
|
||||||
|
|
||||||
def log_episode(self, length: int, rewards: list[float], contents: list[dict[str, Any]]) -> None:
|
def log_episode(self, length: int, rewards: List[float], contents: List[Dict[str, Any]]) -> None:
|
||||||
"""This is triggered at the end of each trajectory.
|
"""This is triggered at the end of each trajectory.
|
||||||
|
|
||||||
Parameters
|
Parameters
|
||||||
@@ -242,7 +246,7 @@ class LogWriter(Generic[ObsType, ActType]):
|
|||||||
Logged contents for every steps.
|
Logged contents for every steps.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def log_step(self, reward: float, contents: dict[str, Any]) -> None:
|
def log_step(self, reward: float, contents: Dict[str, Any]) -> None:
|
||||||
"""This is triggered at each step.
|
"""This is triggered at each step.
|
||||||
|
|
||||||
Parameters
|
Parameters
|
||||||
@@ -265,7 +269,7 @@ class LogWriter(Generic[ObsType, ActType]):
|
|||||||
# TODO: reward can be a list of list for MARL
|
# TODO: reward can be a list of list for MARL
|
||||||
self.episode_rewards[env_id].append(rew)
|
self.episode_rewards[env_id].append(rew)
|
||||||
|
|
||||||
values: dict[str, Any] = {}
|
values: Dict[str, Any] = {}
|
||||||
|
|
||||||
for key, (loglevel, value) in info["log"].items():
|
for key, (loglevel, value) in info["log"].items():
|
||||||
if loglevel >= self.loglevel: # FIXME: this is actually incorrect (see last FIXME)
|
if loglevel >= self.loglevel: # FIXME: this is actually incorrect (see last FIXME)
|
||||||
@@ -393,11 +397,11 @@ class ConsoleWriter(LogWriter):
|
|||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
log_every_n_episode: int = 20,
|
log_every_n_episode: int = 20,
|
||||||
total_episodes: int | None = None,
|
total_episodes: int = None,
|
||||||
float_format: str = ":.4f",
|
float_format: str = ":.4f",
|
||||||
counter_format: str = ":4d",
|
counter_format: str = ":4d",
|
||||||
loglevel: int | LogLevel = LogLevel.PERIODIC,
|
loglevel: int | LogLevel = LogLevel.PERIODIC,
|
||||||
):
|
) -> None:
|
||||||
super().__init__(loglevel)
|
super().__init__(loglevel)
|
||||||
# TODO: support log_every_n_step
|
# TODO: support log_every_n_step
|
||||||
self.log_every_n_episode = log_every_n_episode
|
self.log_every_n_episode = log_every_n_episode
|
||||||
@@ -412,15 +416,15 @@ class ConsoleWriter(LogWriter):
|
|||||||
|
|
||||||
# FIXME: save & reload
|
# FIXME: save & reload
|
||||||
|
|
||||||
def clear(self):
|
def clear(self) -> None:
|
||||||
super().clear()
|
super().clear()
|
||||||
# Clear average meters
|
# Clear average meters
|
||||||
self.metric_counts: dict[str, int] = defaultdict(int)
|
self.metric_counts: Dict[str, int] = defaultdict(int)
|
||||||
self.metric_sums: dict[str, float] = defaultdict(float)
|
self.metric_sums: Dict[str, float] = defaultdict(float)
|
||||||
|
|
||||||
def log_episode(self, length: int, rewards: list[float], contents: list[dict[str, Any]]) -> None:
|
def log_episode(self, length: int, rewards: List[float], contents: List[Dict[str, Any]]) -> None:
|
||||||
# Aggregate step-wise to episode-wise
|
# Aggregate step-wise to episode-wise
|
||||||
episode_wise_contents: dict[str, list] = defaultdict(list)
|
episode_wise_contents: Dict[str, list] = defaultdict(list)
|
||||||
|
|
||||||
for step_contents in contents:
|
for step_contents in contents:
|
||||||
for name, value in step_contents.items():
|
for name, value in step_contents.items():
|
||||||
@@ -429,7 +433,7 @@ class ConsoleWriter(LogWriter):
|
|||||||
|
|
||||||
# Generate log contents and track them in average-meter.
|
# Generate log contents and track them in average-meter.
|
||||||
# This should be done at every step, regardless of periodic or not.
|
# This should be done at every step, regardless of periodic or not.
|
||||||
logs: dict[str, float] = {}
|
logs: Dict[str, float] = {}
|
||||||
for name, values in episode_wise_contents.items():
|
for name, values in episode_wise_contents.items():
|
||||||
logs[name] = self.aggregation(values, name) # type: ignore
|
logs[name] = self.aggregation(values, name) # type: ignore
|
||||||
|
|
||||||
@@ -441,7 +445,7 @@ class ConsoleWriter(LogWriter):
|
|||||||
# Only log periodically or at the end
|
# Only log periodically or at the end
|
||||||
self.console_logger.info(self.generate_log_message(logs))
|
self.console_logger.info(self.generate_log_message(logs))
|
||||||
|
|
||||||
def generate_log_message(self, logs: dict[str, float]) -> str:
|
def generate_log_message(self, logs: Dict[str, float]) -> str:
|
||||||
if self.prefix:
|
if self.prefix:
|
||||||
msg_prefix = self.prefix + " "
|
msg_prefix = self.prefix + " "
|
||||||
else:
|
else:
|
||||||
@@ -471,29 +475,29 @@ class CsvWriter(LogWriter):
|
|||||||
|
|
||||||
SUPPORTED_TYPES = (float, str, pd.Timestamp)
|
SUPPORTED_TYPES = (float, str, pd.Timestamp)
|
||||||
|
|
||||||
all_records: list[dict[str, Any]]
|
all_records: List[Dict[str, Any]]
|
||||||
|
|
||||||
# FIXME: save & reload
|
# FIXME: save & reload
|
||||||
|
|
||||||
def __init__(self, output_dir: Path, loglevel: int | LogLevel = LogLevel.PERIODIC):
|
def __init__(self, output_dir: Path, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None:
|
||||||
super().__init__(loglevel)
|
super().__init__(loglevel)
|
||||||
self.output_dir = output_dir
|
self.output_dir = output_dir
|
||||||
self.output_dir.mkdir(exist_ok=True)
|
self.output_dir.mkdir(exist_ok=True)
|
||||||
|
|
||||||
def clear(self):
|
def clear(self) -> None:
|
||||||
super().clear()
|
super().clear()
|
||||||
self.all_records = []
|
self.all_records = []
|
||||||
|
|
||||||
def log_episode(self, length: int, rewards: list[float], contents: list[dict[str, Any]]) -> None:
|
def log_episode(self, length: int, rewards: List[float], contents: List[Dict[str, Any]]) -> None:
|
||||||
# FIXME Same as ConsoleLogger, needs a refactor to eliminate code-dup
|
# FIXME Same as ConsoleLogger, needs a refactor to eliminate code-dup
|
||||||
episode_wise_contents: dict[str, list] = defaultdict(list)
|
episode_wise_contents: Dict[str, list] = defaultdict(list)
|
||||||
|
|
||||||
for step_contents in contents:
|
for step_contents in contents:
|
||||||
for name, value in step_contents.items():
|
for name, value in step_contents.items():
|
||||||
if isinstance(value, self.SUPPORTED_TYPES):
|
if isinstance(value, self.SUPPORTED_TYPES):
|
||||||
episode_wise_contents[name].append(value)
|
episode_wise_contents[name].append(value)
|
||||||
|
|
||||||
logs: dict[str, float] = {}
|
logs: Dict[str, float] = {}
|
||||||
for name, values in episode_wise_contents.items():
|
for name, values in episode_wise_contents.items():
|
||||||
logs[name] = self.aggregation(values, name) # type: ignore
|
logs[name] = self.aggregation(values, name) # type: ignore
|
||||||
|
|
||||||
|
|||||||
0
qlib/run/__init__.py
Normal file
0
qlib/run/__init__.py
Normal file
9
qlib/run/get_data.py
Normal file
9
qlib/run/get_data.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# Copyright (c) Microsoft Corporation.
|
||||||
|
# Licensed under the MIT License.
|
||||||
|
|
||||||
|
import fire
|
||||||
|
from qlib.tests.data import GetData
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
fire.Fire(GetData)
|
||||||
@@ -2,14 +2,14 @@
|
|||||||
# Licensed under the MIT License.
|
# Licensed under the MIT License.
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from abc import abstractmethod
|
from abc import ABCMeta, abstractmethod
|
||||||
from typing import TYPE_CHECKING, Any, Generator, Optional
|
from typing import Any, Generator, Optional, TYPE_CHECKING, Union
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from qlib.backtest.exchange import Exchange
|
from qlib.backtest.exchange import Exchange
|
||||||
from qlib.backtest.position import BasePosition
|
from qlib.backtest.position import BasePosition
|
||||||
|
|
||||||
from typing import Tuple, Union
|
from typing import Tuple
|
||||||
|
|
||||||
from ..backtest.decision import BaseTradeDecision
|
from ..backtest.decision import BaseTradeDecision
|
||||||
from ..backtest.utils import CommonInfrastructure, LevelInfrastructure, TradeCalendarManager
|
from ..backtest.utils import CommonInfrastructure, LevelInfrastructure, TradeCalendarManager
|
||||||
@@ -207,8 +207,18 @@ class BaseStrategy:
|
|||||||
range_limit = self.outer_trade_decision.get_data_cal_range_limit(rtype=rtype)
|
range_limit = self.outer_trade_decision.get_data_cal_range_limit(rtype=rtype)
|
||||||
return max(cal_range[0], range_limit[0]), min(cal_range[1], range_limit[1])
|
return max(cal_range[0], range_limit[0]), min(cal_range[1], range_limit[1])
|
||||||
|
|
||||||
|
def post_exe_step(self, execute_result: list) -> None:
|
||||||
|
"""
|
||||||
|
A hook for doing sth after the corresponding executor finished its execution.
|
||||||
|
|
||||||
class RLStrategy(BaseStrategy):
|
Parameters
|
||||||
|
----------
|
||||||
|
execute_result :
|
||||||
|
the execution result
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class RLStrategy(BaseStrategy, metaclass=ABCMeta):
|
||||||
"""RL-based strategy"""
|
"""RL-based strategy"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -229,14 +239,14 @@ class RLStrategy(BaseStrategy):
|
|||||||
self.policy = policy
|
self.policy = policy
|
||||||
|
|
||||||
|
|
||||||
class RLIntStrategy(RLStrategy):
|
class RLIntStrategy(RLStrategy, metaclass=ABCMeta):
|
||||||
"""(RL)-based (Strategy) with (Int)erpreter"""
|
"""(RL)-based (Strategy) with (Int)erpreter"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
policy,
|
policy,
|
||||||
state_interpreter: Union[dict, StateInterpreter],
|
state_interpreter: dict | StateInterpreter,
|
||||||
action_interpreter: Union[dict, ActionInterpreter],
|
action_interpreter: dict | ActionInterpreter,
|
||||||
outer_trade_decision: BaseTradeDecision = None,
|
outer_trade_decision: BaseTradeDecision = None,
|
||||||
level_infra: LevelInfrastructure = None,
|
level_infra: LevelInfrastructure = None,
|
||||||
common_infra: CommonInfrastructure = None,
|
common_infra: CommonInfrastructure = None,
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
"""Commonly used types."""
|
"""Commonly used types."""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
|
from typing import Union
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
__all__ = ["Literal", "TypedDict", "final"]
|
__all__ = ["Literal", "TypedDict", "final"]
|
||||||
|
|
||||||
@@ -11,3 +13,51 @@ if sys.version_info >= (3, 8):
|
|||||||
from typing import Literal, TypedDict, final # type: ignore # pylint: disable=no-name-in-module
|
from typing import Literal, TypedDict, final # type: ignore # pylint: disable=no-name-in-module
|
||||||
else:
|
else:
|
||||||
from typing_extensions import Literal, TypedDict, final
|
from typing_extensions import Literal, TypedDict, final
|
||||||
|
|
||||||
|
|
||||||
|
class InstDictConf(TypedDict):
|
||||||
|
"""
|
||||||
|
InstDictConf is a Dict-based config to describe an instance
|
||||||
|
|
||||||
|
case 1)
|
||||||
|
{
|
||||||
|
'class': 'ClassName',
|
||||||
|
'kwargs': dict, # It is optional. {} will be used if not given
|
||||||
|
'model_path': path, # It is optional if module is given in the class
|
||||||
|
}
|
||||||
|
case 2)
|
||||||
|
{
|
||||||
|
'class': <The class it self>,
|
||||||
|
'kwargs': dict, # It is optional. {} will be used if not given
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
# class: str # because class is a keyword of Python. We have to comment it
|
||||||
|
kwargs: dict # It is optional. {} will be used if not given
|
||||||
|
module_path: str # It is optional if module is given in the class
|
||||||
|
|
||||||
|
|
||||||
|
InstConf = Union[InstDictConf, str, object, Path]
|
||||||
|
"""
|
||||||
|
InstConf is a type to describe an instance; it will be passed into init_instance_by_config for Qlib
|
||||||
|
|
||||||
|
config : Union[str, dict, object, Path]
|
||||||
|
|
||||||
|
InstDictConf example.
|
||||||
|
please refer to the docs of InstDictConf
|
||||||
|
|
||||||
|
str example.
|
||||||
|
1) specify a pickle object
|
||||||
|
- path like 'file:///<path to pickle file>/obj.pkl'
|
||||||
|
2) specify a class name
|
||||||
|
- "ClassName": getattr(module, "ClassName")() will be used.
|
||||||
|
3) specify module path with class name
|
||||||
|
- "a.b.c.ClassName" getattr(<a.b.c.module>, "ClassName")() will be used.
|
||||||
|
|
||||||
|
object example:
|
||||||
|
instance of accept_types
|
||||||
|
|
||||||
|
Path example:
|
||||||
|
specify a pickle object
|
||||||
|
- it will be treated like 'file:///<path to pickle file>/obj.pkl'
|
||||||
|
"""
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import re
|
|||||||
import sys
|
import sys
|
||||||
import copy
|
import copy
|
||||||
import json
|
import json
|
||||||
|
from qlib.typehint import InstConf
|
||||||
import yaml
|
import yaml
|
||||||
import redis
|
import redis
|
||||||
import bisect
|
import bisect
|
||||||
@@ -291,7 +292,11 @@ def get_module_by_module_path(module_path: Union[str, ModuleType]):
|
|||||||
|
|
||||||
:param module_path:
|
:param module_path:
|
||||||
:return:
|
:return:
|
||||||
|
:raises: ModuleNotFoundError
|
||||||
"""
|
"""
|
||||||
|
if module_path is None:
|
||||||
|
raise ModuleNotFoundError("None is passed in as parameters as module_path")
|
||||||
|
|
||||||
if isinstance(module_path, ModuleType):
|
if isinstance(module_path, ModuleType):
|
||||||
module = module_path
|
module = module_path
|
||||||
else:
|
else:
|
||||||
@@ -324,7 +329,7 @@ def split_module_path(module_path: str) -> Tuple[str, str]:
|
|||||||
return m_path, cls
|
return m_path, cls
|
||||||
|
|
||||||
|
|
||||||
def get_callable_kwargs(config: Union[dict, str], default_module: Union[str, ModuleType] = None) -> (type, dict):
|
def get_callable_kwargs(config: InstConf, default_module: Union[str, ModuleType] = None) -> (type, dict):
|
||||||
"""
|
"""
|
||||||
extract class/func and kwargs from config info
|
extract class/func and kwargs from config info
|
||||||
|
|
||||||
@@ -343,6 +348,10 @@ def get_callable_kwargs(config: Union[dict, str], default_module: Union[str, Mod
|
|||||||
-------
|
-------
|
||||||
(type, dict):
|
(type, dict):
|
||||||
the class/func object and it's arguments.
|
the class/func object and it's arguments.
|
||||||
|
|
||||||
|
Raises
|
||||||
|
------
|
||||||
|
ModuleNotFoundError
|
||||||
"""
|
"""
|
||||||
if isinstance(config, dict):
|
if isinstance(config, dict):
|
||||||
key = "class" if "class" in config else "func"
|
key = "class" if "class" in config else "func"
|
||||||
@@ -376,7 +385,7 @@ get_cls_kwargs = get_callable_kwargs # NOTE: this is for compatibility for the
|
|||||||
|
|
||||||
|
|
||||||
def init_instance_by_config(
|
def init_instance_by_config(
|
||||||
config: Union[str, dict, object, Path], # TODO: use a user-defined type to replace this Union.
|
config: InstConf,
|
||||||
default_module=None,
|
default_module=None,
|
||||||
accept_types: Union[type, Tuple[type]] = (),
|
accept_types: Union[type, Tuple[type]] = (),
|
||||||
try_kwargs: Dict = {},
|
try_kwargs: Dict = {},
|
||||||
@@ -387,31 +396,8 @@ def init_instance_by_config(
|
|||||||
|
|
||||||
Parameters
|
Parameters
|
||||||
----------
|
----------
|
||||||
config : Union[str, dict, object]
|
config : InstConf
|
||||||
dict example.
|
|
||||||
case 1)
|
|
||||||
{
|
|
||||||
'class': 'ClassName',
|
|
||||||
'kwargs': dict, # It is optional. {} will be used if not given
|
|
||||||
'model_path': path, # It is optional if module is given
|
|
||||||
}
|
|
||||||
case 2)
|
|
||||||
{
|
|
||||||
'class': <The class it self>,
|
|
||||||
'kwargs': dict, # It is optional. {} will be used if not given
|
|
||||||
}
|
|
||||||
str example.
|
|
||||||
1) specify a pickle object
|
|
||||||
- path like 'file:///<path to pickle file>/obj.pkl'
|
|
||||||
2) specify a class name
|
|
||||||
- "ClassName": getattr(module, "ClassName")() will be used.
|
|
||||||
3) specify module path with class name
|
|
||||||
- "a.b.c.ClassName" getattr(<a.b.c.module>, "ClassName")() will be used.
|
|
||||||
object example:
|
|
||||||
instance of accept_types
|
|
||||||
Path example:
|
|
||||||
specify a pickle object
|
|
||||||
- it will be treated like 'file:///<path to pickle file>/obj.pkl'
|
|
||||||
default_module : Python module
|
default_module : Python module
|
||||||
Optional. It should be a python module.
|
Optional. It should be a python module.
|
||||||
NOTE: the "module_path" will be override by `module` arguments
|
NOTE: the "module_path" will be override by `module` arguments
|
||||||
@@ -518,7 +504,7 @@ def remove_fields_space(fields: [list, str, tuple]):
|
|||||||
"""
|
"""
|
||||||
if isinstance(fields, str):
|
if isinstance(fields, str):
|
||||||
return fields.replace(" ", "")
|
return fields.replace(" ", "")
|
||||||
return [i.replace(" ", "") for i in fields if isinstance(i, str)]
|
return [i.replace(" ", "") if isinstance(i, str) else str(i) for i in fields]
|
||||||
|
|
||||||
|
|
||||||
def normalize_cache_fields(fields: [list, tuple]):
|
def normalize_cache_fields(fields: [list, tuple]):
|
||||||
|
|||||||
@@ -271,7 +271,7 @@ class LocIndexer:
|
|||||||
if isinstance(_indexing, IndexData):
|
if isinstance(_indexing, IndexData):
|
||||||
_indexing = _indexing.data
|
_indexing = _indexing.data
|
||||||
assert _indexing.ndim == 1
|
assert _indexing.ndim == 1
|
||||||
if _indexing.dtype != np.bool:
|
if _indexing.dtype != bool:
|
||||||
_indexing = np.array(list(index.index(i) for i in _indexing))
|
_indexing = np.array(list(index.index(i) for i in _indexing))
|
||||||
else:
|
else:
|
||||||
_indexing = index.index(_indexing)
|
_indexing = index.index(_indexing)
|
||||||
@@ -431,7 +431,7 @@ class IndexData(metaclass=index_data_ops_creator):
|
|||||||
|
|
||||||
# The code below could be simpler like methods in __getattribute__
|
# The code below could be simpler like methods in __getattribute__
|
||||||
def __invert__(self):
|
def __invert__(self):
|
||||||
return self.__class__(~self.data.astype(np.bool), *self.indices)
|
return self.__class__(~self.data.astype(bool), *self.indices)
|
||||||
|
|
||||||
def abs(self):
|
def abs(self):
|
||||||
"""get the abs of data except np.NaN."""
|
"""get the abs of data except np.NaN."""
|
||||||
|
|||||||
@@ -575,6 +575,44 @@ class QlibRecorder:
|
|||||||
"""
|
"""
|
||||||
self.get_exp(start=True).get_recorder(start=True).log_metrics(step, **kwargs)
|
self.get_exp(start=True).get_recorder(start=True).log_metrics(step, **kwargs)
|
||||||
|
|
||||||
|
def log_artifact(self, local_path: str, artifact_path: Optional[str] = None):
|
||||||
|
"""
|
||||||
|
Log a local file or directory as an artifact of the currently active run
|
||||||
|
|
||||||
|
- If `active recorder` exists: it will set tags through the active recorder.
|
||||||
|
- If `active recorder` not exists: the system will create a default experiment as well as a new recorder, and set the tags under it.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
local_path : str
|
||||||
|
Path to the file to write.
|
||||||
|
artifact_path : Optional[str]
|
||||||
|
If provided, the directory in ``artifact_uri`` to write to.
|
||||||
|
"""
|
||||||
|
self.get_exp(start=True).get_recorder(start=True).log_artifact(local_path, artifact_path)
|
||||||
|
|
||||||
|
def download_artifact(self, path: str, dst_path: Optional[str] = None) -> str:
|
||||||
|
"""
|
||||||
|
Download an artifact file or directory from a run to a local directory if applicable,
|
||||||
|
and return a local path for it.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
path : str
|
||||||
|
Relative source path to the desired artifact.
|
||||||
|
dst_path : Optional[str]
|
||||||
|
Absolute path of the local filesystem destination directory to which to
|
||||||
|
download the specified artifacts. This directory must already exist.
|
||||||
|
If unspecified, the artifacts will either be downloaded to a new
|
||||||
|
uniquely-named directory on the local filesystem.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str
|
||||||
|
Local path of desired artifact.
|
||||||
|
"""
|
||||||
|
self.get_exp(start=True).get_recorder(start=True).download_artifact(path, dst_path)
|
||||||
|
|
||||||
def set_tags(self, **kwargs):
|
def set_tags(self, **kwargs):
|
||||||
"""
|
"""
|
||||||
Method for setting tags for a recorder. In addition to using ``R``, one can also set the tag to a specific recorder after getting it with `get_recorder` API.
|
Method for setting tags for a recorder. In addition to using ``R``, one can also set the tag to a specific recorder after getting it with `get_recorder` API.
|
||||||
@@ -611,7 +649,7 @@ class RecorderWrapper(Wrapper):
|
|||||||
expm = getattr(self._provider, "exp_manager")
|
expm = getattr(self._provider, "exp_manager")
|
||||||
if expm.active_experiment is not None:
|
if expm.active_experiment is not None:
|
||||||
raise RecorderInitializationError(
|
raise RecorderInitializationError(
|
||||||
"Please don't reinitialize Qlib if QlibRecorder is already acivated. Otherwise, the experiment stored location will be modified."
|
"Please don't reinitialize Qlib if QlibRecorder is already activated. Otherwise, the experiment stored location will be modified."
|
||||||
)
|
)
|
||||||
self._provider = provider
|
self._provider = provider
|
||||||
|
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ class Experiment:
|
|||||||
"""
|
"""
|
||||||
raise NotImplementedError(f"Please implement the `delete_recorder` method.")
|
raise NotImplementedError(f"Please implement the `delete_recorder` method.")
|
||||||
|
|
||||||
def get_recorder(self, recorder_id=None, recorder_name=None, create: bool = True, start: bool = False):
|
def get_recorder(self, recorder_id=None, recorder_name=None, create: bool = True, start: bool = False) -> Recorder:
|
||||||
"""
|
"""
|
||||||
Retrieve a Recorder for user. When user specify recorder id and name, the method will try to return the
|
Retrieve a Recorder for user. When user specify recorder id and name, the method will try to return the
|
||||||
specific recorder. When user does not provide recorder id or name, the method will try to return the current
|
specific recorder. When user does not provide recorder id or name, the method will try to return the current
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
from typing import Optional
|
||||||
import mlflow
|
import mlflow
|
||||||
import logging
|
import logging
|
||||||
import shutil
|
import shutil
|
||||||
@@ -138,6 +139,19 @@ class Recorder:
|
|||||||
"""
|
"""
|
||||||
raise NotImplementedError(f"Please implement the `log_metrics` method.")
|
raise NotImplementedError(f"Please implement the `log_metrics` method.")
|
||||||
|
|
||||||
|
def log_artifact(self, local_path: str, artifact_path: Optional[str] = None):
|
||||||
|
"""
|
||||||
|
Log a local file or directory as an artifact of the currently active run.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
local_path : str
|
||||||
|
Path to the file to write.
|
||||||
|
artifact_path : Optional[str]
|
||||||
|
If provided, the directory in ``artifact_uri`` to write to.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError(f"Please implement the `log_metrics` method.")
|
||||||
|
|
||||||
def set_tags(self, **kwargs):
|
def set_tags(self, **kwargs):
|
||||||
"""
|
"""
|
||||||
Log a batch of tags for the current run.
|
Log a batch of tags for the current run.
|
||||||
@@ -175,6 +189,28 @@ class Recorder:
|
|||||||
"""
|
"""
|
||||||
raise NotImplementedError(f"Please implement the `list_artifacts` method.")
|
raise NotImplementedError(f"Please implement the `list_artifacts` method.")
|
||||||
|
|
||||||
|
def download_artifact(self, path: str, dst_path: Optional[str] = None) -> str:
|
||||||
|
"""
|
||||||
|
Download an artifact file or directory from a run to a local directory if applicable,
|
||||||
|
and return a local path for it.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
path : str
|
||||||
|
Relative source path to the desired artifact.
|
||||||
|
dst_path : Optional[str]
|
||||||
|
Absolute path of the local filesystem destination directory to which to
|
||||||
|
download the specified artifacts. This directory must already exist.
|
||||||
|
If unspecified, the artifacts will either be downloaded to a new
|
||||||
|
uniquely-named directory on the local filesystem.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str
|
||||||
|
Local path of desired artifact.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError(f"Please implement the `list_artifacts` method.")
|
||||||
|
|
||||||
def list_metrics(self):
|
def list_metrics(self):
|
||||||
"""
|
"""
|
||||||
List all the metrics of a recorder.
|
List all the metrics of a recorder.
|
||||||
@@ -212,6 +248,14 @@ class MLflowRecorder(Recorder):
|
|||||||
|
|
||||||
Due to the fact that mlflow will only log artifact from a file or directory, we decide to
|
Due to the fact that mlflow will only log artifact from a file or directory, we decide to
|
||||||
use file manager to help maintain the objects in the project.
|
use file manager to help maintain the objects in the project.
|
||||||
|
|
||||||
|
Instead of using mlflow directly, we use another interface wrapping mlflow to log experiments.
|
||||||
|
Though it takes extra efforts, but it brings users benefits due to following reasons.
|
||||||
|
- It will be more convenient to change the experiment logging backend without changing any code in upper level
|
||||||
|
- We can provide more convenience to automatically do some extra things and make interface easier. For examples:
|
||||||
|
- Automatically logging the uncommitted code
|
||||||
|
- Automatically logging part of environment variables
|
||||||
|
- User can control several different runs by just creating different Recorder (in mlflow, you always have to switch artifact_uri and pass in run ids frequently)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, experiment_id, uri, name=None, mlflow_run=None):
|
def __init__(self, experiment_id, uri, name=None, mlflow_run=None):
|
||||||
@@ -304,6 +348,9 @@ class MLflowRecorder(Recorder):
|
|||||||
self._log_uncommitted_code()
|
self._log_uncommitted_code()
|
||||||
|
|
||||||
self.log_params(**{"cmd-sys.argv": " ".join(sys.argv)}) # log the command to produce current experiment
|
self.log_params(**{"cmd-sys.argv": " ".join(sys.argv)}) # log the command to produce current experiment
|
||||||
|
self.log_params(
|
||||||
|
**{k: v for k, v in os.environ.items() if k.startswith("_QLIB_")}
|
||||||
|
) # Log necessary environment variables
|
||||||
return run
|
return run
|
||||||
|
|
||||||
def _log_uncommitted_code(self):
|
def _log_uncommitted_code(self):
|
||||||
@@ -398,6 +445,9 @@ class MLflowRecorder(Recorder):
|
|||||||
for name, data in kwargs.items():
|
for name, data in kwargs.items():
|
||||||
self.client.log_metric(self.id, name, data, step=step)
|
self.client.log_metric(self.id, name, data, step=step)
|
||||||
|
|
||||||
|
def log_artifact(self, local_path, artifact_path: Optional[str] = None):
|
||||||
|
self.client.log_artifact(self.id, local_path=local_path, artifact_path=artifact_path)
|
||||||
|
|
||||||
@AsyncCaller.async_dec(ac_attr="async_log")
|
@AsyncCaller.async_dec(ac_attr="async_log")
|
||||||
def set_tags(self, **kwargs):
|
def set_tags(self, **kwargs):
|
||||||
for name, data in kwargs.items():
|
for name, data in kwargs.items():
|
||||||
@@ -420,6 +470,9 @@ class MLflowRecorder(Recorder):
|
|||||||
artifacts = self.client.list_artifacts(self.id, artifact_path)
|
artifacts = self.client.list_artifacts(self.id, artifact_path)
|
||||||
return [art.path for art in artifacts]
|
return [art.path for art in artifacts]
|
||||||
|
|
||||||
|
def download_artifact(self, path: str, dst_path: Optional[str] = None) -> str:
|
||||||
|
return self.client.download_artifacts(self.id, path, dst_path)
|
||||||
|
|
||||||
def list_metrics(self):
|
def list_metrics(self):
|
||||||
run = self.client.get_run(self.id)
|
run = self.client.get_run(self.id)
|
||||||
return run.data.metrics
|
return run.data.metrics
|
||||||
|
|||||||
@@ -67,3 +67,10 @@ from qlib.constant import REG_CN
|
|||||||
provider_uri = "~/.qlib/qlib_data/cn_data" # target_dir
|
provider_uri = "~/.qlib/qlib_data/cn_data" # target_dir
|
||||||
qlib.init(provider_uri=provider_uri, region=REG_CN)
|
qlib.init(provider_uri=provider_uri, region=REG_CN)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Use Crowd Sourced Data
|
||||||
|
The is also a [crowd sourced version of qlib data](data_collector/crowd_source/README.md): https://github.com/chenditc/investment_data/releases
|
||||||
|
```bash
|
||||||
|
wget https://github.com/chenditc/investment_data/releases/download/20220720/qlib_bin.tar.gz
|
||||||
|
tar -zxvf qlib_bin.tar.gz -C ~/.qlib/qlib_data/cn_data --strip-components=2
|
||||||
|
```
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ pip install -r requirements.txt
|
|||||||
## fill 1min data
|
## fill 1min data
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python fill_1min_using_1d.py --data_1min_dir ~/.qlib/csv_data/cn_data_1min --qlib_data_1d_dir ~/.qlib/qlib_data/cn_data
|
python fill_cn_1min_data.py --data_1min_dir ~/.qlib/csv_data/cn_data_1min --qlib_data_1d_dir ~/.qlib/qlib_data/cn_data
|
||||||
```
|
```
|
||||||
|
|
||||||
## Parameters
|
## Parameters
|
||||||
|
|||||||
32
scripts/data_collector/crowd_source/README.md
Normal file
32
scripts/data_collector/crowd_source/README.md
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
# Crowd Source Data
|
||||||
|
|
||||||
|
## Initiative
|
||||||
|
Public data source like yahoo is flawed, it might miss data for stock which is delisted and it might has data which is wrong. This can introduce survivorship bias into our training process.
|
||||||
|
|
||||||
|
The crowd sourced data is introduced to merged data from multiple data source and cross validate against each other, so that:
|
||||||
|
1. We will have a more complete history record.
|
||||||
|
2. We can identify the anomaly data and apply correction when necessary.
|
||||||
|
|
||||||
|
## Related Repo
|
||||||
|
The raw data is hosted on dolthub repo: https://www.dolthub.com/repositories/chenditc/investment_data
|
||||||
|
|
||||||
|
The processing script and sql is hosted on github repo: https://github.com/chenditc/investment_data
|
||||||
|
|
||||||
|
The pakcaged docker runtime is hosted on dockerhub: https://hub.docker.com/repository/docker/chenditc/investment_data
|
||||||
|
|
||||||
|
## How to use it in qlib
|
||||||
|
### Option 1: Download release bin data
|
||||||
|
User can download data in qlib bin format and use it directly: https://github.com/chenditc/investment_data/releases/tag/20220720
|
||||||
|
```bash
|
||||||
|
wget https://github.com/chenditc/investment_data/releases/download/20220720/qlib_bin.tar.gz
|
||||||
|
tar -zxvf qlib_bin.tar.gz -C ~/.qlib/qlib_data/cn_data --strip-components=2
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option 2: Generate qlib data from dolthub
|
||||||
|
Dolthub data will be update daily, so that if user wants to get up to date data, they can dump qlib bin using docker:
|
||||||
|
```
|
||||||
|
docker run -v /<some output directory>:/output -it --rm chenditc/investment_data bash dump_qlib_bin.sh && cp ./qlib_bin.tar.gz /output/
|
||||||
|
```
|
||||||
|
|
||||||
|
## FAQ and other info
|
||||||
|
See: https://github.com/chenditc/investment_data/blob/main/README.md
|
||||||
@@ -49,3 +49,7 @@ pythono collector.py collector_data --help
|
|||||||
|
|
||||||
- interval: 1d
|
- interval: 1d
|
||||||
- region: CN
|
- region: CN
|
||||||
|
|
||||||
|
## 免责声明
|
||||||
|
|
||||||
|
本项目仅供学习研究使用,不作为任何行为的指导和建议,由此而引发任何争议和纠纷,与本项目无任何关系
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ pip install -r requirements.txt
|
|||||||
- `target_dir`: save dir, by default *~/.qlib/qlib_data/cn_data*
|
- `target_dir`: save dir, by default *~/.qlib/qlib_data/cn_data*
|
||||||
- `version`: dataset version, value from [`v1`, `v2`], by default `v1`
|
- `version`: dataset version, value from [`v1`, `v2`], by default `v1`
|
||||||
- `v2` end date is *2021-06*, `v1` end date is *2020-09*
|
- `v2` end date is *2021-06*, `v1` end date is *2020-09*
|
||||||
- user can append data to `v2`: [automatic update of daily frequency data](#automatic-update-of-daily-frequency-datafrom-yahoo-finance)
|
- If users want to incrementally update data, they need to use yahoo collector to [collect data from scratch](#collector-yahoofinance-data-to-qlib).
|
||||||
- **the [benchmarks](https://github.com/microsoft/qlib/tree/main/examples/benchmarks) for qlib use `v1`**, *due to the unstable access to historical data by YahooFinance, there are some differences between `v2` and `v1`*
|
- **the [benchmarks](https://github.com/microsoft/qlib/tree/main/examples/benchmarks) for qlib use `v1`**, *due to the unstable access to historical data by YahooFinance, there are some differences between `v2` and `v1`*
|
||||||
- `interval`: `1d` or `1min`, by default `1d`
|
- `interval`: `1d` or `1min`, by default `1d`
|
||||||
- `region`: `cn` or `us` or `in`, by default `cn`
|
- `region`: `cn` or `us` or `in`, by default `cn`
|
||||||
@@ -62,6 +62,8 @@ pip install -r requirements.txt
|
|||||||
> collector *YahooFinance* data and *dump* into `qlib` format.
|
> collector *YahooFinance* data and *dump* into `qlib` format.
|
||||||
> If the above ready-made data can't meet users' requirements, users can follow this section to crawl the latest data and convert it to qlib-data.
|
> If the above ready-made data can't meet users' requirements, users can follow this section to crawl the latest data and convert it to qlib-data.
|
||||||
1. download data to csv: `python scripts/data_collector/yahoo/collector.py download_data`
|
1. download data to csv: `python scripts/data_collector/yahoo/collector.py download_data`
|
||||||
|
|
||||||
|
This will download the raw data such as high, low, open, close, adjclose price from yahoo to a local directory. One file per symbol.
|
||||||
|
|
||||||
- parameters:
|
- parameters:
|
||||||
- `source_dir`: save the directory
|
- `source_dir`: save the directory
|
||||||
@@ -99,6 +101,10 @@ pip install -r requirements.txt
|
|||||||
```
|
```
|
||||||
2. normalize data: `python scripts/data_collector/yahoo/collector.py normalize_data`
|
2. normalize data: `python scripts/data_collector/yahoo/collector.py normalize_data`
|
||||||
|
|
||||||
|
This will:
|
||||||
|
1. Normalize high, low, close, open price using adjclose.
|
||||||
|
2. Normalize the high, low, close, open price so that the first valid trading date's close price is 1.
|
||||||
|
|
||||||
- parameters:
|
- parameters:
|
||||||
- `source_dir`: csv directory
|
- `source_dir`: csv directory
|
||||||
- `normalize_dir`: result directory
|
- `normalize_dir`: result directory
|
||||||
@@ -136,6 +142,8 @@ pip install -r requirements.txt
|
|||||||
```
|
```
|
||||||
3. dump data: `python scripts/dump_bin.py dump_all`
|
3. dump data: `python scripts/dump_bin.py dump_all`
|
||||||
|
|
||||||
|
This will convert the normalized csv in `feature` directory as numpy array and store the normalized data one file per column and one symbol per directory.
|
||||||
|
|
||||||
- parameters:
|
- parameters:
|
||||||
- `csv_path`: stock data path or directory, **normalize result(normalize_dir)**
|
- `csv_path`: stock data path or directory, **normalize result(normalize_dir)**
|
||||||
- `qlib_dir`: qlib(dump) data director
|
- `qlib_dir`: qlib(dump) data director
|
||||||
@@ -157,6 +165,9 @@ pip install -r requirements.txt
|
|||||||
|
|
||||||
### Automatic update of daily frequency data(from yahoo finance)
|
### Automatic update of daily frequency data(from yahoo finance)
|
||||||
> It is recommended that users update the data manually once (--trading_date 2021-05-25) and then set it to update automatically.
|
> It is recommended that users update the data manually once (--trading_date 2021-05-25) and then set it to update automatically.
|
||||||
|
>
|
||||||
|
> **NOTE**: Users can't incrementally update data based on the offline data provided by Qlib(some fields are removed to reduce the data size). Users should use [yahoo collector](https://github.com/microsoft/qlib/tree/main/scripts/data_collector/yahoo#automatic-update-of-daily-frequency-datafrom-yahoo-finance) to download Yahoo data from scratch and then incrementally update it.
|
||||||
|
>
|
||||||
|
|
||||||
* Automatic update of data to the "qlib" directory each trading day(Linux)
|
* Automatic update of data to the "qlib" directory each trading day(Linux)
|
||||||
* use *crontab*: `crontab -e`
|
* use *crontab*: `crontab -e`
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user