mirror of
https://github.com/microsoft/qlib.git
synced 2026-07-22 03:37:34 +08:00
Compare commits
247 Commits
v0.8.0
...
you-n-g-pa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74cb26c38f | ||
|
|
d149c2b177 | ||
|
|
6fddae9965 | ||
|
|
107d716cf8 | ||
|
|
792285b64f | ||
|
|
78b6b16640 | ||
|
|
b9bba4940f | ||
|
|
c34051c1ce | ||
|
|
a0c83d7997 | ||
|
|
82b10ee37a | ||
|
|
9b446f9a92 | ||
|
|
59b1820447 | ||
|
|
1dededa33f | ||
|
|
e62684eddf | ||
|
|
8a5efda0f6 | ||
|
|
a6700d81ff | ||
|
|
623774d8fb | ||
|
|
3db22452fb | ||
|
|
b655f90511 | ||
|
|
5e404909cf | ||
|
|
23c657a7a2 | ||
|
|
9bf3423a64 | ||
|
|
25ecb1135f | ||
|
|
2ca0d88d2d | ||
|
|
50d74b5560 | ||
|
|
a87b02619a | ||
|
|
da676a20a2 | ||
|
|
13d904d9a9 | ||
|
|
36950b905d | ||
|
|
58540f76ee | ||
|
|
3e6e2865ce | ||
|
|
3fcbaa33fa | ||
|
|
50409ff17b | ||
|
|
afcea404a5 | ||
|
|
e24ef67663 | ||
|
|
2d5eecb9a2 | ||
|
|
89972f6c6f | ||
|
|
1ef8e61abd | ||
|
|
1a4114b683 | ||
|
|
e874ef2bc1 | ||
|
|
14b2b355a7 | ||
|
|
64fadff218 | ||
|
|
a02ac95538 | ||
|
|
cc94c32db6 | ||
|
|
9a40fd3cdc | ||
|
|
c4281121e3 | ||
|
|
2de9903200 | ||
|
|
2cf842bcfe | ||
|
|
9e381493c2 | ||
|
|
a73b60d05a | ||
|
|
64979ad769 | ||
|
|
c5cf8fb9cc | ||
|
|
5d579d1a20 | ||
|
|
3c9c76b384 | ||
|
|
9d0a8f61d1 | ||
|
|
701b18af1b | ||
|
|
84ff662a26 | ||
|
|
00e40e775b | ||
|
|
45fe5e6974 | ||
|
|
366a9c33f3 | ||
|
|
982e0da715 | ||
|
|
cd5e5d5235 | ||
|
|
caea495f40 | ||
|
|
d934c8caba | ||
|
|
a139986f4e | ||
|
|
12c3de42d0 | ||
|
|
fe0f9427f2 | ||
|
|
a973e4fb66 | ||
|
|
c60366addd | ||
|
|
41447f320b | ||
|
|
e1271a83f7 | ||
|
|
30b531086c | ||
|
|
87926513cb | ||
|
|
7bfc7e1797 | ||
|
|
85e7cdcac3 | ||
|
|
08fd1d3f42 | ||
|
|
defd6758f6 | ||
|
|
61cc1a3867 | ||
|
|
655ed982cf | ||
|
|
2952c443ca | ||
|
|
7f1293ec34 | ||
|
|
73438807f9 | ||
|
|
962751c72d | ||
|
|
56cfa480dc | ||
|
|
6edd0bf298 | ||
|
|
fe155703b0 | ||
|
|
3c4f4bfd44 | ||
|
|
5200ff520a | ||
|
|
30e457119c | ||
|
|
243e516cf1 | ||
|
|
e229b567ad | ||
|
|
f129bfef5d | ||
|
|
9dd5e07819 | ||
|
|
00ed35fc1b | ||
|
|
3f53a097b0 | ||
|
|
fb230a8097 | ||
|
|
ff4724e248 | ||
|
|
73d90f7f44 | ||
|
|
b7988e6428 | ||
|
|
8efc8b92ef | ||
|
|
f2a5ecd98a | ||
|
|
705354cc28 | ||
|
|
1b5d0d4d6d | ||
|
|
f4a481945b | ||
|
|
5f18ba7970 | ||
|
|
2681c61c60 | ||
|
|
776b0c5bb4 | ||
|
|
829ad9f5e9 | ||
|
|
921c13cc90 | ||
|
|
0f519f6053 | ||
|
|
2ed806c846 | ||
|
|
d2f0bebf60 | ||
|
|
615a381038 | ||
|
|
568a88fddb | ||
|
|
058f976727 | ||
|
|
faa99f30fa | ||
|
|
837067b9e1 | ||
|
|
3a911bc09b | ||
|
|
90be21bb40 | ||
|
|
7540b1257b | ||
|
|
57f7ed9914 | ||
|
|
9e3d0249f7 | ||
|
|
2ac964c470 | ||
|
|
07f0d4f599 | ||
|
|
ea4fb33ff2 | ||
|
|
ed0c238787 | ||
|
|
80af395b3c | ||
|
|
4dc66932d5 | ||
|
|
40dd84857c | ||
|
|
74cc21fc2c | ||
|
|
ec8969a3ae | ||
|
|
528f74af09 | ||
|
|
d482726f28 | ||
|
|
cfc3e886ed | ||
|
|
60d45ad770 | ||
|
|
0e8b94a552 | ||
|
|
4bf127eba5 | ||
|
|
c149c8616c | ||
|
|
3274e16c95 | ||
|
|
d496cf7476 | ||
|
|
357ee74b6f | ||
|
|
5da5cf5175 | ||
|
|
6a946761cf | ||
|
|
76b7b5f24b | ||
|
|
d7d19feb4e | ||
|
|
bba6972a55 | ||
|
|
18af288692 | ||
|
|
ba056850cb | ||
|
|
aed5b8ebc0 | ||
|
|
79355666a9 | ||
|
|
144e1e2459 | ||
|
|
635632e4ed | ||
|
|
c5834476e2 | ||
|
|
01afd06e18 | ||
|
|
d533219738 | ||
|
|
5b5c99fe75 | ||
|
|
da48f42f3f | ||
|
|
f979dcf5e8 | ||
|
|
97aa16a078 | ||
|
|
094be9be86 | ||
|
|
d9b9386032 | ||
|
|
b86a30aae7 | ||
|
|
2c5a4691f3 | ||
|
|
54344c4426 | ||
|
|
303cdb8ce3 | ||
|
|
1a0ac1ab6d | ||
|
|
a79e446724 | ||
|
|
bdf1fb29a6 | ||
|
|
86e1265f69 | ||
|
|
628eb7fa73 | ||
|
|
2a1b512cd2 | ||
|
|
50e7901e87 | ||
|
|
3ba54cd1ab | ||
|
|
483d01f0c1 | ||
|
|
61836cba3d | ||
|
|
aeb5e40c77 | ||
|
|
116f0fa7a7 | ||
|
|
5296cce725 | ||
|
|
292fcc9e98 | ||
|
|
d3fbf066cf | ||
|
|
52ecb79e0b | ||
|
|
59c52eac0a | ||
|
|
f455305a2a | ||
|
|
a67f67db6e | ||
|
|
5c2e99aee3 | ||
|
|
2bb8a4ce0e | ||
|
|
7f274b1e4e | ||
|
|
2aee9e0145 | ||
|
|
a62e2ec4de | ||
|
|
e7954bdb32 | ||
|
|
d6f69aefea | ||
|
|
1bebe9780e | ||
|
|
7a4a92bc69 | ||
|
|
271782c9dd | ||
|
|
d0113ea7df | ||
|
|
c3996955ef | ||
|
|
8261965015 | ||
|
|
6f71f8a46b | ||
|
|
edd8badeaf | ||
|
|
19689024d4 | ||
|
|
0304df0d5b | ||
|
|
181ee3c070 | ||
|
|
cf35562e84 | ||
|
|
184ce34a34 | ||
|
|
382ababc01 | ||
|
|
bcf18c14de | ||
|
|
6c1332f604 | ||
|
|
93088485c3 | ||
|
|
c633d3fec0 | ||
|
|
0b6d99bd38 | ||
|
|
03cce8c908 | ||
|
|
e76b409d9a | ||
|
|
3e79a088ef | ||
|
|
dfc0ed3c01 | ||
|
|
f59cfe51e0 | ||
|
|
1ecdfd45fe | ||
|
|
622303b83a | ||
|
|
6bafd0a09b | ||
|
|
aed9c09091 | ||
|
|
1b8f0b4575 | ||
|
|
4709909782 | ||
|
|
a0f49fe2e7 | ||
|
|
2840570dd3 | ||
|
|
00ad122175 | ||
|
|
3493f29e16 | ||
|
|
e33de44cb9 | ||
|
|
e843e021a2 | ||
|
|
5aa5a6f356 | ||
|
|
f490708025 | ||
|
|
41a5778684 | ||
|
|
ef161715f7 | ||
|
|
d087054a59 | ||
|
|
350fbe91c9 | ||
|
|
2aca74cd21 | ||
|
|
92ff3d20b9 | ||
|
|
0552120a2e | ||
|
|
3480fd932f | ||
|
|
957f9a18e9 | ||
|
|
6c83632fc4 | ||
|
|
125922b77a | ||
|
|
5e69d089c0 | ||
|
|
c10c349b20 | ||
|
|
7cb1f7cee0 | ||
|
|
d0ff5eea9d | ||
|
|
e99f00b445 | ||
|
|
e50ad4309e | ||
|
|
d89ae2370f |
1
.github/PULL_REQUEST_TEMPLATE.md
vendored
1
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -8,6 +8,7 @@
|
|||||||
<!--- Why is this change required? What problem does it solve? -->
|
<!--- Why is this change required? What problem does it solve? -->
|
||||||
|
|
||||||
## How Has This Been Tested?
|
## How Has This Been Tested?
|
||||||
|
<!--- Put an `x` in all the boxes that apply: --->
|
||||||
- [ ] Pass the test by running: `pytest qlib/tests/test_all_pipeline.py` under upper directory of `qlib`.
|
- [ ] Pass the test by running: `pytest qlib/tests/test_all_pipeline.py` under upper directory of `qlib`.
|
||||||
- [ ] If you are adding a new feature, test on your own test scripts.
|
- [ ] If you are adding a new feature, test on your own test scripts.
|
||||||
|
|
||||||
|
|||||||
3
.github/workflows/python-publish.yml
vendored
3
.github/workflows/python-publish.yml
vendored
@@ -12,7 +12,8 @@ jobs:
|
|||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [windows-latest, macos-latest, macos-11]
|
os: [windows-latest, macos-11]
|
||||||
|
# FIXME: macos-latest will raise error now.
|
||||||
# not supporting 3.6 due to annotations is not supported https://stackoverflow.com/a/52890129
|
# not supporting 3.6 due to annotations is not supported https://stackoverflow.com/a/52890129
|
||||||
python-version: [3.7, 3.8]
|
python-version: [3.7, 3.8]
|
||||||
|
|
||||||
|
|||||||
66
.github/workflows/test.yml
vendored
66
.github/workflows/test.yml
vendored
@@ -1,66 +0,0 @@
|
|||||||
name: Test
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ main ]
|
|
||||||
pull_request:
|
|
||||||
branches: [ main ]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
os: [windows-latest, ubuntu-18.04, ubuntu-20.04]
|
|
||||||
# not supporting 3.6 due to annotations is not supported https://stackoverflow.com/a/52890129
|
|
||||||
python-version: [3.7, 3.8]
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Set up Python ${{ matrix.python-version }}
|
|
||||||
uses: actions/setup-python@v2
|
|
||||||
with:
|
|
||||||
python-version: ${{ matrix.python-version }}
|
|
||||||
|
|
||||||
- name: Lint with Black
|
|
||||||
run: |
|
|
||||||
pip install --upgrade pip
|
|
||||||
pip install black wheel
|
|
||||||
black qlib -l 120 --check --diff
|
|
||||||
|
|
||||||
- name: Install Qlib with pip
|
|
||||||
run: |
|
|
||||||
pip install numpy==1.19.5 ruamel.yaml
|
|
||||||
pip install pyqlib --ignore-installed
|
|
||||||
|
|
||||||
- name: Test data downloads
|
|
||||||
run: |
|
|
||||||
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn
|
|
||||||
|
|
||||||
- name: Test workflow by config (install from pip)
|
|
||||||
run: |
|
|
||||||
python qlib/workflow/cli.py examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
|
||||||
python -m pip uninstall -y pyqlib
|
|
||||||
|
|
||||||
# Test Qlib installed from source
|
|
||||||
- name: Install Qlib from source
|
|
||||||
run: |
|
|
||||||
pip install --upgrade cython jupyter jupyter_contrib_nbextensions numpy scipy scikit-learn # installing without this line will cause errors on GitHub Actions, while instsalling locally won't
|
|
||||||
pip install -e .
|
|
||||||
|
|
||||||
- name: Install test dependencies
|
|
||||||
run: |
|
|
||||||
pip install --upgrade pip
|
|
||||||
pip install black pytest
|
|
||||||
|
|
||||||
- name: Unit tests with Pytest
|
|
||||||
run: |
|
|
||||||
cd tests
|
|
||||||
python -m pytest . --durations=10
|
|
||||||
|
|
||||||
- name: Test workflow by config (install from source)
|
|
||||||
run: |
|
|
||||||
python qlib/workflow/cli.py examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
|
||||||
|
|
||||||
75
.github/workflows/test_macos.yml
vendored
75
.github/workflows/test_macos.yml
vendored
@@ -1,75 +0,0 @@
|
|||||||
# There are some issues (in the downloading data phase) on MacOS when running with other tests. So we split it into an individual config.
|
|
||||||
name: Test MacOS
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ main ]
|
|
||||||
pull_request:
|
|
||||||
branches: [ main ]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
os: [macos-11, macos-latest]
|
|
||||||
# not supporting 3.6 due to annotations is not supported https://stackoverflow.com/a/52890129
|
|
||||||
python-version: [3.7, 3.8]
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Set up Python ${{ matrix.python-version }}
|
|
||||||
uses: actions/setup-python@v2
|
|
||||||
with:
|
|
||||||
python-version: ${{ matrix.python-version }}
|
|
||||||
|
|
||||||
- name: Lint with Black
|
|
||||||
run: |
|
|
||||||
cd ..
|
|
||||||
python -m pip install pip --upgrade
|
|
||||||
python -m pip install wheel --upgrade
|
|
||||||
python -m pip install black
|
|
||||||
python -m black qlib -l 120 --check --diff
|
|
||||||
# Test Qlib installed with pip
|
|
||||||
|
|
||||||
- name: Install Qlib with pip
|
|
||||||
run: |
|
|
||||||
python -m pip install numpy==1.19.5
|
|
||||||
python -m pip install pyqlib --ignore-installed ruamel.yaml numpy
|
|
||||||
- name: Install Lightgbm for MacOS
|
|
||||||
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 data downloads
|
|
||||||
run: |
|
|
||||||
python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn
|
|
||||||
- name: Test workflow by config (install from pip)
|
|
||||||
run: |
|
|
||||||
python qlib/workflow/cli.py examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
|
||||||
python -m pip uninstall -y pyqlib
|
|
||||||
# Test Qlib installed from source
|
|
||||||
- name: Install Qlib from source
|
|
||||||
run: |
|
|
||||||
python -m pip install --upgrade cython
|
|
||||||
python -m pip install numpy jupyter jupyter_contrib_nbextensions
|
|
||||||
python -m pip install -U scipy scikit-learn # installing without this line will cause errors on GitHub Actions, while instsalling locally won't
|
|
||||||
python setup.py install
|
|
||||||
- name: Install test dependencies
|
|
||||||
run: |
|
|
||||||
python -m pip install --upgrade pip
|
|
||||||
python -m pip install -U pyopenssl idna
|
|
||||||
python -m pip install black pytest
|
|
||||||
- name: Unit tests with Pytest
|
|
||||||
run: |
|
|
||||||
cd tests
|
|
||||||
python -m pytest . --durations=0
|
|
||||||
- name: Test workflow by config (install from source)
|
|
||||||
run: |
|
|
||||||
python qlib/workflow/cli.py examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
|
||||||
57
.github/workflows/test_qlib_from_pip.yml
vendored
Normal file
57
.github/workflows/test_qlib_from_pip.yml
vendored
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
name: Test qlib from pip
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ main ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ main ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
timeout-minutes: 120
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [windows-latest, ubuntu-18.04, ubuntu-20.04, macos-11, macos-latest]
|
||||||
|
# not supporting 3.6 due to annotations is not supported https://stackoverflow.com/a/52890129
|
||||||
|
python-version: [3.7, 3.8]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Test qlib from pip
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
|
uses: actions/setup-python@v2
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
|
- name: Update pip to the latest version
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
|
||||||
|
- name: Qlib installation test
|
||||||
|
run: |
|
||||||
|
python -m pip install pyqlib
|
||||||
|
# Specify the numpy version because the numpy upgrade caused the CI test to fail,
|
||||||
|
# and this line of code will be removed when the next version of qlib is released.
|
||||||
|
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
|
||||||
|
run: |
|
||||||
|
python scripts/get_data.py qlib_data --name qlib_data_simple --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn
|
||||||
|
|
||||||
|
- name: Test workflow by config
|
||||||
|
run: |
|
||||||
|
qrun examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
||||||
155
.github/workflows/test_qlib_from_source.yml
vendored
Normal file
155
.github/workflows/test_qlib_from_source.yml
vendored
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
name: Test qlib from source
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ main ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ main ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
timeout-minutes: 180
|
||||||
|
# we may retry for 3 times for `Unit tests with Pytest`
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [windows-latest, ubuntu-18.04, ubuntu-20.04, macos-11, macos-latest]
|
||||||
|
# not supporting 3.6 due to annotations is not supported https://stackoverflow.com/a/52890129
|
||||||
|
python-version: [3.7, 3.8]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Test qlib from source
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
|
uses: actions/setup-python@v2
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
|
- name: Update pip to the latest version
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
|
||||||
|
- name: Installing pytorch for macos
|
||||||
|
if: ${{ matrix.os == 'macos-11' || matrix.os == 'macos-latest' }}
|
||||||
|
run: |
|
||||||
|
python -m pip install torch torchvision torchaudio
|
||||||
|
|
||||||
|
- name: Installing pytorch for ubuntu
|
||||||
|
if: ${{ matrix.os == 'ubuntu-18.04' || matrix.os == 'ubuntu-20.04' }}
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
python -m pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cpu
|
||||||
|
|
||||||
|
- name: Installing pytorch for windows
|
||||||
|
if: ${{ matrix.os == 'windows-latest' }}
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
python -m pip install torch torchvision torchaudio
|
||||||
|
|
||||||
|
- name: Set up Python tools
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade cython
|
||||||
|
python -m pip install -e .[dev]
|
||||||
|
|
||||||
|
- name: Lint with Black
|
||||||
|
run: |
|
||||||
|
black . -l 120 --check --diff
|
||||||
|
|
||||||
|
- name: Make html with sphinx
|
||||||
|
run: |
|
||||||
|
cd docs
|
||||||
|
sphinx-build -b html . build
|
||||||
|
cd ..
|
||||||
|
|
||||||
|
# Check Qlib with pylint
|
||||||
|
# TODO: These problems we will solve in the future. Important among them are: W0221, W0223, W0237, E1102
|
||||||
|
# C0103: invalid-name
|
||||||
|
# C0209: consider-using-f-string
|
||||||
|
# R0402: consider-using-from-import
|
||||||
|
# R1705: no-else-return
|
||||||
|
# R1710: inconsistent-return-statements
|
||||||
|
# R1725: super-with-arguments
|
||||||
|
# R1735: use-dict-literal
|
||||||
|
# W0102: dangerous-default-value
|
||||||
|
# W0212: protected-access
|
||||||
|
# W0221: arguments-differ
|
||||||
|
# W0223: abstract-method
|
||||||
|
# W0231: super-init-not-called
|
||||||
|
# W0237: arguments-renamed
|
||||||
|
# W0612: unused-variable
|
||||||
|
# W0621: redefined-outer-name
|
||||||
|
# W0622: redefined-builtin
|
||||||
|
# FIXME: specify exception type
|
||||||
|
# W0703: broad-except
|
||||||
|
# W1309: f-string-without-interpolation
|
||||||
|
# E1102: not-callable
|
||||||
|
# E1136: unsubscriptable-object
|
||||||
|
# References for parameters: https://github.com/PyCQA/pylint/issues/4577#issuecomment-1000245962
|
||||||
|
- name: Check Qlib with pylint
|
||||||
|
run: |
|
||||||
|
pylint --disable=C0104,C0114,C0115,C0116,C0301,C0302,C0411,C0413,C1802,R0401,R0801,R0902,R0903,R0911,R0912,R0913,R0914,R0915,R1720,W0105,W0123,W0201,W0511,W0613,W1113,W1514,E0401,E1121,C0103,C0209,R0402,R1705,R1710,R1725,R1735,W0102,W0212,W0221,W0223,W0231,W0237,W0612,W0621,W0622,W0703,W1309,E1102,E1136 --const-rgx='[a-z_][a-z0-9_]{2,30}$' qlib --init-hook "import astroid; astroid.context.InferenceContext.max_inferred = 500"
|
||||||
|
|
||||||
|
# The following flake8 error codes were ignored:
|
||||||
|
# E501 line too long
|
||||||
|
# Description: We have used black to limit the length of each line to 120.
|
||||||
|
# F541 f-string is missing placeholders
|
||||||
|
# Description: The same thing is done when using pylint for detection.
|
||||||
|
# E266 too many leading '#' for block comment
|
||||||
|
# Description: To make the code more readable, a lot of "#" is used.
|
||||||
|
# This error code appears centrally in:
|
||||||
|
# qlib/backtest/executor.py
|
||||||
|
# qlib/data/ops.py
|
||||||
|
# qlib/utils/__init__.py
|
||||||
|
# E402 module level import not at top of file
|
||||||
|
# Description: There are times when module level import is not available at the top of the file.
|
||||||
|
# W503 line break before binary operator
|
||||||
|
# Description: Since black formats the length of each line of code, it has to perform a line break when a line of arithmetic is too long.
|
||||||
|
# E731 do not assign a lambda expression, use a def
|
||||||
|
# Description: Restricts the use of lambda expressions, but at some point lambda expressions are required.
|
||||||
|
# E203 whitespace before ':'
|
||||||
|
# Description: If there is whitespace before ":", it cannot pass the black check.
|
||||||
|
- name: Check Qlib with flake8
|
||||||
|
run: |
|
||||||
|
flake8 --ignore=E501,F541,E266,E402,W503,E731,E203 --per-file-ignores="__init__.py:F401,F403" qlib
|
||||||
|
|
||||||
|
# https://github.com/python/mypy/issues/10600
|
||||||
|
- name: Check Qlib with mypy
|
||||||
|
run: |
|
||||||
|
mypy qlib --install-types --non-interactive || true
|
||||||
|
mypy qlib --verbose
|
||||||
|
|
||||||
|
- name: Test data downloads
|
||||||
|
run: |
|
||||||
|
python scripts/get_data.py qlib_data --name qlib_data_simple --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn
|
||||||
|
azcopy copy https://qlibpublic.blob.core.windows.net/data/rl /tmp/qlibpublic/data --recursive
|
||||||
|
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)
|
||||||
|
run: |
|
||||||
|
# Version 0.52.0 of numba must be installed manually in CI, otherwise it will cause incompatibility with the latest version of numpy.
|
||||||
|
python -m pip install numba==0.52.0
|
||||||
|
# You must update numpy manually, because when installing python tools, it will try to uninstall numpy and cause CI to fail.
|
||||||
|
python -m pip install --upgrade numpy
|
||||||
|
python qlib/workflow/cli.py examples/benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml
|
||||||
|
|
||||||
|
- name: Unit tests with Pytest
|
||||||
|
uses: nick-fields/retry@v2
|
||||||
|
with:
|
||||||
|
timeout_minutes: 60
|
||||||
|
max_attempts: 3
|
||||||
|
command: |
|
||||||
|
cd tests
|
||||||
|
python -m pytest . -m "not slow" --durations=0
|
||||||
57
.github/workflows/test_qlib_from_source_slow.yml
vendored
Normal file
57
.github/workflows/test_qlib_from_source_slow.yml
vendored
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
name: Test qlib from source slow
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ main ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ main ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
timeout-minutes: 360
|
||||||
|
# we may retry for 3 times for `Unit tests with Pytest`
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [windows-latest, ubuntu-18.04, ubuntu-20.04, macos-11, macos-latest]
|
||||||
|
# not supporting 3.6 due to annotations is not supported https://stackoverflow.com/a/52890129
|
||||||
|
python-version: [3.7, 3.8]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Test qlib from source slow
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
|
uses: actions/setup-python@v2
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
|
- name: Set up Python tools
|
||||||
|
run: |
|
||||||
|
pip install --upgrade cython numpy pip
|
||||||
|
pip install -e .[dev]
|
||||||
|
|
||||||
|
- name: Downloads dependencies data
|
||||||
|
run: |
|
||||||
|
python scripts/get_data.py qlib_data --name qlib_data_simple --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn
|
||||||
|
|
||||||
|
- 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: Unit tests with Pytest
|
||||||
|
uses: nick-fields/retry@v2
|
||||||
|
with:
|
||||||
|
timeout_minutes: 120
|
||||||
|
max_attempts: 3
|
||||||
|
command: |
|
||||||
|
cd tests
|
||||||
|
python -m pytest . -m "slow" --durations=0
|
||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -27,6 +27,10 @@ examples/estimator/estimator_example/
|
|||||||
|
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
|
|
||||||
|
# test related
|
||||||
|
test-output.xml
|
||||||
|
.output
|
||||||
|
.data
|
||||||
|
|
||||||
# special software
|
# special software
|
||||||
mlruns/
|
mlruns/
|
||||||
@@ -34,8 +38,10 @@ mlruns/
|
|||||||
tags
|
tags
|
||||||
|
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|
||||||
*.swp
|
*.swp
|
||||||
|
|
||||||
./pretrain
|
./pretrain
|
||||||
|
.idea/
|
||||||
|
|||||||
17
.mypy.ini
Normal file
17
.mypy.ini
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
[mypy]
|
||||||
|
exclude = (?x)(
|
||||||
|
^qlib/backtest/high_performance_ds\.py$
|
||||||
|
| ^qlib/contrib
|
||||||
|
| ^qlib/data
|
||||||
|
| ^qlib/model
|
||||||
|
| ^qlib/strategy
|
||||||
|
| ^qlib/tests
|
||||||
|
| ^qlib/utils
|
||||||
|
| ^qlib/workflow
|
||||||
|
| ^qlib/config\.py$
|
||||||
|
| ^qlib/log\.py$
|
||||||
|
| ^qlib/__init__\.py$
|
||||||
|
)
|
||||||
|
ignore_missing_imports = true
|
||||||
|
disallow_incomplete_defs = true
|
||||||
|
follow_imports = skip
|
||||||
12
.pre-commit-config.yaml
Normal file
12
.pre-commit-config.yaml
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
repos:
|
||||||
|
- repo: https://github.com/psf/black
|
||||||
|
rev: 22.6.0
|
||||||
|
hooks:
|
||||||
|
- id: black
|
||||||
|
args: ["qlib", "-l 120"]
|
||||||
|
|
||||||
|
- repo: https://github.com/PyCQA/flake8
|
||||||
|
rev: 4.0.1
|
||||||
|
hooks:
|
||||||
|
- id: flake8
|
||||||
|
args: ["--ignore=E501,F541,E266,E402,W503,E731,E203"]
|
||||||
5
.pylintrc
Normal file
5
.pylintrc
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
[TYPECHECK]
|
||||||
|
# https://stackoverflow.com/a/53572939
|
||||||
|
# List of members which are set dynamically and missed by Pylint inference
|
||||||
|
# system, and so shouldn't trigger E1101 when accessed.
|
||||||
|
generated-members=numpy.*, torch.*
|
||||||
@@ -17,5 +17,5 @@ python:
|
|||||||
version: 3.7
|
version: 3.7
|
||||||
install:
|
install:
|
||||||
- requirements: docs/requirements.txt
|
- requirements: docs/requirements.txt
|
||||||
- method: setuptools
|
- method: pip
|
||||||
path: .
|
path: .
|
||||||
60
CHANGES.rst
60
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 exising 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,24 +65,24 @@ 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
|
||||||
- Change ``split_rolling_data``, we roll the data on market calender now, not on normal date
|
- Change ``split_rolling_data``, we roll the data on market calendar now, not on normal date
|
||||||
- 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,19 +161,19 @@ 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
|
||||||
- The trading limitation is more accurate;
|
- The trading limitation is more accurate;
|
||||||
- In `previous version <https://github.com/microsoft/qlib/blob/v0.7.2/qlib/contrib/backtest/exchange.py#L160>`_, longing and shorting actions share the same action.
|
- In `previous version <https://github.com/microsoft/qlib/blob/v0.7.2/qlib/contrib/backtest/exchange.py#L160>`_, longing and shorting actions share the same action.
|
||||||
- In `current verison <https://github.com/microsoft/qlib/blob/7c31012b507a3823117bddcc693fc64899460b2a/qlib/backtest/exchange.py#L304>`_, the trading limitation is different between loging and shorting action.
|
- In `current version <https://github.com/microsoft/qlib/blob/7c31012b507a3823117bddcc693fc64899460b2a/qlib/backtest/exchange.py#L304>`_, the trading limitation is different between logging and shorting action.
|
||||||
- The constant is different when calculating annualized metrics.
|
- The constant is different when calculating annualized metrics.
|
||||||
- `Current version <https://github.com/microsoft/qlib/blob/7c31012b507a3823117bddcc693fc64899460b2a/qlib/contrib/evaluate.py#L42>`_ uses more accurate constant than `previous version <https://github.com/microsoft/qlib/blob/v0.7.2/qlib/contrib/evaluate.py#L22>`_
|
- `Current version <https://github.com/microsoft/qlib/blob/7c31012b507a3823117bddcc693fc64899460b2a/qlib/contrib/evaluate.py#L42>`_ uses more accurate constant than `previous version <https://github.com/microsoft/qlib/blob/v0.7.2/qlib/contrib/evaluate.py#L22>`_
|
||||||
- `A new version <https://github.com/microsoft/qlib/blob/7c31012b507a3823117bddcc693fc64899460b2a/qlib/tests/data.py#L17>`_ of data is released. Due to the unstability of Yahoo data source, the data may be different after downloading data again.
|
- `A new version <https://github.com/microsoft/qlib/blob/7c31012b507a3823117bddcc693fc64899460b2a/qlib/tests/data.py#L17>`_ of data is released. Due to the unstability of Yahoo data source, the data may be different after downloading data again.
|
||||||
- Users could chec kout the backtesting results between `Current version <https://github.com/microsoft/qlib/tree/7c31012b507a3823117bddcc693fc64899460b2a/examples/benchmarks>`_ and `previous version <https://github.com/microsoft/qlib/tree/v0.7.2/examples/benchmarks>`_
|
- Users could check out the backtesting results between `Current version <https://github.com/microsoft/qlib/tree/7c31012b507a3823117bddcc693fc64899460b2a/examples/benchmarks>`_ and `previous version <https://github.com/microsoft/qlib/tree/v0.7.2/examples/benchmarks>`_
|
||||||
|
|
||||||
|
|
||||||
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>`_
|
||||||
|
|||||||
187
README.md
187
README.md
@@ -11,19 +11,28 @@
|
|||||||
Recent released features
|
Recent released features
|
||||||
| Feature | Status |
|
| Feature | Status |
|
||||||
| -- | ------ |
|
| -- | ------ |
|
||||||
| ADD model | [Released](https://github.com/microsoft/qlib/pull/704) on Nov 22, 2021 |
|
| HIST and IGMTF models | :chart_with_upwards_trend: [Released](https://github.com/microsoft/qlib/pull/1040) on Apr 10, 2022 |
|
||||||
| ADARNN model | [Released](https://github.com/microsoft/qlib/pull/689) on Nov 14, 2021 |
|
| Qlib [notebook tutorial](https://github.com/microsoft/qlib/tree/main/examples/tutorial) | 📖 [Released](https://github.com/microsoft/qlib/pull/1037) on Apr 7, 2022 |
|
||||||
| TCN model | [Released](https://github.com/microsoft/qlib/pull/668) on Nov 4, 2021 |
|
| Ibovespa index data | :rice: [Released](https://github.com/microsoft/qlib/pull/990) on Apr 6, 2022 |
|
||||||
|Temporal Routing Adaptor (TRA) | [Released](https://github.com/microsoft/qlib/pull/531) on July 30, 2021 |
|
| Point-in-Time database | :hammer: [Released](https://github.com/microsoft/qlib/pull/343) on Mar 10, 2022 |
|
||||||
| Transformer & Localformer | [Released](https://github.com/microsoft/qlib/pull/508) on July 22, 2021 |
|
| Arctic Provider Backend & Orderbook data example | :hammer: [Released](https://github.com/microsoft/qlib/pull/744) on Jan 17, 2022 |
|
||||||
| Release Qlib v0.7.0 | [Released](https://github.com/microsoft/qlib/releases/tag/v0.7.0) on July 12, 2021 |
|
| Meta-Learning-based framework & DDG-DA | :chart_with_upwards_trend: :hammer: [Released](https://github.com/microsoft/qlib/pull/743) on Jan 10, 2022 |
|
||||||
| TCTS Model | [Released](https://github.com/microsoft/qlib/pull/491) on July 1, 2021 |
|
| Planning-based portfolio optimization | :hammer: [Released](https://github.com/microsoft/qlib/pull/754) on Dec 28, 2021 |
|
||||||
| Online serving and automatic model rolling | :star: [Released](https://github.com/microsoft/qlib/pull/290) on May 17, 2021 |
|
| Release Qlib v0.8.0 | :octocat: [Released](https://github.com/microsoft/qlib/releases/tag/v0.8.0) on Dec 8, 2021 |
|
||||||
| DoubleEnsemble Model | [Released](https://github.com/microsoft/qlib/pull/286) on Mar 2, 2021 |
|
| ADD model | :chart_with_upwards_trend: [Released](https://github.com/microsoft/qlib/pull/704) on Nov 22, 2021 |
|
||||||
| High-frequency data processing example | [Released](https://github.com/microsoft/qlib/pull/257) on Feb 5, 2021 |
|
| ADARNN model | :chart_with_upwards_trend: [Released](https://github.com/microsoft/qlib/pull/689) on Nov 14, 2021 |
|
||||||
| High-frequency trading example | [Part of code released](https://github.com/microsoft/qlib/pull/227) on Jan 28, 2021 |
|
| TCN model | :chart_with_upwards_trend: [Released](https://github.com/microsoft/qlib/pull/668) on Nov 4, 2021 |
|
||||||
| High-frequency data(1min) | [Released](https://github.com/microsoft/qlib/pull/221) on Jan 27, 2021 |
|
| Nested Decision Framework | :hammer: [Released](https://github.com/microsoft/qlib/pull/438) on Oct 1, 2021. [Example](https://github.com/microsoft/qlib/blob/main/examples/nested_decision_execution/workflow.py) and [Doc](https://qlib.readthedocs.io/en/latest/component/highfreq.html) |
|
||||||
| Tabnet Model | [Released](https://github.com/microsoft/qlib/pull/205) on Jan 22, 2021 |
|
| Temporal Routing Adaptor (TRA) | :chart_with_upwards_trend: [Released](https://github.com/microsoft/qlib/pull/531) on July 30, 2021 |
|
||||||
|
| Transformer & Localformer | :chart_with_upwards_trend: [Released](https://github.com/microsoft/qlib/pull/508) on July 22, 2021 |
|
||||||
|
| Release Qlib v0.7.0 | :octocat: [Released](https://github.com/microsoft/qlib/releases/tag/v0.7.0) on July 12, 2021 |
|
||||||
|
| TCTS Model | :chart_with_upwards_trend: [Released](https://github.com/microsoft/qlib/pull/491) on July 1, 2021 |
|
||||||
|
| Online serving and automatic model rolling | :hammer: [Released](https://github.com/microsoft/qlib/pull/290) on May 17, 2021 |
|
||||||
|
| DoubleEnsemble Model | :chart_with_upwards_trend: [Released](https://github.com/microsoft/qlib/pull/286) on Mar 2, 2021 |
|
||||||
|
| High-frequency data processing example | :hammer: [Released](https://github.com/microsoft/qlib/pull/257) on Feb 5, 2021 |
|
||||||
|
| High-frequency trading example | :chart_with_upwards_trend: [Part of code released](https://github.com/microsoft/qlib/pull/227) on Jan 28, 2021 |
|
||||||
|
| High-frequency data(1min) | :rice: [Released](https://github.com/microsoft/qlib/pull/221) on Jan 27, 2021 |
|
||||||
|
| Tabnet Model | :chart_with_upwards_trend: [Released](https://github.com/microsoft/qlib/pull/205) on Jan 22, 2021 |
|
||||||
|
|
||||||
Features released before 2021 are not listed here.
|
Features released before 2021 are not listed here.
|
||||||
|
|
||||||
@@ -40,35 +49,58 @@ With Qlib, users can easily try ideas to create better Quant investment strategi
|
|||||||
|
|
||||||
For more details, please refer to our paper ["Qlib: An AI-oriented Quantitative Investment Platform"](https://arxiv.org/abs/2009.11189).
|
For more details, please refer to our paper ["Qlib: An AI-oriented Quantitative Investment Platform"](https://arxiv.org/abs/2009.11189).
|
||||||
|
|
||||||
- [**Plans**](#plans)
|
|
||||||
- [Framework of Qlib](#framework-of-qlib)
|
|
||||||
- [Quick Start](#quick-start)
|
|
||||||
- [Installation](#installation)
|
|
||||||
- [Data Preparation](#data-preparation)
|
|
||||||
- [Auto Quant Research Workflow](#auto-quant-research-workflow)
|
|
||||||
- [Building Customized Quant Research Workflow by Code](#building-customized-quant-research-workflow-by-code)
|
|
||||||
- [**Quant Model(Paper) Zoo**](#quant-model-paper-zoo)
|
|
||||||
- [Run a single model](#run-a-single-model)
|
|
||||||
- [Run multiple models](#run-multiple-models)
|
|
||||||
- [**Quant Dataset Zoo**](#quant-dataset-zoo)
|
|
||||||
- [More About Qlib](#more-about-qlib)
|
|
||||||
- [Offline Mode and Online Mode](#offline-mode-and-online-mode)
|
|
||||||
- [Performance of Qlib Data Server](#performance-of-qlib-data-server)
|
|
||||||
- [Related Reports](#related-reports)
|
|
||||||
- [Contact Us](#contact-us)
|
|
||||||
- [Contributing](#contributing)
|
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<th>Frameworks, Tutorial, Data & DevOps</th>
|
||||||
|
<th>Main Challenges & Solutions in Quant Research</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<li><a href="#plans"><strong>Plans</strong></a></li>
|
||||||
|
<li><a href="#framework-of-qlib">Framework of Qlib</a></li>
|
||||||
|
<li><a href="#quick-start">Quick Start</a></li>
|
||||||
|
<ul dir="auto">
|
||||||
|
<li type="circle"><a href="#installation">Installation</a> </li>
|
||||||
|
<li type="circle"><a href="#data-preparation">Data Preparation</a></li>
|
||||||
|
<li type="circle"><a href="#auto-quant-research-workflow">Auto Quant Research Workflow</a></li>
|
||||||
|
<li type="circle"><a href="#building-customized-quant-research-workflow-by-code">Building Customized Quant Research Workflow by Code</a></li></ul>
|
||||||
|
<li><a href="#quant-dataset-zoo"><strong>Quant Dataset Zoo</strong></a></li>
|
||||||
|
<li><a href="#more-about-qlib">More About Qlib</a></li>
|
||||||
|
<li><a href="#offline-mode-and-online-mode">Offline Mode and Online Mode</a>
|
||||||
|
<ul>
|
||||||
|
<li type="circle"><a href="#performance-of-qlib-data-server">Performance of Qlib Data Server</a></li></ul>
|
||||||
|
<li><a href="#related-reports">Related Reports</a></li>
|
||||||
|
<li><a href="#contact-us">Contact Us</a></li>
|
||||||
|
<li><a href="#contributing">Contributing</a></li>
|
||||||
|
</td>
|
||||||
|
<td valign="baseline">
|
||||||
|
<li><a href="#main-challenges--solutions-in-quant-research">Main Challenges & Solutions in Quant Research</a>
|
||||||
|
<ul>
|
||||||
|
<li type="circle"><a href="#forecasting-finding-valuable-signalspatterns">Forecasting: Finding Valuable Signals/Patterns</a>
|
||||||
|
<ul>
|
||||||
|
<li type="disc"><a href="#quant-model-paper-zoo"><strong>Quant Model (Paper) Zoo</strong></a>
|
||||||
|
<ul>
|
||||||
|
<li type="circle"><a href="#run-a-single-model">Run a Single Model</a></li>
|
||||||
|
<li type="circle"><a href="#run-multiple-models">Run Multiple Models</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li type="circle"><a href="#adapting-to-market-dynamics">Adapting to Market Dynamics</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
# Plans
|
# Plans
|
||||||
New features under development(order by estimated release time).
|
New features under development(order by estimated release time).
|
||||||
Your feedbacks about the features are very important.
|
Your feedbacks about the features are very important.
|
||||||
| Feature | Status |
|
<!-- | Feature | Status | -->
|
||||||
| -- | ------ |
|
<!-- | -- | ------ | -->
|
||||||
| Planning-based portfolio optimization | Under review: https://github.com/microsoft/qlib/pull/280 |
|
|
||||||
| Fund data supporting and analysis | Under review: https://github.com/microsoft/qlib/pull/292 |
|
|
||||||
| Point-in-Time database | Under review: https://github.com/microsoft/qlib/pull/343 |
|
|
||||||
| High-frequency trading | Under review: https://github.com/microsoft/qlib/pull/408 |
|
|
||||||
| Meta-Learning-based data selection | Initial opensource version under development |
|
|
||||||
|
|
||||||
# Framework of Qlib
|
# Framework of Qlib
|
||||||
|
|
||||||
@@ -76,7 +108,6 @@ Your feedbacks about the features are very important.
|
|||||||
<img src="docs/_static/img/framework.svg" />
|
<img src="docs/_static/img/framework.svg" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
At the module level, Qlib is a platform that consists of the above components. The components are designed as loose-coupled modules, and each component could be used stand-alone.
|
At the module level, Qlib is a platform that consists of the above components. The components are designed as loose-coupled modules, and each component could be used stand-alone.
|
||||||
|
|
||||||
| Name | Description |
|
| Name | Description |
|
||||||
@@ -88,6 +119,8 @@ At the module level, Qlib is a platform that consists of the above components. T
|
|||||||
* The modules with hand-drawn style are under development and will be released in the future.
|
* The modules with hand-drawn style are under development and will be released in the future.
|
||||||
* The modules with dashed borders are highly user-customizable and extendible.
|
* The modules with dashed borders are highly user-customizable and extendible.
|
||||||
|
|
||||||
|
(p.s. framework image is created with https://draw.io/)
|
||||||
|
|
||||||
|
|
||||||
# Quick Start
|
# Quick Start
|
||||||
|
|
||||||
@@ -111,6 +144,7 @@ This table demonstrates the supported Python version of `Qlib`:
|
|||||||
1. **Conda** is suggested for managing your Python environment.
|
1. **Conda** is suggested for managing your Python environment.
|
||||||
1. Please pay attention that installing cython in Python 3.6 will raise some error when installing ``Qlib`` from source. If users use Python 3.6 on their machines, it is recommended to *upgrade* Python to version 3.7 or use `conda`'s Python to install ``Qlib`` from source.
|
1. Please pay attention that installing cython in Python 3.6 will raise some error when installing ``Qlib`` from source. If users use Python 3.6 on their machines, it is recommended to *upgrade* Python to version 3.7 or use `conda`'s Python to install ``Qlib`` from source.
|
||||||
1. For Python 3.9, `Qlib` supports running workflows such as training models, doing backtest and plot most of the related figures (those included in [notebook](examples/workflow_by_code.ipynb)). However, plotting for the *model performance* is not supported for now and we will fix this when the dependent packages are upgraded in the future.
|
1. For Python 3.9, `Qlib` supports running workflows such as training models, doing backtest and plot most of the related figures (those included in [notebook](examples/workflow_by_code.ipynb)). However, plotting for the *model performance* is not supported for now and we will fix this when the dependent packages are upgraded in the future.
|
||||||
|
1. `Qlib`Requires `tables` package, `hdf5` in tables does not support python3.9.
|
||||||
|
|
||||||
### Install with pip
|
### Install with pip
|
||||||
Users can easily install ``Qlib`` by pip according to the following command.
|
Users can easily install ``Qlib`` by pip according to the following command.
|
||||||
@@ -132,19 +166,13 @@ Also, users can install the latest dev version ``Qlib`` by the source code accor
|
|||||||
```
|
```
|
||||||
|
|
||||||
* Clone the repository and install ``Qlib`` as follows.
|
* Clone the repository and install ``Qlib`` as follows.
|
||||||
* If you haven't installed qlib by the command ``pip install pyqlib`` before:
|
|
||||||
```bash
|
|
||||||
git clone https://github.com/microsoft/qlib.git && cd qlib
|
|
||||||
python setup.py install
|
|
||||||
```
|
|
||||||
* If you have already installed the stable version by the command ``pip install pyqlib``:
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/microsoft/qlib.git && cd qlib
|
git clone https://github.com/microsoft/qlib.git && cd qlib
|
||||||
pip install .
|
pip install .
|
||||||
```
|
```
|
||||||
**Note**: **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:
|
||||||
@@ -159,15 +187,19 @@ Load and prepare data by running the following code:
|
|||||||
|
|
||||||
This dataset is created by public data collected by [crawler scripts](scripts/data_collector/), which have been released in
|
This dataset is created by public data collected by [crawler scripts](scripts/data_collector/), which have been released in
|
||||||
the same repository.
|
the same repository.
|
||||||
Users could create the same dataset with it.
|
Users could create the same dataset with it. [Description of dataset](https://github.com/microsoft/qlib/tree/main/scripts/data_collector#description-of-dataset)
|
||||||
|
|
||||||
*Please pay **ATTENTION** that the data is collected from [Yahoo Finance](https://finance.yahoo.com/lookup), and the data might not be perfect.
|
*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 a high-quality dataset. For more information, users can refer to the [related document](https://qlib.readthedocs.io/en/latest/component/data.html#converting-csv-format-into-qlib-format)*.
|
We recommend users to prepare their own data if they have a high-quality dataset. For more information, users can refer to the [related document](https://qlib.readthedocs.io/en/latest/component/data.html#converting-csv-format-into-qlib-format)*.
|
||||||
|
|
||||||
### Automatic update of daily frequency data (from yahoo finance)
|
### Automatic update of daily frequency data (from yahoo finance)
|
||||||
|
> This step is *Optional* if users only want to try their models and strategies on history data.
|
||||||
|
>
|
||||||
> 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.
|
||||||
|
>
|
||||||
> For more information refer to: [yahoo collector](https://github.com/microsoft/qlib/tree/main/scripts/data_collector/yahoo#automatic-update-of-daily-frequency-datafrom-yahoo-finance)
|
> **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)
|
||||||
|
|
||||||
* 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`
|
||||||
@@ -192,7 +224,7 @@ We recommend users to prepare their own data if they have a high-quality dataset
|
|||||||
```python
|
```python
|
||||||
import qlib
|
import qlib
|
||||||
from qlib.data import D
|
from qlib.data import D
|
||||||
from qlib.config import REG_CN
|
from qlib.constant import REG_CN
|
||||||
|
|
||||||
# Initialization
|
# Initialization
|
||||||
mount_path = "~/.qlib/qlib_data/cn_data" # target_dir
|
mount_path = "~/.qlib/qlib_data/cn_data" # target_dir
|
||||||
@@ -277,8 +309,18 @@ Qlib provides a tool named `qrun` to run the whole workflow automatically (inclu
|
|||||||
## Building Customized Quant Research Workflow by Code
|
## Building Customized Quant Research Workflow by Code
|
||||||
The automatic workflow may not suit the research workflow of all Quant researchers. To support a flexible Quant research workflow, Qlib also provides a modularized interface to allow researchers to build their own workflow by code. [Here](examples/workflow_by_code.ipynb) is a demo for customized Quant research workflow by code.
|
The automatic workflow may not suit the research workflow of all Quant researchers. To support a flexible Quant research workflow, Qlib also provides a modularized interface to allow researchers to build their own workflow by code. [Here](examples/workflow_by_code.ipynb) is a demo for customized Quant research workflow by code.
|
||||||
|
|
||||||
|
# Main Challenges & Solutions in Quant Research
|
||||||
|
Quant investment is an very unique scenario with lots of key challenges to be solved.
|
||||||
|
Currently, Qlib provides some solutions for several of them.
|
||||||
|
|
||||||
# [Quant Model (Paper) Zoo](examples/benchmarks)
|
## Forecasting: Finding Valuable Signals/Patterns
|
||||||
|
Accurate forecasting of the stock price trend is a very important part to construct profitable portfolios.
|
||||||
|
However, huge amount of data with various formats in the financial market which make it challenging to build forecasting models.
|
||||||
|
|
||||||
|
An increasing number of SOTA Quant research works/papers, which focus on building forecasting models to mine valuable signals/patterns in complex financial data, are released in `Qlib`
|
||||||
|
|
||||||
|
|
||||||
|
### [Quant Model (Paper) Zoo](examples/benchmarks)
|
||||||
|
|
||||||
Here is a list of models built on `Qlib`.
|
Here is a list of models built on `Qlib`.
|
||||||
- [GBDT based on XGBoost (Tianqi Chen, et al. KDD 2016)](examples/benchmarks/XGBoost/)
|
- [GBDT based on XGBoost (Tianqi Chen, et al. KDD 2016)](examples/benchmarks/XGBoost/)
|
||||||
@@ -300,12 +342,14 @@ Here is a list of models built on `Qlib`.
|
|||||||
- [TCN based on pytorch (Shaojie Bai, et al. 2018)](examples/benchmarks/TCN/)
|
- [TCN based on pytorch (Shaojie Bai, et al. 2018)](examples/benchmarks/TCN/)
|
||||||
- [ADARNN based on pytorch (YunTao Du, et al. 2021)](examples/benchmarks/ADARNN/)
|
- [ADARNN based on pytorch (YunTao Du, et al. 2021)](examples/benchmarks/ADARNN/)
|
||||||
- [ADD based on pytorch (Hongshun Tang, et al.2020)](examples/benchmarks/ADD/)
|
- [ADD based on pytorch (Hongshun Tang, et al.2020)](examples/benchmarks/ADD/)
|
||||||
|
- [IGMTF based on pytorch (Wentao Xu, et al.2021)](examples/benchmarks/IGMTF/)
|
||||||
|
- [HIST based on pytorch (Wentao Xu, et al.2021)](examples/benchmarks/HIST/)
|
||||||
|
|
||||||
Your PR of new Quant models is highly welcomed.
|
Your PR of new Quant models is highly welcomed.
|
||||||
|
|
||||||
The performance of each model on the `Alpha158` and `Alpha360` dataset can be found [here](examples/benchmarks/README.md).
|
The performance of each model on the `Alpha158` and `Alpha360` dataset can be found [here](examples/benchmarks/README.md).
|
||||||
|
|
||||||
## Run a single model
|
### Run a single model
|
||||||
All the models listed above are runnable with ``Qlib``. Users can find the config files we provide and some details about the model through the [benchmarks](examples/benchmarks) folder. More information can be retrieved at the model files listed above.
|
All the models listed above are runnable with ``Qlib``. Users can find the config files we provide and some details about the model through the [benchmarks](examples/benchmarks) folder. More information can be retrieved at the model files listed above.
|
||||||
|
|
||||||
`Qlib` provides three different ways to run a single model, users can pick the one that fits their cases best:
|
`Qlib` provides three different ways to run a single model, users can pick the one that fits their cases best:
|
||||||
@@ -315,7 +359,7 @@ All the models listed above are runnable with ``Qlib``. Users can find the confi
|
|||||||
- Users can use the script [`run_all_model.py`](examples/run_all_model.py) listed in the `examples` folder to run a model. Here is an example of the specific shell command to be used: `python run_all_model.py run --models=lightgbm`, where the `--models` arguments can take any number of models listed above(the available models can be found in [benchmarks](examples/benchmarks/)). For more use cases, please refer to the file's [docstrings](examples/run_all_model.py).
|
- Users can use the script [`run_all_model.py`](examples/run_all_model.py) listed in the `examples` folder to run a model. Here is an example of the specific shell command to be used: `python run_all_model.py run --models=lightgbm`, where the `--models` arguments can take any number of models listed above(the available models can be found in [benchmarks](examples/benchmarks/)). For more use cases, please refer to the file's [docstrings](examples/run_all_model.py).
|
||||||
- **NOTE**: Each baseline has different environment dependencies, please make sure that your python version aligns with the requirements(e.g. TFT only supports Python 3.6~3.7 due to the limitation of `tensorflow==1.15.0`)
|
- **NOTE**: Each baseline has different environment dependencies, please make sure that your python version aligns with the requirements(e.g. TFT only supports Python 3.6~3.7 due to the limitation of `tensorflow==1.15.0`)
|
||||||
|
|
||||||
## Run multiple models
|
### Run multiple models
|
||||||
`Qlib` also provides a script [`run_all_model.py`](examples/run_all_model.py) which can run multiple models for several iterations. (**Note**: the script only support *Linux* for now. Other OS will be supported in the future. Besides, it doesn't support parallel running the same model for multiple times as well, and this will be fixed in the future development too.)
|
`Qlib` also provides a script [`run_all_model.py`](examples/run_all_model.py) which can run multiple models for several iterations. (**Note**: the script only support *Linux* for now. Other OS will be supported in the future. Besides, it doesn't support parallel running the same model for multiple times as well, and this will be fixed in the future development too.)
|
||||||
|
|
||||||
The script will create a unique virtual environment for each model, and delete the environments after training. Thus, only experiment results such as `IC` and `backtest` results will be generated and stored.
|
The script will create a unique virtual environment for each model, and delete the environments after training. Thus, only experiment results such as `IC` and `backtest` results will be generated and stored.
|
||||||
@@ -327,6 +371,14 @@ python run_all_model.py run 10
|
|||||||
|
|
||||||
It also provides the API to run specific models at once. For more use cases, please refer to the file's [docstrings](examples/run_all_model.py).
|
It also provides the API to run specific models at once. For more use cases, please refer to the file's [docstrings](examples/run_all_model.py).
|
||||||
|
|
||||||
|
## [Adapting to Market Dynamics](examples/benchmarks_dynamic)
|
||||||
|
|
||||||
|
Due to the non-stationary nature of the environment of the financial market, the data distribution may change in different periods, which makes the performance of models build on training data decays in the future test data.
|
||||||
|
So adapting the forecasting models/strategies to market dynamics is very important to the model/strategies' performance.
|
||||||
|
|
||||||
|
Here is a list of solutions built on `Qlib`.
|
||||||
|
- [Rolling Retraining](examples/benchmarks_dynamic/baseline/)
|
||||||
|
- [DDG-DA on pytorch (Wendi, et al. AAAI 2022)](examples/benchmarks_dynamic/DDG-DA/)
|
||||||
|
|
||||||
# Quant Dataset Zoo
|
# Quant Dataset Zoo
|
||||||
Dataset plays a very important role in Quant. Here is a list of the datasets built on `Qlib`:
|
Dataset plays a very important role in Quant. Here is a list of the datasets built on `Qlib`:
|
||||||
@@ -340,6 +392,8 @@ Dataset plays a very important role in Quant. Here is a list of the datasets bui
|
|||||||
Your PR to build new Quant dataset is highly welcomed.
|
Your PR to build new Quant dataset is highly welcomed.
|
||||||
|
|
||||||
# More About Qlib
|
# More About Qlib
|
||||||
|
If you want to have a quick glance at the most frequently used components of qlib, you can try notebooks [here](examples/tutorial/).
|
||||||
|
|
||||||
The detailed documents are organized in [docs](docs/).
|
The detailed documents are organized in [docs](docs/).
|
||||||
[Sphinx](http://www.sphinx-doc.org) and the readthedocs theme is required to build the documentation in html formats.
|
[Sphinx](http://www.sphinx-doc.org) and the readthedocs theme is required to build the documentation in html formats.
|
||||||
```bash
|
```bash
|
||||||
@@ -397,17 +451,40 @@ Join IM discussion groups:
|
|||||||
||
|
||
|
||||||
|
|
||||||
# Contributing
|
# Contributing
|
||||||
|
We appreciate all contributions and thank all the contributors!
|
||||||
|
<a href="https://github.com/microsoft/qlib/graphs/contributors"><img src="https://contrib.rocks/image?repo=microsoft/qlib" /></a>
|
||||||
|
|
||||||
|
Before we released Qlib as an open-source project on Github in Sep 2020, Qlib is an internal project in our group. Unfortunately, the internal commit history is not kept. A lot of members in our group have also contributed a lot to Qlib, which includes Ruihua Wang, Yinda Zhang, Haisu Yu, Shuyu Wang, Bochen Pang, and [Dong Zhou](https://github.com/evanzd/evanzd). Especially thanks to [Dong Zhou](https://github.com/evanzd/evanzd) due to his initial version of Qlib.
|
||||||
|
|
||||||
|
## Guidance
|
||||||
|
|
||||||
This project welcomes contributions and suggestions.
|
This project welcomes contributions and suggestions.
|
||||||
**Here are some
|
**Here are some
|
||||||
[code standards](docs/developer/code_standard.rst) when you submit a pull request.**
|
[code standards and development guidance](docs/developer/code_standard_and_dev_guide.rst) for submiting a pull request.**
|
||||||
|
|
||||||
If you want to contribute to Qlib's document, you can follow the steps in the figure below.
|
Making contributions is not a hard thing. Solving an issue(maybe just answering a question raised in [issues list](https://github.com/microsoft/qlib/issues) or [gitter](https://gitter.im/Microsoft/qlib)), fixing/issuing a bug, improving the documents and even fixing a typo are important contributions to Qlib.
|
||||||
|
|
||||||
|
For example, if you want to contribute to Qlib's document/code, you can follow the steps in the figure below.
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="https://github.com/demon143/qlib/blob/main/docs/_static/img/change%20doc.gif" />
|
<img src="https://github.com/demon143/qlib/blob/main/docs/_static/img/change%20doc.gif" />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
If you don't know how to start to contribute, you can refer to the following examples.
|
||||||
|
| Type | Examples |
|
||||||
|
| -- | -- |
|
||||||
|
| Solving issues | [Answer a question](https://github.com/microsoft/qlib/issues/749); [issuing](https://github.com/microsoft/qlib/issues/765) or [fixing](https://github.com/microsoft/qlib/pull/792) a bug |
|
||||||
|
| Docs | [Improve docs quality](https://github.com/microsoft/qlib/pull/797/files) ; [Fix a typo](https://github.com/microsoft/qlib/pull/774) |
|
||||||
|
| Feature | Implement a [requested feature](https://github.com/microsoft/qlib/projects) like [this](https://github.com/microsoft/qlib/pull/754); [Refactor interfaces](https://github.com/microsoft/qlib/pull/539/files) |
|
||||||
|
| Dataset | [Add a dataset](https://github.com/microsoft/qlib/pull/733) |
|
||||||
|
| Models | [Implement a new model](https://github.com/microsoft/qlib/pull/689), [some instructions to contribute models](https://github.com/microsoft/qlib/tree/main/examples/benchmarks#contributing) |
|
||||||
|
|
||||||
|
[Good first issues](https://github.com/microsoft/qlib/labels/good%20first%20issue) are labelled to indicate that they are easy to start your contributions.
|
||||||
|
|
||||||
|
You can find some impefect implementation in Qlib by `rg 'TODO|FIXME' qlib`
|
||||||
|
|
||||||
|
If you would like to become one of Qlib's maintainers to contribute more (e.g. help merge PR, triage issues), please contact us by email([qlib@microsoft.com](mailto:qlib@microsoft.com)). We are glad to help to upgrade your permission.
|
||||||
|
|
||||||
|
## Licence
|
||||||
Most contributions require you to agree to a
|
Most contributions require you to agree to a
|
||||||
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
|
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
|
||||||
the right to use your contribution. For details, visit https://cla.opensource.microsoft.com.
|
the right to use your contribution. For details, visit https://cla.opensource.microsoft.com.
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
0.8.0
|
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
136
docs/advanced/PIT.rst
Normal file
136
docs/advanced/PIT.rst
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
.. _pit:
|
||||||
|
|
||||||
|
============================
|
||||||
|
(P)oint-(I)n-(T)ime Database
|
||||||
|
============================
|
||||||
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
|
|
||||||
|
Introduction
|
||||||
|
------------
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
|
||||||
|
In financial data (especially financial reports), the same piece of data may be amended for multiple times overtime. If we only use the latest version for historical backtesting, data leakage will happen.
|
||||||
|
Point-in-time database is designed for solving this problem to make sure user get the right version of data at any historical timestamp. It will keep the performance of online trading and historical backtesting the same.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Data Preparation
|
||||||
|
----------------
|
||||||
|
|
||||||
|
Qlib provides a crawler to help users to download financial data and then a converter to dump the data in Qlib format.
|
||||||
|
Please follow `scripts/data_collector/pit/README.md <https://github.com/microsoft/qlib/tree/main/scripts/data_collector/pit/>`_ to download and convert data.
|
||||||
|
Besides, you can find some additional usage examples there.
|
||||||
|
|
||||||
|
|
||||||
|
File-based design for PIT data
|
||||||
|
------------------------------
|
||||||
|
|
||||||
|
Qlib provides a file-based storage for PIT data.
|
||||||
|
|
||||||
|
For each feature, it contains 4 columns, i.e. date, period, value, _next.
|
||||||
|
Each row corresponds to a statement.
|
||||||
|
|
||||||
|
The meaning of each feature with filename like `XXX_a.data`:
|
||||||
|
|
||||||
|
- `date`: the statement's date of publication.
|
||||||
|
- `period`: the period of the statement. (e.g. it will be quarterly frequency in most of the markets)
|
||||||
|
- If it is an annual period, it will be an integer corresponding to the year
|
||||||
|
- If it is an quarterly periods, it will be an integer like `<year><index of quarter>`. The last two decimal digits represents the index of quarter. Others represent the year.
|
||||||
|
- `value`: the described value
|
||||||
|
- `_next`: the byte index of the next occurance of the field.
|
||||||
|
|
||||||
|
Besides the feature data, an index `XXX_a.index` is included to speed up the querying performance
|
||||||
|
|
||||||
|
The statements are soted by the `date` in ascending order from the beginning of the file.
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
# the data format from XXXX.data
|
||||||
|
array([(20070428, 200701, 0.090219 , 4294967295),
|
||||||
|
(20070817, 200702, 0.13933 , 4294967295),
|
||||||
|
(20071023, 200703, 0.24586301, 4294967295),
|
||||||
|
(20080301, 200704, 0.3479 , 80),
|
||||||
|
(20080313, 200704, 0.395989 , 4294967295),
|
||||||
|
(20080422, 200801, 0.100724 , 4294967295),
|
||||||
|
(20080828, 200802, 0.24996801, 4294967295),
|
||||||
|
(20081027, 200803, 0.33412001, 4294967295),
|
||||||
|
(20090325, 200804, 0.39011699, 4294967295),
|
||||||
|
(20090421, 200901, 0.102675 , 4294967295),
|
||||||
|
(20090807, 200902, 0.230712 , 4294967295),
|
||||||
|
(20091024, 200903, 0.30072999, 4294967295),
|
||||||
|
(20100402, 200904, 0.33546099, 4294967295),
|
||||||
|
(20100426, 201001, 0.083825 , 4294967295),
|
||||||
|
(20100812, 201002, 0.200545 , 4294967295),
|
||||||
|
(20101029, 201003, 0.260986 , 4294967295),
|
||||||
|
(20110321, 201004, 0.30739301, 4294967295),
|
||||||
|
(20110423, 201101, 0.097411 , 4294967295),
|
||||||
|
(20110831, 201102, 0.24825101, 4294967295),
|
||||||
|
(20111018, 201103, 0.318919 , 4294967295),
|
||||||
|
(20120323, 201104, 0.4039 , 420),
|
||||||
|
(20120411, 201104, 0.403925 , 4294967295),
|
||||||
|
(20120426, 201201, 0.112148 , 4294967295),
|
||||||
|
(20120810, 201202, 0.26484701, 4294967295),
|
||||||
|
(20121026, 201203, 0.370487 , 4294967295),
|
||||||
|
(20130329, 201204, 0.45004699, 4294967295),
|
||||||
|
(20130418, 201301, 0.099958 , 4294967295),
|
||||||
|
(20130831, 201302, 0.21044201, 4294967295),
|
||||||
|
(20131016, 201303, 0.30454299, 4294967295),
|
||||||
|
(20140325, 201304, 0.394328 , 4294967295),
|
||||||
|
(20140425, 201401, 0.083217 , 4294967295),
|
||||||
|
(20140829, 201402, 0.16450299, 4294967295),
|
||||||
|
(20141030, 201403, 0.23408499, 4294967295),
|
||||||
|
(20150421, 201404, 0.319612 , 4294967295),
|
||||||
|
(20150421, 201501, 0.078494 , 4294967295),
|
||||||
|
(20150828, 201502, 0.137504 , 4294967295),
|
||||||
|
(20151023, 201503, 0.201709 , 4294967295),
|
||||||
|
(20160324, 201504, 0.26420501, 4294967295),
|
||||||
|
(20160421, 201601, 0.073664 , 4294967295),
|
||||||
|
(20160827, 201602, 0.136576 , 4294967295),
|
||||||
|
(20161029, 201603, 0.188062 , 4294967295),
|
||||||
|
(20170415, 201604, 0.244385 , 4294967295),
|
||||||
|
(20170425, 201701, 0.080614 , 4294967295),
|
||||||
|
(20170728, 201702, 0.15151 , 4294967295),
|
||||||
|
(20171026, 201703, 0.25416601, 4294967295),
|
||||||
|
(20180328, 201704, 0.32954201, 4294967295),
|
||||||
|
(20180428, 201801, 0.088887 , 4294967295),
|
||||||
|
(20180802, 201802, 0.170563 , 4294967295),
|
||||||
|
(20181029, 201803, 0.25522 , 4294967295),
|
||||||
|
(20190329, 201804, 0.34464401, 4294967295),
|
||||||
|
(20190425, 201901, 0.094737 , 4294967295),
|
||||||
|
(20190713, 201902, 0. , 1040),
|
||||||
|
(20190718, 201902, 0.175322 , 4294967295),
|
||||||
|
(20191016, 201903, 0.25581899, 4294967295)],
|
||||||
|
dtype=[('date', '<u4'), ('period', '<u4'), ('value', '<f8'), ('_next', '<u4')])
|
||||||
|
# - each row contains 20 byte
|
||||||
|
|
||||||
|
|
||||||
|
# The data format from XXXX.index. It consists of two parts
|
||||||
|
# 1) the start index of the data. So the first part of the info will be like
|
||||||
|
2007
|
||||||
|
# 2) the remain index data will be like information below
|
||||||
|
# - The data indicate the **byte index** of first data update of a period.
|
||||||
|
# - e.g. Because the info at both byte 80 and 100 corresponds to 200704. The byte index of first occurance (i.e. 100) is recorded in the data.
|
||||||
|
array([ 0, 20, 40, 60, 100,
|
||||||
|
120, 140, 160, 180, 200,
|
||||||
|
220, 240, 260, 280, 300,
|
||||||
|
320, 340, 360, 380, 400,
|
||||||
|
440, 460, 480, 500, 520,
|
||||||
|
540, 560, 580, 600, 620,
|
||||||
|
640, 660, 680, 700, 720,
|
||||||
|
740, 760, 780, 800, 820,
|
||||||
|
840, 860, 880, 900, 920,
|
||||||
|
940, 960, 980, 1000, 1020,
|
||||||
|
1060, 4294967295], dtype=uint32)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Known limitations:
|
||||||
|
|
||||||
|
- Currently, the PIT database is designed for quarterly or annually factors, which can handle fundamental data of financial reports in most markets.
|
||||||
|
- Qlib leverage the file name to identify the type of the data. File with name like `XXX_q.data` corresponds to quarterly data. File with name like `XXX_a.data` corresponds to annual data.
|
||||||
|
- The caclulation of PIT is not performed in the optimal way. There is great potential to boost the performance of PIT data calcuation.
|
||||||
@@ -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,12 +15,12 @@ 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.
|
||||||
|
|
||||||
@@ -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,16 +1,16 @@
|
|||||||
.. _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.
|
||||||
@@ -19,7 +19,7 @@ However, users can use ``config`` method or override ``default_dump_all`` attrib
|
|||||||
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.
|
||||||
|
|
||||||
@@ -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,13 +1,13 @@
|
|||||||
.. _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.
|
||||||
|
|
||||||
@@ -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,11 +1,11 @@
|
|||||||
.. _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.
|
||||||
|
|
||||||
@@ -21,12 +21,18 @@ The introduction of ``Data Layer`` includes the following parts.
|
|||||||
- Cache
|
- Cache
|
||||||
- Data and Cache File Structure
|
- Data and Cache File Structure
|
||||||
|
|
||||||
|
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).
|
||||||
|
- 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.
|
||||||
|
- 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.
|
||||||
@@ -44,8 +50,15 @@ 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.
|
||||||
|
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).
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
@@ -96,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.
|
||||||
|
|
||||||
@@ -182,7 +195,7 @@ After conversion, users can find their Qlib format data in the directory `~/.qli
|
|||||||
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.
|
||||||
|
|
||||||
@@ -192,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:
|
||||||
|
|
||||||
@@ -213,7 +226,7 @@ The `trade unit` defines the unit number of stocks can be used in a trade, and t
|
|||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
from qlib.config 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)
|
||||||
|
|
||||||
|
|
||||||
@@ -234,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.
|
||||||
|
|
||||||
@@ -256,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`
|
||||||
@@ -291,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:
|
||||||
|
|
||||||
@@ -321,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 leanable ``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:
|
||||||
|
|
||||||
@@ -356,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`.
|
||||||
|
|
||||||
@@ -379,7 +392,7 @@ Users can also create their own `processor` by inheriting the base class of ``Pr
|
|||||||
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.
|
||||||
|
|
||||||
@@ -419,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 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.
|
||||||
@@ -440,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`.
|
||||||
|
|
||||||
@@ -463,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.
|
||||||
|
|
||||||
@@ -478,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.
|
||||||
|
|
||||||
@@ -495,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.
|
||||||
|
|
||||||
@@ -528,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.
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ To get the join trading performance of daily and intraday trading, they must int
|
|||||||
In order to support the joint backtest strategies in multiple levels, a corresponding framework is required. None of the publicly available high-frequency trading frameworks considers multi-level joint trading, which make the backtesting aforementioned inaccurate.
|
In order to support the joint backtest strategies in multiple levels, a corresponding framework is required. None of the publicly available high-frequency trading frameworks considers multi-level joint trading, which make the backtesting aforementioned inaccurate.
|
||||||
|
|
||||||
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 imporve 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.
|
||||||
@@ -26,6 +26,13 @@ The design of the framework is shown in the yellow part in the middle of the fig
|
|||||||
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>`_.
|
||||||
|
|
||||||
|
|
||||||
|
Besides, the above examples, here are some other related work about high-frequency trading in Qlib.
|
||||||
|
|
||||||
|
- `Prediction with high-frequency data <https://github.com/microsoft/qlib/tree/main/examples/highfreq#benchmarks-performance-predicting-the-price-trend-in-high-frequency-data>`_
|
||||||
|
- `Examples <https://github.com/microsoft/qlib/blob/main/examples/orderbook_data/>`_ to extract features form high-frequency data without fixed frequency.
|
||||||
|
- `A paper <https://github.com/microsoft/qlib/tree/high-freq-execution#high-frequency-execution>`_ for high-frequency trading.
|
||||||
|
|||||||
68
docs/component/meta.rst
Normal file
68
docs/component/meta.rst
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
.. _meta:
|
||||||
|
|
||||||
|
======================================================
|
||||||
|
Meta Controller: Meta-Task & Meta-Dataset & Meta-Model
|
||||||
|
======================================================
|
||||||
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
|
|
||||||
|
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 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`.
|
||||||
|
|
||||||
|
.. autoclass:: qlib.model.meta.task.MetaTask
|
||||||
|
:members:
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
.. autoclass:: qlib.model.meta.dataset.MetaTaskDataset
|
||||||
|
:members:
|
||||||
|
|
||||||
|
Meta Model
|
||||||
|
==========
|
||||||
|
|
||||||
|
General Meta Model
|
||||||
|
------------------
|
||||||
|
`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.
|
||||||
|
2. The `Meta Model` instance guides the workflow by giving useful information via the `inference` function.
|
||||||
|
|
||||||
|
.. autoclass:: qlib.model.meta.model.MetaModel
|
||||||
|
:members:
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
.. autoclass:: qlib.model.meta.model.MetaTaskModel
|
||||||
|
:members:
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
.. autoclass:: qlib.model.meta.model.MetaGuideModel
|
||||||
|
:members:
|
||||||
|
|
||||||
|
|
||||||
|
Example
|
||||||
|
=======
|
||||||
|
``Qlib`` provides an implementation of ``Meta Model`` module, ``DDG-DA``,
|
||||||
|
which adapts to the market dynamics.
|
||||||
|
|
||||||
|
``DDG-DA`` includes four steps:
|
||||||
|
|
||||||
|
1. Calculate meta-information and encapsulate it into ``Meta Task`` instances. All the meta-tasks form a ``Meta Dataset`` instance.
|
||||||
|
2. Train ``DDG-DA`` based on the training data of the meta-dataset.
|
||||||
|
3. Do the inference of the ``DDG-DA`` to get guide information.
|
||||||
|
4. Apply guide information to the forecasting models to improve their performances.
|
||||||
|
|
||||||
|
The `above example <https://github.com/microsoft/qlib/tree/main/examples/benchmarks_dynamic/DDG-DA>`_ can be found in ``examples/benchmarks_dynamic/DDG-DA/workflow.py``.
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
.. _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>`_.
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ The base class provides the following interfaces:
|
|||||||
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.
|
||||||
|
|
||||||
@@ -106,13 +106,16 @@ Example
|
|||||||
`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.
|
||||||
|
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
|
||||||
@@ -23,26 +23,30 @@ The `examples <https://github.com/microsoft/qlib/tree/main/examples/online_srv>`
|
|||||||
|
|
||||||
**NOTE**: User should keep his data source updated to support online serving. For example, Qlib provides `a batch of scripts <https://github.com/microsoft/qlib/blob/main/scripts/data_collector/yahoo/README.md#automatic-update-of-daily-frequency-datafrom-yahoo-finance>`_ to help users update Yahoo daily data.
|
**NOTE**: User should keep his data source updated to support online serving. For example, Qlib provides `a batch of scripts <https://github.com/microsoft/qlib/blob/main/scripts/data_collector/yahoo/README.md#automatic-update-of-daily-frequency-datafrom-yahoo-finance>`_ to help users update Yahoo daily data.
|
||||||
|
|
||||||
|
Known limitations currently
|
||||||
|
- Currently, the daily updating prediction for the next trading day is supported. But generating orders for the next trading day is not supported due to the `limitations of public data <https://github.com/microsoft/qlib/issues/215#issuecomment-766293563>_`
|
||||||
|
|
||||||
|
|
||||||
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,7 +6,7 @@ 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:
|
||||||
@@ -37,10 +37,10 @@ Here is a general view of the structure of the system:
|
|||||||
|
|
||||||
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, pleaes 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:
|
||||||
|
|
||||||
@@ -143,3 +143,9 @@ Here is a simple exampke of what is done in ``PortAnaRecord``, which users can r
|
|||||||
print(analysis_df)
|
print(analysis_df)
|
||||||
|
|
||||||
For more information about the APIs, please refer to `Record Template API <../reference/api.html#module-qlib.workflow.record_temp>`_.
|
For more information about the APIs, please refer to `Record Template API <../reference/api.html#module-qlib.workflow.record_temp>`_.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Known Limitations
|
||||||
|
=================
|
||||||
|
- The Python objects are saved based on pickle, which may results in issues when the environment dumping objects and loading objects are different.
|
||||||
|
|||||||
@@ -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:
|
||||||
|
|
||||||
@@ -20,8 +20,11 @@ Introduction
|
|||||||
- model_performance_graph
|
- model_performance_graph
|
||||||
|
|
||||||
|
|
||||||
|
All of the accumulated profit metrics(e.g. return, max drawdown) in Qlib are calculated by summation.
|
||||||
|
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.
|
||||||
|
|
||||||
@@ -38,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:
|
||||||
@@ -86,14 +89,14 @@ 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::
|
||||||
|
|
||||||
@@ -101,7 +104,7 @@ Graphical Result
|
|||||||
- 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, -1)/$close - 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`.
|
||||||
@@ -141,17 +144,17 @@ Graphical Result
|
|||||||
|
|
||||||
|
|
||||||
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::
|
||||||
|
|
||||||
@@ -223,17 +226,17 @@ Graphical Result
|
|||||||
|
|
||||||
..
|
..
|
||||||
.. 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::
|
||||||
..
|
..
|
||||||
@@ -259,17 +262,17 @@ Graphical Result
|
|||||||
..
|
..
|
||||||
|
|
||||||
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::
|
||||||
|
|
||||||
|
|||||||
@@ -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,20 +20,19 @@ Base Class & Interface
|
|||||||
======================
|
======================
|
||||||
|
|
||||||
BaseStrategy
|
BaseStrategy
|
||||||
------------------
|
------------
|
||||||
|
|
||||||
Qlib provides a base class ``qlib.contrib.strategy.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.
|
||||||
|
|
||||||
- `get_risk_degree`
|
- `generate_trade_decision`
|
||||||
Return the proportion of your total value you will use in investment. Dynamically risk_degree will result in Market timing.
|
generate_trade_decision is a key interface that generates trade decisions in each trading bar.
|
||||||
|
The frequency to call this method depends on the executor frequency("time_per_step"="day" by default). But the trading frequency can be decided by users' implementation.
|
||||||
- `generate_order_list`
|
For example, if the user wants to trading in weekly while the `time_per_step` is "day" in executor, user can return non-empty TradeDecision weekly(otherwise return empty like `this <https://github.com/microsoft/qlib/blob/main/qlib/contrib/strategy/signal_strategy.py#L132>`_ ).
|
||||||
Return the order list.
|
|
||||||
|
|
||||||
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`.
|
||||||
|
|
||||||
@@ -61,34 +60,50 @@ 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
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
``Topk-Drop`` algorithm:
|
There are two parameters for the ``Topk-Drop`` algorithm:
|
||||||
|
|
||||||
- `Topk`: The number of stocks held
|
- `Topk`: The number of stocks held
|
||||||
- `Drop`: The number of stocks sold on each trading day
|
- `Drop`: The number of stocks sold on each trading day
|
||||||
|
|
||||||
Currently, the number of held stocks is `Topk`.
|
In general, the number of stocks currently held is `Topk`, with the exception of being zero at the beginning period of trading.
|
||||||
On each trading day, the `Drop` number of held stocks with the worst `prediction score` will be sold, and the same number of unheld stocks with the best `prediction score` will be bought.
|
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.
|
||||||
|
|
||||||
|
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$.
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
``TopkDrop`` algorithm sells `Drop` stocks every trading day, which guarantees a fixed turnover rate.
|
|
||||||
|
|
||||||
- Generate the order list from the target amount
|
- Generate the order list from the target amount
|
||||||
|
|
||||||
|
EnhancedIndexingStrategy
|
||||||
|
------------------------
|
||||||
|
`EnhancedIndexingStrategy` Enhanced indexing combines the arts of active management and passive management,
|
||||||
|
with the aim of outperforming a benchmark index (e.g., S&P 500) in terms of portfolio return while controlling
|
||||||
|
the risk exposure (a.k.a. tracking error).
|
||||||
|
|
||||||
|
For more information, please refer to `qlib.contrib.strategy.signal_strategy.EnhancedIndexingStrategy`
|
||||||
|
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.
|
||||||
@@ -112,9 +127,14 @@ A prediction sample is shown as follows.
|
|||||||
|
|
||||||
``Forecast Model`` module can make predictions, please refer to `Forecast Model: Model Training & Prediction <model.html>`_.
|
``Forecast Model`` module can make predictions, please refer to `Forecast Model: Model Training & Prediction <model.html>`_.
|
||||||
|
|
||||||
|
Normally, the prediction score is the output of the models. But some models are learned from a label with a different scale. So the scale of the prediction score may be different from your expectation(e.g. the return of instruments).
|
||||||
|
|
||||||
|
Qlib didn't add a step to scale the prediction score to a unified scale due to the following reasons.
|
||||||
|
- Because not every trading strategy cares about the scale(e.g. TopkDropoutStrategy only cares about the order). So the strategy is responsible for rescaling the prediction score(e.g. some portfolio-optimization-based strategies may require a meaningful scale).
|
||||||
|
- 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``.
|
||||||
|
|
||||||
@@ -147,12 +167,9 @@ Running backtest
|
|||||||
start_time="2017-01-01", end_time="2020-08-01", strategy=strategy_obj
|
start_time="2017-01-01", end_time="2020-08-01", strategy=strategy_obj
|
||||||
)
|
)
|
||||||
analysis = dict()
|
analysis = dict()
|
||||||
analysis["excess_return_without_cost"] = risk_analysis(
|
# default frequency will be daily (i.e. "day")
|
||||||
report_normal["return"] - report_normal["bench"], freq=analysis_freq
|
analysis["excess_return_without_cost"] = risk_analysis(report_normal["return"] - report_normal["bench"])
|
||||||
)
|
analysis["excess_return_with_cost"] = risk_analysis(report_normal["return"] - report_normal["bench"] - report_normal["cost"])
|
||||||
analysis["excess_return_with_cost"] = risk_analysis(
|
|
||||||
report_normal["return"] - report_normal["bench"] - report_normal["cost"], freq=analysis_freq
|
|
||||||
)
|
|
||||||
|
|
||||||
analysis_df = pd.concat(analysis) # type: pd.DataFrame
|
analysis_df = pd.concat(analysis) # type: pd.DataFrame
|
||||||
pprint(analysis_df)
|
pprint(analysis_df)
|
||||||
@@ -177,6 +194,14 @@ Running backtest
|
|||||||
qlib.init(provider_uri=<qlib data dir>)
|
qlib.init(provider_uri=<qlib data dir>)
|
||||||
|
|
||||||
CSI300_BENCH = "SH000300"
|
CSI300_BENCH = "SH000300"
|
||||||
|
# Benchmark is for calculating the excess return of your strategy.
|
||||||
|
# Its data format will be like **ONE normal instrument**.
|
||||||
|
# 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')`
|
||||||
|
# It is different from the argument `market`, which indicates a universe of stocks (e.g. **A SET** of stocks like csi300)
|
||||||
|
# For example, you can query all data from a stock market with the code below.
|
||||||
|
# ` D.features(D.instruments(market='csi300'), ["$close"], start_time='2010-01-01', end_time='2017-12-31', freq='day')`
|
||||||
|
|
||||||
FREQ = "day"
|
FREQ = "day"
|
||||||
STRATEGY_CONFIG = {
|
STRATEGY_CONFIG = {
|
||||||
"topk": 50,
|
"topk": 50,
|
||||||
@@ -237,7 +262,7 @@ Running backtest
|
|||||||
|
|
||||||
|
|
||||||
Result
|
Result
|
||||||
------------------
|
------
|
||||||
|
|
||||||
The backtest results are in the following form:
|
The backtest results are in the following form:
|
||||||
|
|
||||||
@@ -282,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``.
|
||||||
@@ -121,14 +121,52 @@ If users want to use ``qrun`` under debug mode, please use the following command
|
|||||||
|
|
||||||
|
|
||||||
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.
|
||||||
|
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.
|
||||||
|
|
||||||
|
.. code-block:: YAML
|
||||||
|
|
||||||
|
model:
|
||||||
|
class: LGBModel
|
||||||
|
module_path: qlib.contrib.model.gbdt
|
||||||
|
kwargs:
|
||||||
|
loss: mse
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
from qlib.contrib.model.gbdt import LGBModel
|
||||||
|
kwargs = {
|
||||||
|
"loss": "mse" ,
|
||||||
|
"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,
|
||||||
|
}
|
||||||
|
LGBModel(kwargs)
|
||||||
|
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
@@ -152,12 +190,12 @@ The meaning of each field is as follows:
|
|||||||
|
|
||||||
|
|
||||||
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>`_.
|
||||||
|
|
||||||
@@ -193,9 +231,9 @@ The meaning of each field is as follows:
|
|||||||
``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 Model <../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>`_.
|
||||||
|
|
||||||
The keywords arguments configuration of the ``DataHandler`` is as follows:
|
The keywords arguments configuration of the ``DataHandler`` is as follows:
|
||||||
|
|
||||||
@@ -210,7 +248,7 @@ The keywords arguments configuration of the ``DataHandler`` is as follows:
|
|||||||
|
|
||||||
Users can refer to the document of `DataHandler <../component/data.html#datahandler>`_ for more information about the meaning of each field in the configuration.
|
Users can refer to the document of `DataHandler <../component/data.html#datahandler>`_ for more information about the meaning of each field in the configuration.
|
||||||
|
|
||||||
Here is the configuration for the ``Dataset`` module which will take care of data preprossing and slicing during the training and testing phase.
|
Here is the configuration for the ``Dataset`` module which will take care of data preprocessing and slicing during the training and testing phase.
|
||||||
|
|
||||||
.. code-block:: YAML
|
.. code-block:: YAML
|
||||||
|
|
||||||
@@ -228,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.
|
||||||
|
|
||||||
|
|||||||
12
docs/conf.py
12
docs/conf.py
@@ -54,9 +54,9 @@ master_doc = "index"
|
|||||||
|
|
||||||
|
|
||||||
# General information about the project.
|
# General information about the project.
|
||||||
project = u"QLib"
|
project = "QLib"
|
||||||
copyright = u"Microsoft"
|
copyright = "Microsoft"
|
||||||
author = u"Microsoft"
|
author = "Microsoft"
|
||||||
|
|
||||||
# The version info for the project you're documenting, acts as replacement for
|
# The version info for the project you're documenting, acts as replacement for
|
||||||
# |version| and |release|, also used in various other places throughout the
|
# |version| and |release|, also used in various other places throughout the
|
||||||
@@ -174,7 +174,7 @@ latex_elements = {
|
|||||||
# (source start file, target name, title,
|
# (source start file, target name, title,
|
||||||
# author, documentclass [howto, manual, or own class]).
|
# author, documentclass [howto, manual, or own class]).
|
||||||
latex_documents = [
|
latex_documents = [
|
||||||
(master_doc, "qlib.tex", u"QLib Documentation", u"Microsoft", "manual"),
|
(master_doc, "qlib.tex", "QLib Documentation", "Microsoft", "manual"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -182,7 +182,7 @@ latex_documents = [
|
|||||||
|
|
||||||
# One entry per manual page. List of tuples
|
# One entry per manual page. List of tuples
|
||||||
# (source start file, name, description, authors, manual section).
|
# (source start file, name, description, authors, manual section).
|
||||||
man_pages = [(master_doc, "qlib", u"QLib Documentation", [author], 1)]
|
man_pages = [(master_doc, "qlib", "QLib Documentation", [author], 1)]
|
||||||
|
|
||||||
|
|
||||||
# -- Options for Texinfo output -------------------------------------------
|
# -- Options for Texinfo output -------------------------------------------
|
||||||
@@ -194,7 +194,7 @@ texinfo_documents = [
|
|||||||
(
|
(
|
||||||
master_doc,
|
master_doc,
|
||||||
"QLib",
|
"QLib",
|
||||||
u"QLib Documentation",
|
"QLib Documentation",
|
||||||
author,
|
author,
|
||||||
"QLib",
|
"QLib",
|
||||||
"One line description of project.",
|
"One line description of project.",
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
.. _code_standard:
|
|
||||||
|
|
||||||
=================================
|
|
||||||
Code Standard
|
|
||||||
=================================
|
|
||||||
|
|
||||||
Docstring
|
|
||||||
=================================
|
|
||||||
Please use the `Numpydoc Style <https://stackoverflow.com/a/24385103>`_.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
A common error is the mixed use of space and tab. You can fix the bug by inputing the following code in the command line.
|
|
||||||
|
|
||||||
.. code-block:: python
|
|
||||||
|
|
||||||
pip install black
|
|
||||||
python -m black . -l 120
|
|
||||||
60
docs/developer/code_standard_and_dev_guide.rst
Normal file
60
docs/developer/code_standard_and_dev_guide.rst
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
.. _code_standard:
|
||||||
|
|
||||||
|
=============
|
||||||
|
Code Standard
|
||||||
|
=============
|
||||||
|
|
||||||
|
Docstring
|
||||||
|
=========
|
||||||
|
Please use the `Numpydoc Style <https://stackoverflow.com/a/24385103>`_.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
1. Qlib will check the code format with black. The PR will raise error if your code does not align to the standard of Qlib(e.g. a common error is the mixed use of space and tab).
|
||||||
|
You can fix the bug by inputing the following code in the command line.
|
||||||
|
|
||||||
|
.. code-block:: bash
|
||||||
|
|
||||||
|
pip install black
|
||||||
|
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).
|
||||||
|
Sometime pylint's restrictions are not that reasonable. You can ignore specific errors like this
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
return -ICLoss()(pred, target, index) # pylint: disable=E1130
|
||||||
|
|
||||||
|
|
||||||
|
3. Qlib will check your code style flake8. The checking command is implemented in [github action workflow](https://github.com/microsoft/qlib/blob/0e8b94a552f1c457cfa6cd2c1bb3b87ebb3fb279/.github/workflows/test.yml#L73).
|
||||||
|
You can fix the bug by inputing the following code in the command line.
|
||||||
|
|
||||||
|
.. code-block:: bash
|
||||||
|
|
||||||
|
flake8 --ignore E501,F541,E402,F401,W503,E741,E266,E203,E302,E731,E262,F523,F821,F811,F841,E713,E265,W291,E712,E722,W293 qlib
|
||||||
|
|
||||||
|
|
||||||
|
4. Qlib has integrated pre-commit, which will make it easier for developers to format their code.
|
||||||
|
Just run the following two commands, and the code will be automatically formatted using black and flake8 when the git commit command is executed.
|
||||||
|
|
||||||
|
.. code-block:: bash
|
||||||
|
|
||||||
|
pip install -e .[dev]
|
||||||
|
pre-commit install
|
||||||
|
|
||||||
|
|
||||||
|
=================================
|
||||||
|
Development Guidance
|
||||||
|
=================================
|
||||||
|
|
||||||
|
As a developer, you often want make changes to `Qlib` and hope it would reflect directly in your environment without reinstalling it. You can install `Qlib` in editable mode with following command.
|
||||||
|
The `[dev]` option will help you to install some related packages when developing `Qlib` (e.g. pytest, sphinx)
|
||||||
|
|
||||||
|
.. code-block:: bash
|
||||||
|
|
||||||
|
pip install -e .[dev]
|
||||||
@@ -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,7 +31,7 @@ The file structure can be viewed at fileStruct_.
|
|||||||
|
|
||||||
|
|
||||||
Example
|
Example
|
||||||
-------------------
|
-------
|
||||||
|
|
||||||
Let's take an example,
|
Let's take an example,
|
||||||
|
|
||||||
@@ -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.
|
||||||
|
|
||||||
@@ -31,7 +31,7 @@ Let's see an example,
|
|||||||
|
|
||||||
First make sure you have the latest version of `qlib` installed.
|
First make sure you have the latest version of `qlib` installed.
|
||||||
|
|
||||||
Then, you need to privide a configuration to setup the experiment.
|
Then, you need to provide a configuration to setup the experiment.
|
||||||
We write a simple configuration example as following,
|
We write a simple configuration example as following,
|
||||||
|
|
||||||
.. code-block:: YAML
|
.. code-block:: YAML
|
||||||
@@ -217,13 +217,13 @@ The tuner pipeline contains different tuners, and the `tuner` program will proce
|
|||||||
Each part represents a tuner, and its modules which are to be tuned. Space in each part is the hyper-parameters' space of a certain module, you need to create your searching space and modify it in `/qlib/contrib/tuner/space.py`. We use `hyperopt` package to help us to construct the space, you can see the detail of how to use it in https://github.com/hyperopt/hyperopt/wiki/FMin .
|
Each part represents a tuner, and its modules which are to be tuned. Space in each part is the hyper-parameters' space of a certain module, you need to create your searching space and modify it in `/qlib/contrib/tuner/space.py`. We use `hyperopt` package to help us to construct the space, you can see the detail of how to use it in https://github.com/hyperopt/hyperopt/wiki/FMin .
|
||||||
|
|
||||||
- model
|
- model
|
||||||
You need to provide the `class` and the `space` of the model. If the model is user's own implementation, you need to privide the `module_path`.
|
You need to provide the `class` and the `space` of the model. If the model is user's own implementation, you need to provide the `module_path`.
|
||||||
|
|
||||||
- trainer
|
- trainer
|
||||||
You need to proveide the `class` of the trainer. If the trainer is user's own implementation, you need to privide the `module_path`.
|
You need to provide the `class` of the trainer. If the trainer is user's own implementation, you need to provide the `module_path`.
|
||||||
|
|
||||||
- strategy
|
- strategy
|
||||||
You need to provide the `class` and the `space` of the strategy. If the strategy is user's own implementation, you need to privide the `module_path`.
|
You need to provide the `class` and the `space` of the strategy. If the strategy is user's own implementation, you need to provide the `module_path`.
|
||||||
|
|
||||||
- data_label
|
- data_label
|
||||||
The label of the data, you can search which kinds of labels will lead to a better result. This part is optional, and you only need to provide `space`.
|
The label of the data, you can search which kinds of labels will lead to a better result. This part is optional, and you only need to provide `space`.
|
||||||
@@ -273,7 +273,7 @@ You need to use the same dataset to evaluate your different `estimator` experime
|
|||||||
About the data and backtest
|
About the data and backtest
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
`data` and `backtest` are all same in the whole `tuner` experiment. Different `estimator` experiments must use the same data and backtest method. So, these two parts of config are same with that in `estimator` configuration. You can see the precise defination of these parts in `estimator` introduction. We only provide an example here.
|
`data` and `backtest` are all same in the whole `tuner` experiment. Different `estimator` experiments must use the same data and backtest method. So, these two parts of config are same with that in `estimator` configuration. You can see the precise definition of these parts in `estimator` introduction. We only provide an example here.
|
||||||
|
|
||||||
.. code-block:: YAML
|
.. code-block:: YAML
|
||||||
|
|
||||||
@@ -322,4 +322,3 @@ What we save are as following:
|
|||||||
- 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.
|
||||||
|
|
||||||
@@ -36,10 +36,11 @@ Document Structure
|
|||||||
:caption: COMPONENTS:
|
:caption: COMPONENTS:
|
||||||
|
|
||||||
Workflow: Workflow Management <component/workflow.rst>
|
Workflow: Workflow Management <component/workflow.rst>
|
||||||
Data Layer: Data Framework&Usage <component/data.rst>
|
Data Layer: Data Framework & Usage <component/data.rst>
|
||||||
Forecast Model: Model Training & Prediction <component/model.rst>
|
Forecast Model: Model Training & Prediction <component/model.rst>
|
||||||
Portfolio Management and Backtest <component/strategy.rst>
|
Portfolio Management and Backtest <component/strategy.rst>
|
||||||
Nested Decision Execution: High-Frequency Trading <component/highfreq.rst>
|
Nested Decision Execution: High-Frequency Trading <component/highfreq.rst>
|
||||||
|
Meta Controller: Meta-Task & Meta-Dataset & Meta-Model <component/meta.rst>
|
||||||
Qlib Recorder: Experiment Management <component/recorder.rst>
|
Qlib Recorder: Experiment Management <component/recorder.rst>
|
||||||
Analysis: Evaluation & Results Analysis <component/report.rst>
|
Analysis: Evaluation & Results Analysis <component/report.rst>
|
||||||
Online Serving: Online Management & Strategy & Tool <component/online.rst>
|
Online Serving: Online Management & Strategy & Tool <component/online.rst>
|
||||||
@@ -52,6 +53,7 @@ Document Structure
|
|||||||
Online & Offline mode <advanced/server.rst>
|
Online & Offline mode <advanced/server.rst>
|
||||||
Serialization <advanced/serial.rst>
|
Serialization <advanced/serial.rst>
|
||||||
Task Management <advanced/task_management.rst>
|
Task Management <advanced/task_management.rst>
|
||||||
|
Point-In-Time database <advanced/PIT.rst>
|
||||||
|
|
||||||
.. toctree::
|
.. toctree::
|
||||||
:maxdepth: 3
|
:maxdepth: 3
|
||||||
|
|||||||
@@ -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,7 +13,7 @@ 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
|
||||||
|
|||||||
@@ -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:
|
||||||
|
|
||||||
@@ -31,10 +31,10 @@ Users can easily intsall ``Qlib`` according to the following steps:
|
|||||||
git clone https://github.com/microsoft/qlib.git && cd qlib
|
git clone https://github.com/microsoft/qlib.git && cd qlib
|
||||||
python setup.py install
|
python setup.py install
|
||||||
|
|
||||||
To kown 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:
|
||||||
|
|
||||||
@@ -44,10 +44,10 @@ Load and prepare data by running the following code:
|
|||||||
|
|
||||||
This dataset is created by public data collected by crawler scripts in ``scripts/data_collector/``, which have been released in the same repository. Users could create the same dataset with it.
|
This dataset is created by public data collected by crawler scripts in ``scripts/data_collector/``, which have been released in the same repository. Users could create the same dataset with it.
|
||||||
|
|
||||||
To kown 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:
|
||||||
|
|
||||||
@@ -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:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,3 +3,4 @@ cmake
|
|||||||
numpy
|
numpy
|
||||||
scipy
|
scipy
|
||||||
scikit-learn
|
scikit-learn
|
||||||
|
pandas
|
||||||
|
|||||||
@@ -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:
|
||||||
@@ -120,6 +120,32 @@ For more details about features, please refer `Feature API <../component/data.ht
|
|||||||
|
|
||||||
.. note:: When calling `D.features()` at the client, use parameter `disk_cache=0` to skip dataset cache, use `disk_cache=1` to generate and use dataset cache. In addition, when calling at the server, users can use `disk_cache=2` to update the dataset cache.
|
.. note:: When calling `D.features()` at the client, use parameter `disk_cache=0` to skip dataset cache, use `disk_cache=1` to generate and use dataset cache. In addition, when calling at the server, users can use `disk_cache=2` to update the dataset cache.
|
||||||
|
|
||||||
|
|
||||||
|
When you are building complicated expressions, implementing all the expressions in a single string may not be easy.
|
||||||
|
For example, it looks quite long and complicated:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
>> from qlib.data import D
|
||||||
|
>> 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.
|
||||||
|
Here is an exmaple which does the same thing as above examples.
|
||||||
|
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
>> from qlib.data.ops import *
|
||||||
|
>> f1 = Feature("high") / Feature("close")
|
||||||
|
>> f2 = Feature("open") / Feature("close")
|
||||||
|
>> f3 = f1 + f2
|
||||||
|
>> f4 = f3 * f3 / f3
|
||||||
|
|
||||||
|
>> data = D.features(["sh600519"], [f4], start_time="20200101")
|
||||||
|
>> data.head()
|
||||||
|
|
||||||
|
|
||||||
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,14 +1,14 @@
|
|||||||
.. _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``.
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ Initialize Qlib before calling other APIs: run following code in python.
|
|||||||
|
|
||||||
import qlib
|
import qlib
|
||||||
# region in [REG_CN, REG_US]
|
# region in [REG_CN, REG_US]
|
||||||
from qlib.config 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)
|
||||||
|
|
||||||
@@ -37,18 +37,19 @@ Initialize Qlib before calling other APIs: run following code in python.
|
|||||||
Parameters
|
Parameters
|
||||||
-------------------
|
-------------------
|
||||||
|
|
||||||
Besides `provider_uri` and `region`, `qlib.init` has other parameters. The following are several important parameters of `qlib.init`:
|
Besides `provider_uri` and `region`, `qlib.init` has other parameters.
|
||||||
|
The following are several important parameters of `qlib.init` (`Qlib` has a lot of config. Only part of parameters are limited here. More detailed setting can be found `here <https://github.com/microsoft/qlib/blob/main/qlib/config.py>`_):
|
||||||
|
|
||||||
- `provider_uri`
|
- `provider_uri`
|
||||||
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`
|
||||||
Type: str, optional parameter(default: `qlib.config.REG_CN`).
|
Type: str, optional parameter(default: `qlib.constant.REG_CN`).
|
||||||
Currently: ``qlib.config.REG_US`` ('us') and ``qlib.config.REG_CN`` ('cn') is supported. Different value of `region` will result in different stock market mode.
|
Currently: ``qlib.constant.REG_US`` ('us') and ``qlib.constant.REG_CN`` ('cn') is supported. Different value of `region` will result in different stock market mode.
|
||||||
- ``qlib.config.REG_US``: US stock market.
|
- ``qlib.constant.REG_US``: US stock market.
|
||||||
- ``qlib.config.REG_CN``: China stock market.
|
- ``qlib.constant.REG_CN``: China stock market.
|
||||||
|
|
||||||
Different modes will result in different trading limitations and costs.
|
Different modes will result in different trading limitations and costs.
|
||||||
The region is just `shortcuts for defining a batch of configurations <https://github.com/microsoft/qlib/blob/main/qlib/config.py#L239>`_. Users can set the key configurations manually if the existing region setting can't meet their requirements.
|
The region is just `shortcuts for defining a batch of configurations <https://github.com/microsoft/qlib/blob/528f74af099bf6156e9480bcd2bb28e453231212/qlib/config.py#L249>`_, which include minimal trading order unit (``trade_unit``), trading limitation (``limit_threshold``) , etc. It is not a necessary part and users can set the key configurations manually if the existing region setting can't meet their requirements.
|
||||||
- `redis_host`
|
- `redis_host`
|
||||||
Type: str, optional parameter(default: "127.0.0.1"), host of `redis`
|
Type: str, optional parameter(default: "127.0.0.1"), host of `redis`
|
||||||
The lock and cache mechanism relies on redis.
|
The lock and cache mechanism relies on redis.
|
||||||
@@ -88,3 +89,9 @@ Besides `provider_uri` and `region`, `qlib.init` has other parameters. The follo
|
|||||||
"task_url": "mongodb://localhost:27017/", # your mongo url
|
"task_url": "mongodb://localhost:27017/", # your mongo url
|
||||||
"task_db_name": "rolling_db", # the database name of Task Management
|
"task_db_name": "rolling_db", # the database name of Task Management
|
||||||
})
|
})
|
||||||
|
|
||||||
|
- `logging_level`
|
||||||
|
The logging level for the system.
|
||||||
|
|
||||||
|
- `kernels`
|
||||||
|
The number of processes used when calculating features in Qlib's expression engine. It is very helpful to set it to 1 when you are debuggin an expression calculating exception
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
.. _installation:
|
.. _installation:
|
||||||
|
|
||||||
====================
|
============
|
||||||
Installation
|
Installation
|
||||||
====================
|
============
|
||||||
|
|
||||||
.. currentmodule:: qlib
|
.. currentmodule:: qlib
|
||||||
|
|
||||||
@@ -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
|
||||||
@@ -101,7 +101,7 @@ 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.
|
||||||
|
|
||||||
@@ -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
|
||||||
@@ -140,6 +140,6 @@ Also, ``Model`` can also be tested as a single module. An example has been given
|
|||||||
|
|
||||||
|
|
||||||
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>`_.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
|
|||||||
@@ -6,3 +6,4 @@
|
|||||||
|
|
||||||
[https://www.ijcai.org/Proceedings/2017/0366.pdf](https://www.ijcai.org/Proceedings/2017/0366.pdf)
|
[https://www.ijcai.org/Proceedings/2017/0366.pdf](https://www.ijcai.org/Proceedings/2017/0366.pdf)
|
||||||
|
|
||||||
|
- NOTE: Current version of implementation is just a simplified version of ALSTM. It is an LSTM with attention.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
catboost==0.24.3
|
catboost==0.24.3
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
lightgbm==3.1.0
|
lightgbm==3.1.0
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
|
|||||||
3
examples/benchmarks/HIST/README.md
Normal file
3
examples/benchmarks/HIST/README.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# HIST
|
||||||
|
* Code: [https://github.com/Wentao-Xu/HIST](https://github.com/Wentao-Xu/HIST)
|
||||||
|
* Paper: [HIST: A Graph-based Framework for Stock Trend Forecasting via Mining Concept-Oriented Shared InformationAdaRNN: Adaptive Learning and Forecasting for Time Series](https://arxiv.org/abs/2110.13716).
|
||||||
BIN
examples/benchmarks/HIST/qlib_csi300_stock_index.npy
Normal file
BIN
examples/benchmarks/HIST/qlib_csi300_stock_index.npy
Normal file
Binary file not shown.
4
examples/benchmarks/HIST/requirements.txt
Normal file
4
examples/benchmarks/HIST/requirements.txt
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
pandas==1.1.2
|
||||||
|
numpy==1.21.0
|
||||||
|
scikit_learn==0.23.2
|
||||||
|
torch==1.7.0
|
||||||
92
examples/benchmarks/HIST/workflow_config_hist_Alpha360.yaml
Normal file
92
examples/benchmarks/HIST/workflow_config_hist_Alpha360.yaml
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
qlib_init:
|
||||||
|
provider_uri: "~/.qlib/qlib_data/cn_data"
|
||||||
|
region: cn
|
||||||
|
market: &market csi300
|
||||||
|
benchmark: &benchmark SH000300
|
||||||
|
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: HIST
|
||||||
|
module_path: qlib.contrib.model.pytorch_hist
|
||||||
|
kwargs:
|
||||||
|
d_feat: 6
|
||||||
|
hidden_size: 64
|
||||||
|
num_layers: 2
|
||||||
|
dropout: 0
|
||||||
|
n_epochs: 200
|
||||||
|
lr: 1e-4
|
||||||
|
early_stop: 20
|
||||||
|
metric: ic
|
||||||
|
loss: mse
|
||||||
|
base_model: LSTM
|
||||||
|
model_path: "benchmarks/LSTM/model_lstm_csi300.pkl"
|
||||||
|
stock2concept: "benchmarks/HIST/qlib_csi300_stock2concept.npy"
|
||||||
|
stock_index: "benchmarks/HIST/qlib_csi300_stock_index.npy"
|
||||||
|
GPU: 0
|
||||||
|
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
|
||||||
4
examples/benchmarks/IGMTF/README.md
Normal file
4
examples/benchmarks/IGMTF/README.md
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# IGMTF
|
||||||
|
* Code: [https://github.com/Wentao-Xu/IGMTF](https://github.com/Wentao-Xu/IGMTF)
|
||||||
|
* Paper: [IGMTF: An Instance-wise Graph-based Framework for
|
||||||
|
Multivariate Time Series Forecasting](https://arxiv.org/abs/2109.06489).
|
||||||
4
examples/benchmarks/IGMTF/requirements.txt
Normal file
4
examples/benchmarks/IGMTF/requirements.txt
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
pandas==1.1.2
|
||||||
|
numpy==1.21.0
|
||||||
|
scikit_learn==0.23.2
|
||||||
|
torch==1.7.0
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
qlib_init:
|
||||||
|
provider_uri: "~/.qlib/qlib_data/cn_data"
|
||||||
|
region: cn
|
||||||
|
market: &market csi300
|
||||||
|
benchmark: &benchmark SH000300
|
||||||
|
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:
|
||||||
|
model: <MODEL>
|
||||||
|
dataset: <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: IGMTF
|
||||||
|
module_path: qlib.contrib.model.pytorch_igmtf
|
||||||
|
kwargs:
|
||||||
|
d_feat: 6
|
||||||
|
hidden_size: 64
|
||||||
|
num_layers: 2
|
||||||
|
dropout: 0
|
||||||
|
n_epochs: 200
|
||||||
|
lr: 1e-4
|
||||||
|
early_stop: 20
|
||||||
|
metric: ic
|
||||||
|
loss: mse
|
||||||
|
base_model: LSTM
|
||||||
|
model_path: "benchmarks/LSTM/model_lstm_csi300.pkl"
|
||||||
|
GPU: 0
|
||||||
|
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,4 @@
|
|||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
|
|||||||
@@ -2,3 +2,9 @@
|
|||||||
* 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.
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
lightgbm==3.1.0
|
lightgbm
|
||||||
|
|||||||
@@ -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:
|
||||||
|
model: <MODEL>
|
||||||
|
dataset: <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: LGBModel
|
||||||
|
module_path: qlib.contrib.model.gbdt
|
||||||
|
kwargs:
|
||||||
|
loss: mse
|
||||||
|
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
|
||||||
|
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,80 @@
|
|||||||
|
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: LGBModel
|
||||||
|
module_path: qlib.contrib.model.gbdt
|
||||||
|
kwargs:
|
||||||
|
loss: mse
|
||||||
|
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
|
||||||
|
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
|
||||||
@@ -22,7 +22,6 @@ data_handler_config: &data_handler_config
|
|||||||
- class: CSRankNorm
|
- class: CSRankNorm
|
||||||
kwargs:
|
kwargs:
|
||||||
fields_group: label
|
fields_group: label
|
||||||
label: ["Ref($close, -2) / Ref($close, -1) - 1"]
|
|
||||||
port_analysis_config: &port_analysis_config
|
port_analysis_config: &port_analysis_config
|
||||||
strategy:
|
strategy:
|
||||||
class: TopkDropoutStrategy
|
class: TopkDropoutStrategy
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
torch==1.2.0
|
torch==1.2.0
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
|
|||||||
@@ -63,8 +63,6 @@ task:
|
|||||||
module_path: qlib.contrib.model.pytorch_nn
|
module_path: qlib.contrib.model.pytorch_nn
|
||||||
kwargs:
|
kwargs:
|
||||||
loss: mse
|
loss: mse
|
||||||
input_dim: 157
|
|
||||||
output_dim: 1
|
|
||||||
lr: 0.002
|
lr: 0.002
|
||||||
lr_decay: 0.96
|
lr_decay: 0.96
|
||||||
lr_decay_steps: 100
|
lr_decay_steps: 100
|
||||||
@@ -73,6 +71,8 @@ task:
|
|||||||
batch_size: 8192
|
batch_size: 8192
|
||||||
GPU: 0
|
GPU: 0
|
||||||
weight_decay: 0.0002
|
weight_decay: 0.0002
|
||||||
|
pt_model_kwargs:
|
||||||
|
input_dim: 157
|
||||||
dataset:
|
dataset:
|
||||||
class: DatasetH
|
class: DatasetH
|
||||||
module_path: qlib.data.dataset
|
module_path: qlib.data.dataset
|
||||||
|
|||||||
@@ -51,8 +51,6 @@ task:
|
|||||||
module_path: qlib.contrib.model.pytorch_nn
|
module_path: qlib.contrib.model.pytorch_nn
|
||||||
kwargs:
|
kwargs:
|
||||||
loss: mse
|
loss: mse
|
||||||
input_dim: 360
|
|
||||||
output_dim: 1
|
|
||||||
lr: 0.002
|
lr: 0.002
|
||||||
lr_decay: 0.96
|
lr_decay: 0.96
|
||||||
lr_decay_steps: 100
|
lr_decay_steps: 100
|
||||||
@@ -60,6 +58,8 @@ task:
|
|||||||
max_steps: 8000
|
max_steps: 8000
|
||||||
batch_size: 4096
|
batch_size: 4096
|
||||||
GPU: 0
|
GPU: 0
|
||||||
|
pt_model_kwargs:
|
||||||
|
input_dim: 360
|
||||||
dataset:
|
dataset:
|
||||||
class: DatasetH
|
class: DatasetH
|
||||||
module_path: qlib.data.dataset
|
module_path: qlib.data.dataset
|
||||||
|
|||||||
@@ -4,20 +4,25 @@ This page lists a batch of methods designed for alpha seeking. Each method tries
|
|||||||
The alpha is evaluated in two ways.
|
The alpha is evaluated in two ways.
|
||||||
1. The correlation between the alpha and future return.
|
1. The correlation between the alpha and future return.
|
||||||
1. Constructing portfolio based on the alpha and evaluating the final total return.
|
1. Constructing portfolio based on the alpha and evaluating the final total return.
|
||||||
|
- The explanation of metrics can be found [here](https://qlib.readthedocs.io/en/latest/component/report.html#id4)
|
||||||
|
|
||||||
Here are the results of each benchmark model running on Qlib's `Alpha360` and `Alpha158` dataset with China's A shared-stock & CSI300 data respectively. The values of each metric are the mean and std calculated based on 20 runs with different random seeds.
|
Here are the results of each benchmark model running on Qlib's `Alpha360` and `Alpha158` dataset with China's A shared-stock & CSI300 data respectively. The values of each metric are the mean and std calculated based on 20 runs with different random seeds.
|
||||||
|
|
||||||
The numbers shown below demonstrate the performance of the entire `workflow` of each model. We will update the `workflow` as well as models in the near future for better results.
|
The numbers shown below demonstrate the performance of the entire `workflow` of each model. We will update the `workflow` as well as models in the near future for better results.
|
||||||
<!--
|
<!--
|
||||||
> If you need to reproduce the results below, please use the **v1** dataset: `python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/qlib_cn_1d --region cn --version v1`
|
> If you need to reproduce the results below, please use the **v1** dataset: `python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn --version v1`
|
||||||
>
|
>
|
||||||
> In the new version of qlib, the default dataset is **v2**. Since the data is collected from the YahooFinance API (which is not very stable), the results of *v2* and *v1* may differ -->
|
> In the new version of qlib, the default dataset is **v2**. Since the data is collected from the YahooFinance API (which is not very stable), the results of *v2* and *v1* may differ -->
|
||||||
|
|
||||||
> NOTE:
|
> NOTE:
|
||||||
> The backtest start from 0.8.0 is quite different from previous version. Please check out the changelog for the difference.
|
> The backtest start from 0.8.0 is quite different from previous version. Please check out the changelog for the difference.
|
||||||
|
|
||||||
|
> NOTE:
|
||||||
|
> We have very limited resources to implement and finetune the models. We tried our best effort to fairly compare these models. But some models may have greater potential than what it looks like in the table below. Your contribution is highly welcomed to explore their potential.
|
||||||
|
|
||||||
## Alpha158 dataset
|
## Results on CSI300
|
||||||
|
|
||||||
|
### 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 |
|
||||||
|------------------------------------------|-------------------------------------|-------------|-------------|-------------|-------------|-------------------|-------------------|--------------|
|
|------------------------------------------|-------------------------------------|-------------|-------------|-------------|-------------|-------------------|-------------------|--------------|
|
||||||
@@ -38,10 +43,9 @@ 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
|
|
||||||
|
|
||||||
| 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 |
|
||||||
|-------------------------------------------|----------|-------------|-------------|-------------|-------------|-------------------|-------------------|--------------|
|
|-------------------------------------------|----------|-------------|-------------|-------------|-------------|-------------------|-------------------|--------------|
|
||||||
@@ -51,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 |
|
||||||
@@ -62,7 +66,72 @@ The numbers shown below demonstrate the performance of the entire `workflow` of
|
|||||||
| GATs (Petar Velickovic, et al.) | Alpha360 | 0.0476±0.00 | 0.3508±0.02 | 0.0598±0.00 | 0.4604±0.01 | 0.0824±0.02 | 1.1079±0.26 | -0.0894±0.03 |
|
| GATs (Petar Velickovic, et al.) | Alpha360 | 0.0476±0.00 | 0.3508±0.02 | 0.0598±0.00 | 0.4604±0.01 | 0.0824±0.02 | 1.1079±0.26 | -0.0894±0.03 |
|
||||||
| TCTS(Xueqing Wu, et al.) | Alpha360 | 0.0508±0.00 | 0.3931±0.04 | 0.0599±0.00 | 0.4756±0.03 | 0.0893±0.03 | 1.2256±0.36 | -0.0857±0.02 |
|
| TCTS(Xueqing Wu, et al.) | Alpha360 | 0.0508±0.00 | 0.3931±0.04 | 0.0599±0.00 | 0.4756±0.03 | 0.0893±0.03 | 1.2256±0.36 | -0.0857±0.02 |
|
||||||
| TRA(Hengxu Lin, et al.) | Alpha360 | 0.0485±0.00 | 0.3787±0.03 | 0.0587±0.00 | 0.4756±0.03 | 0.0920±0.03 | 1.2789±0.42 | -0.0834±0.02 |
|
| TRA(Hengxu Lin, et al.) | Alpha360 | 0.0485±0.00 | 0.3787±0.03 | 0.0587±0.00 | 0.4756±0.03 | 0.0920±0.03 | 1.2789±0.42 | -0.0834±0.02 |
|
||||||
|
| IGMTF(Wentao Xu, et al.) | Alpha360 | 0.0480±0.00 | 0.3589±0.02 | 0.0606±0.00 | 0.4773±0.01 | 0.0946±0.02 | 1.3509±0.25 | -0.0716±0.02 |
|
||||||
|
| HIST(Wentao Xu, et al.) | Alpha360 | 0.0522±0.00 | 0.3530±0.01 | 0.0667±0.00 | 0.4576±0.01 | 0.0987±0.02 | 1.3726±0.27 | -0.0681±0.01 |
|
||||||
|
|
||||||
|
|
||||||
- The selected 20 features are based on the feature importance of a lightgbm-based model.
|
- The selected 20 features are based on the feature importance of a lightgbm-based model.
|
||||||
- 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
|
||||||
|
- 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)
|
||||||
|
- 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
|
||||||
|
- Signal-based evaluation: IC, ICIR, Rank IC, Rank ICIR
|
||||||
|
- Portfolio-based metrics: Annualized Return, Information Ratio, Max Drawdown
|
||||||
|
|
||||||
|
## Results on CSI500
|
||||||
|
The results on CSI500 is not complete. PR's for models on csi500 are welcome!
|
||||||
|
|
||||||
|
Transfer previous models in CSI300 to CSI500 is quite easy. You can try models with just a few commands below.
|
||||||
|
```
|
||||||
|
cd examples/benchmarks/LightGBM
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# create new config and set the benchmark to csi500
|
||||||
|
cp workflow_config_lightgbm_Alpha158.yaml workflow_config_lightgbm_Alpha158_csi500.yaml
|
||||||
|
sed -i "s/csi300/csi500/g" workflow_config_lightgbm_Alpha158_csi500.yaml
|
||||||
|
sed -i "s/SH000300/SH000905/g" workflow_config_lightgbm_Alpha158_csi500.yaml
|
||||||
|
|
||||||
|
# you can either run the model once
|
||||||
|
qrun workflow_config_lightgbm_Alpha158_csi500.yaml
|
||||||
|
|
||||||
|
# or run it for multiple times automatically and get the summarized results.
|
||||||
|
cd ../../
|
||||||
|
python run_all_model.py run 3 lightgbm Alpha158 csi500 # for models with randomness. please run it for 20 times.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Alpha158 dataset
|
||||||
|
|
||||||
|
| 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 |
|
||||||
|
|
||||||
|
### Alpha360 dataset
|
||||||
|
| Model Name | Dataset | IC | ICIR | Rank IC | Rank ICIR | Annualized Return | Information Ratio | Max Drawdown |
|
||||||
|
|------------|----------|-------------|-------------|-------------|-------------|-------------------|-------------------|--------------|
|
||||||
|
| 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 |
|
||||||
|
|
||||||
|
|
||||||
|
# Contributing
|
||||||
|
|
||||||
|
Your contributions to new models are highly welcome!
|
||||||
|
|
||||||
|
If you want to contribute your new models, you can follow the steps below.
|
||||||
|
1. Create a folder for your model
|
||||||
|
2. The folder contains following items(you can refer to [this example](https://github.com/microsoft/qlib/tree/main/examples/benchmarks/TCTS)).
|
||||||
|
- `requirements.txt`: required dependencies.
|
||||||
|
- `README.md`: a brief introduction to your models
|
||||||
|
- `workflow_config_<model name>_<dataset>.yaml`: a configuration which can read by `qrun`. You are encouraged to run your model in all datasets.
|
||||||
|
3. You can integrate your model as a module [in this folder](https://github.com/microsoft/qlib/tree/main/qlib/contrib/model).
|
||||||
|
4. Please updated your results in the benchmark tables, e.g. [Alpha360](#alpha158-dataset), [Alpha158](#alpha158-dataset)(the values of each metric are the mean and std calculated based on 20 runs with different random seeds, if you don't have enough computational resource, you can ask for help in the PR).
|
||||||
|
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))
|
||||||
|
|
||||||
|
|
||||||
|
# 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).
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
@@ -32,7 +32,7 @@ import abc
|
|||||||
import enum
|
import enum
|
||||||
|
|
||||||
|
|
||||||
# Type defintions
|
# Type definitions
|
||||||
class DataTypes(enum.IntEnum):
|
class DataTypes(enum.IntEnum):
|
||||||
"""Defines numerical types of each column."""
|
"""Defines numerical types of each column."""
|
||||||
|
|
||||||
|
|||||||
@@ -254,9 +254,9 @@ class DistributedHyperparamOptManager(HyperparamOptManager):
|
|||||||
param_ranges: Discrete hyperparameter range for random search.
|
param_ranges: Discrete hyperparameter range for random search.
|
||||||
fixed_params: Fixed model parameters per experiment.
|
fixed_params: Fixed model parameters per experiment.
|
||||||
root_model_folder: Folder to store optimisation artifacts.
|
root_model_folder: Folder to store optimisation artifacts.
|
||||||
worker_number: Worker index definining which set of hyperparameters to
|
worker_number: Worker index defining which set of hyperparameters to
|
||||||
test.
|
test.
|
||||||
search_iterations: Maximum numer of random search iterations.
|
search_iterations: Maximum number of random search iterations.
|
||||||
num_iterations_per_worker: How many iterations are handled per worker.
|
num_iterations_per_worker: How many iterations are handled per worker.
|
||||||
clear_serialised_params: Whether to regenerate hyperparameter
|
clear_serialised_params: Whether to regenerate hyperparameter
|
||||||
combinations.
|
combinations.
|
||||||
@@ -330,7 +330,7 @@ class DistributedHyperparamOptManager(HyperparamOptManager):
|
|||||||
if os.path.exists(self.serialised_ranges_folder):
|
if os.path.exists(self.serialised_ranges_folder):
|
||||||
df = pd.read_csv(self.serialised_ranges_path, index_col=0)
|
df = pd.read_csv(self.serialised_ranges_path, index_col=0)
|
||||||
else:
|
else:
|
||||||
print("Unable to load - regenerating serach ranges instead")
|
print("Unable to load - regenerating search ranges instead")
|
||||||
df = self.update_serialised_hyperparam_df()
|
df = self.update_serialised_hyperparam_df()
|
||||||
|
|
||||||
return df
|
return df
|
||||||
|
|||||||
@@ -342,7 +342,7 @@ class TFTDataCache:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def contains(cls, key):
|
def contains(cls, key):
|
||||||
"""Retuns boolean indicating whether key is present in cache."""
|
"""Returns boolean indicating whether key is present in cache."""
|
||||||
|
|
||||||
return key in cls._data_cache
|
return key in cls._data_cache
|
||||||
|
|
||||||
@@ -1120,10 +1120,10 @@ class TemporalFusionTransformer:
|
|||||||
Args:
|
Args:
|
||||||
df: Input dataframe
|
df: Input dataframe
|
||||||
return_targets: Whether to also return outputs aligned with predictions to
|
return_targets: Whether to also return outputs aligned with predictions to
|
||||||
faciliate evaluation
|
facilitate evaluation
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Input dataframe or tuple of (input dataframe, algined output dataframe).
|
Input dataframe or tuple of (input dataframe, aligned output dataframe).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
data = self._batch_data(df)
|
data = self._batch_data(df)
|
||||||
|
|||||||
@@ -209,7 +209,6 @@ class TFTModel(ModelFT):
|
|||||||
fixed_params = self.data_formatter.get_experiment_params()
|
fixed_params = self.data_formatter.get_experiment_params()
|
||||||
params = self.data_formatter.get_default_model_params()
|
params = self.data_formatter.get_default_model_params()
|
||||||
|
|
||||||
# Wendi: 合并调优的参数和非调优的参数
|
|
||||||
params = {**params, **fixed_params}
|
params = {**params, **fixed_params}
|
||||||
|
|
||||||
if not os.path.exists(self.model_folder):
|
if not os.path.exists(self.model_folder):
|
||||||
@@ -295,7 +294,7 @@ class TFTModel(ModelFT):
|
|||||||
def to_pickle(self, path: Union[Path, str]):
|
def to_pickle(self, path: Union[Path, str]):
|
||||||
"""
|
"""
|
||||||
Tensorflow model can't be dumped directly.
|
Tensorflow model can't be dumped directly.
|
||||||
So the data should be save seperatedly
|
So the data should be save separately
|
||||||
|
|
||||||
**TODO**: Please implement the function to load the files
|
**TODO**: Please implement the function to load the files
|
||||||
|
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ And here are two ways to run the model:
|
|||||||
python example.py --config_file configs/config_alstm.yaml
|
python example.py --config_file configs/config_alstm.yaml
|
||||||
```
|
```
|
||||||
|
|
||||||
Here we trained TRA on a pretrained backbone model. Therefore we run `*_init.yaml` before TRA's scipts.
|
Here we trained TRA on a pretrained backbone model. Therefore we run `*_init.yaml` before TRA's scripts.
|
||||||
|
|
||||||
### Results
|
### Results
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
seaborn
|
seaborn
|
||||||
|
|||||||
@@ -6,8 +6,7 @@ import torch
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from qlib.utils import init_instance_by_config
|
from qlib.data.dataset import DatasetH
|
||||||
from qlib.data.dataset import DatasetH, DataHandler
|
|
||||||
|
|
||||||
|
|
||||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||||
@@ -95,7 +94,7 @@ class MTSDatasetH(DatasetH):
|
|||||||
shuffle=True,
|
shuffle=True,
|
||||||
pin_memory=False,
|
pin_memory=False,
|
||||||
drop_last=False,
|
drop_last=False,
|
||||||
**kwargs
|
**kwargs,
|
||||||
):
|
):
|
||||||
|
|
||||||
assert horizon > 0, "please specify `horizon` to avoid data leakage"
|
assert horizon > 0, "please specify `horizon` to avoid data leakage"
|
||||||
@@ -150,8 +149,15 @@ 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)
|
|
||||||
end_date = fn(slc.stop)
|
if isinstance(slc, slice):
|
||||||
|
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 = fn(start)
|
||||||
|
end_date = 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
|
obj._data = self._data
|
||||||
|
|||||||
@@ -124,13 +124,13 @@ class TRAModel(Model):
|
|||||||
loss = (pred - label).pow(2).mean()
|
loss = (pred - label).pow(2).mean()
|
||||||
|
|
||||||
L = (all_preds.detach() - label[:, None]).pow(2)
|
L = (all_preds.detach() - label[:, None]).pow(2)
|
||||||
L -= L.min(dim=-1, keepdim=True).values # normalize & ensure postive input
|
L -= L.min(dim=-1, keepdim=True).values # normalize & ensure positive input
|
||||||
|
|
||||||
data_set.assign_data(index, L) # save loss to memory
|
data_set.assign_data(index, L) # save loss to memory
|
||||||
|
|
||||||
if prob is not None:
|
if prob is not None:
|
||||||
P = sinkhorn(-L, epsilon=0.01) # sample assignment matrix
|
P = sinkhorn(-L, epsilon=0.01) # sample assignment matrix
|
||||||
lamb = self.lamb * (self.rho ** self.global_step)
|
lamb = self.lamb * (self.rho**self.global_step)
|
||||||
reg = prob.log().mul(P).sum(dim=-1).mean()
|
reg = prob.log().mul(P).sum(dim=-1).mean()
|
||||||
loss = loss - lamb * reg
|
loss = loss - lamb * reg
|
||||||
|
|
||||||
@@ -165,7 +165,7 @@ class TRAModel(Model):
|
|||||||
|
|
||||||
L = (all_preds - label[:, None]).pow(2)
|
L = (all_preds - label[:, None]).pow(2)
|
||||||
|
|
||||||
L -= L.min(dim=-1, keepdim=True).values # normalize & ensure postive input
|
L -= L.min(dim=-1, keepdim=True).values # normalize & ensure positive input
|
||||||
|
|
||||||
data_set.assign_data(index, L) # save loss to memory
|
data_set.assign_data(index, L) # save loss to memory
|
||||||
|
|
||||||
@@ -484,7 +484,7 @@ class TRA(nn.Module):
|
|||||||
|
|
||||||
"""Temporal Routing Adaptor (TRA)
|
"""Temporal Routing Adaptor (TRA)
|
||||||
|
|
||||||
TRA takes historical prediction erros & latent representation as inputs,
|
TRA takes historical prediction errors & latent representation as inputs,
|
||||||
then routes the input sample to a specific predictor for training & inference.
|
then routes the input sample to a specific predictor for training & inference.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -547,7 +547,7 @@ def evaluate(pred):
|
|||||||
score = pred.score
|
score = pred.score
|
||||||
label = pred.label
|
label = pred.label
|
||||||
diff = score - label
|
diff = score - label
|
||||||
MSE = (diff ** 2).mean()
|
MSE = (diff**2).mean()
|
||||||
MAE = (diff.abs()).mean()
|
MAE = (diff.abs()).mean()
|
||||||
IC = score.corr(label)
|
IC = score.corr(label)
|
||||||
return {"MSE": MSE, "MAE": MAE, "IC": IC}
|
return {"MSE": MSE, "MAE": MAE, "IC": IC}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
scikit_learn==0.23.2
|
scikit_learn==0.23.2
|
||||||
torch==1.7.0
|
torch==1.7.0
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
torch==1.2.0
|
torch==1.2.0
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
numpy==1.17.4
|
numpy==1.21.0
|
||||||
pandas==1.1.2
|
pandas==1.1.2
|
||||||
xgboost==1.2.1
|
xgboost==1.2.1
|
||||||
35
examples/benchmarks_dynamic/DDG-DA/README.md
Normal file
35
examples/benchmarks_dynamic/DDG-DA/README.md
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# Introduction
|
||||||
|
This is the implementation of `DDG-DA` based on `Meta Controller` component provided by `Qlib`.
|
||||||
|
|
||||||
|
Please refer to the paper for more details: *DDG-DA: Data Distribution Generation for Predictable Concept Drift Adaptation* [[arXiv](https://arxiv.org/abs/2201.04038)]
|
||||||
|
|
||||||
|
|
||||||
|
# Background
|
||||||
|
In many real-world scenarios, we often deal with streaming data that is sequentially collected over time. Due to the non-stationary nature of the environment, the streaming data distribution may change in unpredictable ways, which is known as concept drift. To handle concept drift, previous methods first detect when/where the concept drift happens and then adapt models to fit the distribution of the latest data. However, there are still many cases that some underlying factors of environment evolution are predictable, making it possible to model the future concept drift trend of the streaming data, while such cases are not fully explored in previous work.
|
||||||
|
|
||||||
|
Therefore, we propose a novel method `DDG-DA`, that can effectively forecast the evolution of data distribution and improve the performance of models. Specifically, we first train a predictor to estimate the future data distribution, then leverage it to generate training samples, and finally train models on the generated data.
|
||||||
|
|
||||||
|
# Dataset
|
||||||
|
The data in the paper are private. So we conduct experiments on Qlib's public dataset.
|
||||||
|
Though the dataset is different, the conclusion remains the same. By applying `DDG-DA`, users can see rising trends at the test phase both in the proxy models' ICs and the performances of the forecasting models.
|
||||||
|
|
||||||
|
# Run the Code
|
||||||
|
Users can try `DDG-DA` by running the following command:
|
||||||
|
```bash
|
||||||
|
python workflow.py run_all
|
||||||
|
```
|
||||||
|
|
||||||
|
The default forecasting models are `Linear`. Users can choose other forecasting models by changing the `forecast_model` parameter when `DDG-DA` initializes. For example, users can try `LightGBM` forecasting models by running the following command:
|
||||||
|
```bash
|
||||||
|
python workflow.py --forecast_model="gbdt" run_all
|
||||||
|
```
|
||||||
|
|
||||||
|
# Results
|
||||||
|
The results of related methods in Qlib's public dataset can be found [here](../)
|
||||||
|
|
||||||
|
# Requirements
|
||||||
|
Here are the minimal hardware requirements to run the ``workflow.py`` of DDG-DA.
|
||||||
|
* Memory: 45G
|
||||||
|
* Disk: 4G
|
||||||
|
|
||||||
|
Pytorch with CPU & RAM will be enough for this example.
|
||||||
1
examples/benchmarks_dynamic/DDG-DA/requirements.txt
Normal file
1
examples/benchmarks_dynamic/DDG-DA/requirements.txt
Normal file
@@ -0,0 +1 @@
|
|||||||
|
torch==1.10.0
|
||||||
259
examples/benchmarks_dynamic/DDG-DA/workflow.py
Normal file
259
examples/benchmarks_dynamic/DDG-DA/workflow.py
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
# Copyright (c) Microsoft Corporation.
|
||||||
|
# Licensed under the MIT License.
|
||||||
|
from pathlib import Path
|
||||||
|
from qlib.model.meta.task import MetaTask
|
||||||
|
from qlib.contrib.meta.data_selection.model import MetaModelDS
|
||||||
|
from qlib.contrib.meta.data_selection.dataset import InternalData, MetaDatasetDS
|
||||||
|
from qlib.data.dataset.handler import DataHandlerLP
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import fire
|
||||||
|
import sys
|
||||||
|
import pickle
|
||||||
|
from qlib import auto_init
|
||||||
|
from qlib.model.trainer import TrainerR
|
||||||
|
from qlib.utils import init_instance_by_config
|
||||||
|
from qlib.workflow import R
|
||||||
|
from qlib.tests.data import GetData
|
||||||
|
|
||||||
|
DIRNAME = Path(__file__).absolute().resolve().parent
|
||||||
|
sys.path.append(str(DIRNAME.parent / "baseline"))
|
||||||
|
from rolling_benchmark import RollingBenchmark # NOTE: sys.path is changed for import RollingBenchmark
|
||||||
|
|
||||||
|
|
||||||
|
class DDGDA:
|
||||||
|
"""
|
||||||
|
please run `python workflow.py run_all` to run the full workflow of the experiment
|
||||||
|
|
||||||
|
**NOTE**
|
||||||
|
before running the example, please clean your previous results with following command
|
||||||
|
- `rm -r mlruns`
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, sim_task_model="linear", forecast_model="linear"):
|
||||||
|
self.step = 20
|
||||||
|
# NOTE:
|
||||||
|
# the horizon must match the meaning in the base task template
|
||||||
|
self.horizon = 20
|
||||||
|
self.meta_exp_name = "DDG-DA"
|
||||||
|
self.sim_task_model = sim_task_model # The model to capture the distribution of data.
|
||||||
|
self.forecast_model = forecast_model # downstream forecasting models' type
|
||||||
|
|
||||||
|
def get_feature_importance(self):
|
||||||
|
# this must be lightGBM, because it needs to get the feature importance
|
||||||
|
rb = RollingBenchmark(model_type="gbdt")
|
||||||
|
task = rb.basic_task()
|
||||||
|
|
||||||
|
with R.start(experiment_name="feature_importance"):
|
||||||
|
model = init_instance_by_config(task["model"])
|
||||||
|
dataset = init_instance_by_config(task["dataset"])
|
||||||
|
model.fit(dataset)
|
||||||
|
|
||||||
|
fi = model.get_feature_importance()
|
||||||
|
|
||||||
|
# Because the model use numpy instead of dataframe for training lightgbm
|
||||||
|
# So the we must use following extra steps to get the right feature importance
|
||||||
|
df = dataset.prepare(segments=slice(None), col_set="feature", data_key=DataHandlerLP.DK_R)
|
||||||
|
cols = df.columns
|
||||||
|
fi_named = {cols[int(k.split("_")[1])]: imp for k, imp in fi.to_dict().items()}
|
||||||
|
|
||||||
|
return pd.Series(fi_named)
|
||||||
|
|
||||||
|
def dump_data_for_proxy_model(self):
|
||||||
|
"""
|
||||||
|
Dump data for training meta model.
|
||||||
|
The meta model will be trained upon the proxy forecasting model.
|
||||||
|
This dataset is for the proxy forecasting model.
|
||||||
|
"""
|
||||||
|
topk = 30
|
||||||
|
fi = self.get_feature_importance()
|
||||||
|
col_selected = fi.nlargest(topk)
|
||||||
|
|
||||||
|
rb = RollingBenchmark(model_type=self.sim_task_model)
|
||||||
|
task = rb.basic_task()
|
||||||
|
dataset = init_instance_by_config(task["dataset"])
|
||||||
|
prep_ds = dataset.prepare(slice(None), col_set=["feature", "label"], data_key=DataHandlerLP.DK_L)
|
||||||
|
|
||||||
|
feature_df = prep_ds["feature"]
|
||||||
|
label_df = prep_ds["label"]
|
||||||
|
|
||||||
|
feature_selected = feature_df.loc[:, col_selected.index]
|
||||||
|
|
||||||
|
feature_selected = feature_selected.groupby("datetime").apply(lambda df: (df - df.mean()).div(df.std()))
|
||||||
|
feature_selected = feature_selected.fillna(0.0)
|
||||||
|
|
||||||
|
df_all = {
|
||||||
|
"label": label_df.reindex(feature_selected.index),
|
||||||
|
"feature": feature_selected,
|
||||||
|
}
|
||||||
|
df_all = pd.concat(df_all, axis=1)
|
||||||
|
df_all.to_pickle(DIRNAME / "fea_label_df.pkl")
|
||||||
|
|
||||||
|
# dump data in handler format for aligning the interface
|
||||||
|
handler = DataHandlerLP(
|
||||||
|
data_loader={
|
||||||
|
"class": "qlib.data.dataset.loader.StaticDataLoader",
|
||||||
|
"kwargs": {"config": DIRNAME / "fea_label_df.pkl"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
handler.to_pickle(DIRNAME / "handler_proxy.pkl", dump_all=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _internal_data_path(self):
|
||||||
|
return DIRNAME / f"internal_data_s{self.step}.pkl"
|
||||||
|
|
||||||
|
def dump_meta_ipt(self):
|
||||||
|
"""
|
||||||
|
Dump data for training meta model.
|
||||||
|
This function will dump the input data for meta model
|
||||||
|
"""
|
||||||
|
# According to the experiments, the choice of the model type is very important for achieving good results
|
||||||
|
rb = RollingBenchmark(model_type=self.sim_task_model)
|
||||||
|
sim_task = rb.basic_task()
|
||||||
|
|
||||||
|
if self.sim_task_model == "gbdt":
|
||||||
|
sim_task["model"].setdefault("kwargs", {}).update({"early_stopping_rounds": None, "num_boost_round": 150})
|
||||||
|
|
||||||
|
exp_name_sim = f"data_sim_s{self.step}"
|
||||||
|
|
||||||
|
internal_data = InternalData(sim_task, self.step, exp_name=exp_name_sim)
|
||||||
|
internal_data.setup(trainer=TrainerR)
|
||||||
|
|
||||||
|
with self._internal_data_path.open("wb") as f:
|
||||||
|
pickle.dump(internal_data, f)
|
||||||
|
|
||||||
|
def train_meta_model(self):
|
||||||
|
"""
|
||||||
|
training a meta model based on a simplified linear proxy model;
|
||||||
|
"""
|
||||||
|
|
||||||
|
# 1) leverage the simplified proxy forecasting model to train meta model.
|
||||||
|
# - Only the dataset part is important, in current version of meta model will integrate the
|
||||||
|
rb = RollingBenchmark(model_type=self.sim_task_model)
|
||||||
|
sim_task = rb.basic_task()
|
||||||
|
proxy_forecast_model_task = {
|
||||||
|
# "model": "qlib.contrib.model.linear.LinearModel",
|
||||||
|
"dataset": {
|
||||||
|
"class": "qlib.data.dataset.DatasetH",
|
||||||
|
"kwargs": {
|
||||||
|
"handler": f"file://{(DIRNAME / 'handler_proxy.pkl').absolute()}",
|
||||||
|
"segments": {
|
||||||
|
"train": ("2008-01-01", "2010-12-31"),
|
||||||
|
"test": ("2011-01-01", sim_task["dataset"]["kwargs"]["segments"]["test"][1]),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
# "record": ["qlib.workflow.record_temp.SignalRecord"]
|
||||||
|
}
|
||||||
|
# the proxy_forecast_model_task will be used to create meta tasks.
|
||||||
|
# The test date of first task will be 2011-01-01. Each test segment will be about 20days
|
||||||
|
# The tasks include all training tasks and test tasks.
|
||||||
|
|
||||||
|
# 2) preparing meta dataset
|
||||||
|
kwargs = dict(
|
||||||
|
task_tpl=proxy_forecast_model_task,
|
||||||
|
step=self.step,
|
||||||
|
segments=0.62, # keep test period consistent with the dataset yaml
|
||||||
|
trunc_days=1 + self.horizon,
|
||||||
|
hist_step_n=30,
|
||||||
|
fill_method="max",
|
||||||
|
rolling_ext_days=0,
|
||||||
|
)
|
||||||
|
# NOTE:
|
||||||
|
# the input of meta model (internal data) are shared between proxy model and final forecasting model
|
||||||
|
# but their task test segment are not aligned! It worked in my previous experiment.
|
||||||
|
# So the misalignment will not affect the effectiveness of the method.
|
||||||
|
with self._internal_data_path.open("rb") as f:
|
||||||
|
internal_data = pickle.load(f)
|
||||||
|
md = MetaDatasetDS(exp_name=internal_data, **kwargs)
|
||||||
|
|
||||||
|
# 3) train and logging meta model
|
||||||
|
with R.start(experiment_name=self.meta_exp_name):
|
||||||
|
R.log_params(**kwargs)
|
||||||
|
mm = MetaModelDS(step=self.step, hist_step_n=kwargs["hist_step_n"], lr=0.001, max_epoch=200, seed=43)
|
||||||
|
mm.fit(md)
|
||||||
|
R.save_objects(model=mm)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _task_path(self):
|
||||||
|
return DIRNAME / f"tasks_s{self.step}.pkl"
|
||||||
|
|
||||||
|
def meta_inference(self):
|
||||||
|
"""
|
||||||
|
Leverage meta-model for inference:
|
||||||
|
- Given
|
||||||
|
- baseline tasks
|
||||||
|
- input for meta model(internal data)
|
||||||
|
- meta model (its learnt knowledge on proxy forecasting model is expected to transfer to normal forecasting model)
|
||||||
|
"""
|
||||||
|
# 1) get meta model
|
||||||
|
exp = R.get_exp(experiment_name=self.meta_exp_name)
|
||||||
|
rec = exp.list_recorders(rtype=exp.RT_L)[0]
|
||||||
|
meta_model: MetaModelDS = rec.load_object("model")
|
||||||
|
|
||||||
|
# 2)
|
||||||
|
# we are transfer to knowledge of meta model to final forecasting tasks.
|
||||||
|
# Create MetaTaskDataset for the final forecasting tasks
|
||||||
|
# Aligning the setting of it to the MetaTaskDataset when training Meta model is necessary
|
||||||
|
|
||||||
|
# 2.1) get previous config
|
||||||
|
param = rec.list_params()
|
||||||
|
trunc_days = int(param["trunc_days"])
|
||||||
|
step = int(param["step"])
|
||||||
|
hist_step_n = int(param["hist_step_n"])
|
||||||
|
fill_method = param.get("fill_method", "max")
|
||||||
|
|
||||||
|
rb = RollingBenchmark(model_type=self.forecast_model)
|
||||||
|
task_l = rb.create_rolling_tasks()
|
||||||
|
|
||||||
|
# 2.2) create meta dataset for final dataset
|
||||||
|
kwargs = dict(
|
||||||
|
task_tpl=task_l,
|
||||||
|
step=step,
|
||||||
|
segments=0.0, # all the tasks are for testing
|
||||||
|
trunc_days=trunc_days,
|
||||||
|
hist_step_n=hist_step_n,
|
||||||
|
fill_method=fill_method,
|
||||||
|
task_mode=MetaTask.PROC_MODE_TRANSFER,
|
||||||
|
)
|
||||||
|
|
||||||
|
with self._internal_data_path.open("rb") as f:
|
||||||
|
internal_data = pickle.load(f)
|
||||||
|
mds = MetaDatasetDS(exp_name=internal_data, **kwargs)
|
||||||
|
|
||||||
|
# 3) meta model make inference and get new qlib task
|
||||||
|
new_tasks = meta_model.inference(mds)
|
||||||
|
with self._task_path.open("wb") as f:
|
||||||
|
pickle.dump(new_tasks, f)
|
||||||
|
|
||||||
|
def train_and_eval_tasks(self):
|
||||||
|
"""
|
||||||
|
Training the tasks generated by meta model
|
||||||
|
Then evaluate it
|
||||||
|
"""
|
||||||
|
with self._task_path.open("rb") as f:
|
||||||
|
tasks = pickle.load(f)
|
||||||
|
rb = RollingBenchmark(rolling_exp="rolling_ds", model_type=self.forecast_model)
|
||||||
|
rb.train_rolling_tasks(tasks)
|
||||||
|
rb.ens_rolling()
|
||||||
|
rb.update_rolling_rec()
|
||||||
|
|
||||||
|
def run_all(self):
|
||||||
|
# 1) file: handler_proxy.pkl
|
||||||
|
self.dump_data_for_proxy_model()
|
||||||
|
# 2)
|
||||||
|
# file: internal_data_s20.pkl
|
||||||
|
# mlflow: data_sim_s20, models for calculating meta_ipt
|
||||||
|
self.dump_meta_ipt()
|
||||||
|
# 3) meta model will be stored in `DDG-DA`
|
||||||
|
self.train_meta_model()
|
||||||
|
# 4) new_tasks are saved in "tasks_s20.pkl" (reweighter is added)
|
||||||
|
self.meta_inference()
|
||||||
|
# 5) load the saved tasks and train model
|
||||||
|
self.train_and_eval_tasks()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
GetData().qlib_data(exists_skip=True)
|
||||||
|
auto_init()
|
||||||
|
fire.Fire(DDGDA)
|
||||||
18
examples/benchmarks_dynamic/README.md
Normal file
18
examples/benchmarks_dynamic/README.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# Introduction
|
||||||
|
Due to the non-stationary nature of the environment of the financial market, the data distribution may change in different periods, which makes the performance of models build on training data decays in the future test data.
|
||||||
|
So adapting the forecasting models/strategies to market dynamics is very important to the model/strategies' performance.
|
||||||
|
|
||||||
|
The table below shows the performances of different solutions on different forecasting models.
|
||||||
|
|
||||||
|
## Alpha158 dataset
|
||||||
|
|
||||||
|
| Model Name | Dataset | IC | ICIR | Rank IC | Rank ICIR | Annualized Return | Information Ratio | Max Drawdown |
|
||||||
|
|------------------|---------|----|------|---------|-----------|-------------------|-------------------|--------------|
|
||||||
|
| RR[Linear] |Alpha158 |0.088|0.570|0.102 |0.622 |0.077 |1.175 |-0.086 |
|
||||||
|
| DDG-DA[Linear] |Alpha158 |0.093|0.622|0.106 |0.670 |0.085 |1.213 |-0.093 |
|
||||||
|
| RR[LightGBM] |Alpha158 |0.079|0.566|0.088 |0.592 |0.075 |1.226 |-0.096 |
|
||||||
|
| DDG-DA[LightGBM] |Alpha158 |0.084|0.639|0.093 |0.664 |0.099 |1.442 |-0.071 |
|
||||||
|
|
||||||
|
- The label horizon of the `Alpha158` dataset is set to 20.
|
||||||
|
- The rolling time intervals are set to 20 trading days.
|
||||||
|
- The test rolling periods are from January 2017 to August 2020.
|
||||||
15
examples/benchmarks_dynamic/baseline/README.md
Normal file
15
examples/benchmarks_dynamic/baseline/README.md
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
# Introduction
|
||||||
|
|
||||||
|
This is the framework of periodically Rolling Retrain (RR) forecasting models. RR adapts to market dynamics by utilizing the up-to-date data periodically.
|
||||||
|
|
||||||
|
## Run the Code
|
||||||
|
Users can try RR by running the following command:
|
||||||
|
```bash
|
||||||
|
python rolling_benchmark.py run_all
|
||||||
|
```
|
||||||
|
|
||||||
|
The default forecasting models are `Linear`. Users can choose other forecasting models by changing the `model_type` parameter.
|
||||||
|
For example, users can try `LightGBM` forecasting models by running the following command:
|
||||||
|
```bash
|
||||||
|
python rolling_benchmark.py --model_type="gbdt" run_all
|
||||||
|
```
|
||||||
114
examples/benchmarks_dynamic/baseline/rolling_benchmark.py
Normal file
114
examples/benchmarks_dynamic/baseline/rolling_benchmark.py
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
# Copyright (c) Microsoft Corporation.
|
||||||
|
# Licensed under the MIT License.
|
||||||
|
from qlib.model.ens.ensemble import RollingEnsemble
|
||||||
|
from qlib.utils import init_instance_by_config
|
||||||
|
import fire
|
||||||
|
import yaml
|
||||||
|
from qlib import auto_init
|
||||||
|
from pathlib import Path
|
||||||
|
from tqdm.auto import tqdm
|
||||||
|
from qlib.model.trainer import TrainerR
|
||||||
|
from qlib.workflow import R
|
||||||
|
from qlib.tests.data import GetData
|
||||||
|
|
||||||
|
DIRNAME = Path(__file__).absolute().resolve().parent
|
||||||
|
from qlib.workflow.task.gen import task_generator, RollingGen
|
||||||
|
from qlib.workflow.task.collect import RecorderCollector
|
||||||
|
from qlib.workflow.record_temp import PortAnaRecord, SigAnaRecord
|
||||||
|
|
||||||
|
|
||||||
|
class RollingBenchmark:
|
||||||
|
"""
|
||||||
|
**NOTE**
|
||||||
|
before running the example, please clean your previous results with following command
|
||||||
|
- `rm -r mlruns`
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, rolling_exp="rolling_models", model_type="linear") -> None:
|
||||||
|
self.step = 20
|
||||||
|
self.horizon = 20
|
||||||
|
self.rolling_exp = rolling_exp
|
||||||
|
self.model_type = model_type
|
||||||
|
|
||||||
|
def basic_task(self):
|
||||||
|
"""For fast training rolling"""
|
||||||
|
if self.model_type == "gbdt":
|
||||||
|
conf_path = DIRNAME.parent.parent / "benchmarks" / "LightGBM" / "workflow_config_lightgbm_Alpha158.yaml"
|
||||||
|
# dump the processed data on to disk for later loading to speed up the processing
|
||||||
|
h_path = DIRNAME / "lightgbm_alpha158_handler_horizon{}.pkl".format(self.horizon)
|
||||||
|
elif self.model_type == "linear":
|
||||||
|
conf_path = DIRNAME.parent.parent / "benchmarks" / "Linear" / "workflow_config_linear_Alpha158.yaml"
|
||||||
|
h_path = DIRNAME / "linear_alpha158_handler_horizon{}.pkl".format(self.horizon)
|
||||||
|
else:
|
||||||
|
raise AssertionError("Model type is not supported!")
|
||||||
|
with conf_path.open("r") as f:
|
||||||
|
conf = yaml.safe_load(f)
|
||||||
|
|
||||||
|
# modify dataset horizon
|
||||||
|
conf["task"]["dataset"]["kwargs"]["handler"]["kwargs"]["label"] = [
|
||||||
|
"Ref($close, -{}) / Ref($close, -1) - 1".format(self.horizon + 1)
|
||||||
|
]
|
||||||
|
|
||||||
|
task = conf["task"]
|
||||||
|
|
||||||
|
if not h_path.exists():
|
||||||
|
h_conf = task["dataset"]["kwargs"]["handler"]
|
||||||
|
h = init_instance_by_config(h_conf)
|
||||||
|
h.to_pickle(h_path, dump_all=True)
|
||||||
|
|
||||||
|
task["dataset"]["kwargs"]["handler"] = f"file://{h_path}"
|
||||||
|
task["record"] = ["qlib.workflow.record_temp.SignalRecord"]
|
||||||
|
return task
|
||||||
|
|
||||||
|
def create_rolling_tasks(self):
|
||||||
|
task = self.basic_task()
|
||||||
|
task_l = task_generator(
|
||||||
|
task, RollingGen(step=self.step, trunc_days=self.horizon + 1)
|
||||||
|
) # the last two days should be truncated to avoid information leakage
|
||||||
|
return task_l
|
||||||
|
|
||||||
|
def train_rolling_tasks(self, task_l=None):
|
||||||
|
if task_l is None:
|
||||||
|
task_l = self.create_rolling_tasks()
|
||||||
|
trainer = TrainerR(experiment_name=self.rolling_exp)
|
||||||
|
trainer(task_l)
|
||||||
|
|
||||||
|
COMB_EXP = "rolling"
|
||||||
|
|
||||||
|
def ens_rolling(self):
|
||||||
|
rc = RecorderCollector(
|
||||||
|
experiment=self.rolling_exp,
|
||||||
|
artifacts_key=["pred", "label"],
|
||||||
|
process_list=[RollingEnsemble()],
|
||||||
|
# rec_key_func=lambda rec: (self.COMB_EXP, rec.info["id"]),
|
||||||
|
artifacts_path={"pred": "pred.pkl", "label": "label.pkl"},
|
||||||
|
)
|
||||||
|
res = rc()
|
||||||
|
with R.start(experiment_name=self.COMB_EXP):
|
||||||
|
R.log_params(exp_name=self.rolling_exp)
|
||||||
|
R.save_objects(**{"pred.pkl": res["pred"], "label.pkl": res["label"]})
|
||||||
|
|
||||||
|
def update_rolling_rec(self):
|
||||||
|
"""
|
||||||
|
Evaluate the combined rolling results
|
||||||
|
"""
|
||||||
|
for rid, rec in R.list_recorders(experiment_name=self.COMB_EXP).items():
|
||||||
|
for rt_cls in SigAnaRecord, PortAnaRecord:
|
||||||
|
rt = rt_cls(recorder=rec, skip_existing=True)
|
||||||
|
rt.generate()
|
||||||
|
print(f"Your evaluation results can be found in the experiment named `{self.COMB_EXP}`.")
|
||||||
|
|
||||||
|
def run_all(self):
|
||||||
|
# the results will be save in mlruns.
|
||||||
|
# 1) each rolling task is saved in rolling_models
|
||||||
|
self.train_rolling_tasks()
|
||||||
|
# 2) combined rolling tasks and evaluation results are saved in rolling
|
||||||
|
self.ens_rolling()
|
||||||
|
self.update_rolling_rec()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
GetData().qlib_data(exists_skip=True)
|
||||||
|
auto_init()
|
||||||
|
fire.Fire(RollingBenchmark)
|
||||||
@@ -1,15 +1,20 @@
|
|||||||
# High-Frequency Dataset
|
# Introduction
|
||||||
|
This folder contains 2 examples
|
||||||
|
- A high-frequency dataset example
|
||||||
|
- An example of predicting the price trend in high-frequency data
|
||||||
|
|
||||||
|
## High-Frequency Dataset
|
||||||
|
|
||||||
This dataset is an example for RL high frequency trading.
|
This dataset is an example for RL high frequency trading.
|
||||||
|
|
||||||
## Get High-Frequency Data
|
### Get High-Frequency Data
|
||||||
|
|
||||||
Get high-frequency data by running the following command:
|
Get high-frequency data by running the following command:
|
||||||
```bash
|
```bash
|
||||||
python workflow.py get_data
|
python workflow.py get_data
|
||||||
```
|
```
|
||||||
|
|
||||||
## Dump & Reload & Reinitialize the Dataset
|
### Dump & Reload & Reinitialize the Dataset
|
||||||
|
|
||||||
|
|
||||||
The High-Frequency Dataset is implemented as `qlib.data.dataset.DatasetH` in the `workflow.py`. `DatatsetH` is the subclass of [`qlib.utils.serial.Serializable`](https://qlib.readthedocs.io/en/latest/advanced/serial.html), whose state can be dumped in or loaded from disk in `pickle` format.
|
The High-Frequency Dataset is implemented as `qlib.data.dataset.DatasetH` in the `workflow.py`. `DatatsetH` is the subclass of [`qlib.utils.serial.Serializable`](https://qlib.readthedocs.io/en/latest/advanced/serial.html), whose state can be dumped in or loaded from disk in `pickle` format.
|
||||||
@@ -27,9 +32,9 @@ Run the example by running the following command:
|
|||||||
python workflow.py dump_and_load_dataset
|
python workflow.py dump_and_load_dataset
|
||||||
```
|
```
|
||||||
|
|
||||||
## Benchmarks Performance
|
## Benchmarks Performance (predicting the price trend in high-frequency data)
|
||||||
### Signal Test
|
|
||||||
Here are the results of signal test for benchmark models. We will keep updating benchmark models in future.
|
Here are the results of models for predicting the price trend in high-frequency data. We will keep updating benchmark models in future.
|
||||||
|
|
||||||
| Model Name | Dataset | IC | ICIR | Rank IC | Rank ICIR | Long precision| Short Precision | Long-Short Average Return | Long-Short Average Sharpe |
|
| Model Name | Dataset | IC | ICIR | Rank IC | Rank ICIR | Long precision| Short Precision | Long-Short Average Return | Long-Short Average Sharpe |
|
||||||
|---|---|---|---|---|---|---|---|---|---|
|
|---|---|---|---|---|---|---|---|---|---|
|
||||||
|
|||||||
@@ -150,7 +150,7 @@ class Cut(ElemOperator):
|
|||||||
self.l = l
|
self.l = l
|
||||||
self.r = r
|
self.r = r
|
||||||
if (self.l is not None and self.l <= 0) or (self.r is not None and self.r >= 0):
|
if (self.l is not None and self.l <= 0) or (self.r is not None and self.r >= 0):
|
||||||
raise ValueError("Cut operator l shoud > 0 and r should < 0")
|
raise ValueError("Cut operator l should > 0 and r should < 0")
|
||||||
|
|
||||||
super(Cut, self).__init__(feature)
|
super(Cut, self).__init__(feature)
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
from qlib.constant import EPS
|
||||||
from qlib.data.dataset.processor import Processor
|
from qlib.data.dataset.processor import Processor
|
||||||
from qlib.data.dataset.utils import fetch_df_by_index
|
from qlib.data.dataset.utils import fetch_df_by_index
|
||||||
|
|
||||||
@@ -27,7 +28,7 @@ class HighFreqNorm(Processor):
|
|||||||
part_values = np.log1p(part_values)
|
part_values = np.log1p(part_values)
|
||||||
self.feature_med[name] = np.nanmedian(part_values)
|
self.feature_med[name] = np.nanmedian(part_values)
|
||||||
part_values = part_values - self.feature_med[name]
|
part_values = part_values - self.feature_med[name]
|
||||||
self.feature_std[name] = np.nanmedian(np.absolute(part_values)) * 1.4826 + 1e-12
|
self.feature_std[name] = np.nanmedian(np.absolute(part_values)) * 1.4826 + EPS
|
||||||
part_values = part_values / self.feature_std[name]
|
part_values = part_values / self.feature_std[name]
|
||||||
self.feature_vmax[name] = np.nanmax(part_values)
|
self.feature_vmax[name] = np.nanmax(part_values)
|
||||||
self.feature_vmin[name] = np.nanmin(part_values)
|
self.feature_vmin[name] = np.nanmin(part_values)
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import fire
|
|||||||
|
|
||||||
import qlib
|
import qlib
|
||||||
import pickle
|
import pickle
|
||||||
from qlib.config import REG_CN, HIGH_FREQ_CONFIG
|
from qlib.constant import REG_CN
|
||||||
|
from qlib.config import HIGH_FREQ_CONFIG
|
||||||
|
|
||||||
from qlib.utils import init_instance_by_config
|
from qlib.utils import init_instance_by_config
|
||||||
from qlib.data.dataset.handler import DataHandlerLP
|
from qlib.data.dataset.handler import DataHandlerLP
|
||||||
@@ -82,7 +83,7 @@ class HighfreqWorkflow:
|
|||||||
|
|
||||||
def _init_qlib(self):
|
def _init_qlib(self):
|
||||||
"""initialize qlib"""
|
"""initialize qlib"""
|
||||||
# use yahoo_cn_1min data
|
# use cn_data_1min data
|
||||||
QLIB_INIT_CONFIG = {**HIGH_FREQ_CONFIG, **self.SPEC_CONF}
|
QLIB_INIT_CONFIG = {**HIGH_FREQ_CONFIG, **self.SPEC_CONF}
|
||||||
provider_uri = QLIB_INIT_CONFIG.get("provider_uri")
|
provider_uri = QLIB_INIT_CONFIG.get("provider_uri")
|
||||||
GetData().qlib_data(target_dir=provider_uri, interval="1min", region=REG_CN, exists_skip=True)
|
GetData().qlib_data(target_dir=provider_uri, interval="1min", region=REG_CN, exists_skip=True)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import qlib
|
import qlib
|
||||||
import optuna
|
import optuna
|
||||||
from qlib.config import REG_CN
|
from qlib.constant import REG_CN
|
||||||
from qlib.utils import init_instance_by_config
|
from qlib.utils import init_instance_by_config
|
||||||
from qlib.tests.config import CSI300_DATASET_CONFIG
|
from qlib.tests.config import CSI300_DATASET_CONFIG
|
||||||
from qlib.tests.data import GetData
|
from qlib.tests.data import GetData
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user