[機械学習]PythonのQlibで株価予測

2021年11月3日水曜日

Artificial Intelligence

本記事では、An AI-oriented Quantitative Investment PlatformであるQlibを使って株価の予測手順を紹介します。

アイキャッチ

Qlibとは

QlibはMicrosoftが開発するAI指向定量的投資プラットフォーム(AI-oriented quantitative investment platform)です。

このプラットフォームには、データ処理モデルのトレーニングモデルの評価等、機械学習パイプラインに必要な処理は全て含まれています。
そしてアルファシーク、リスクモデリング、ポートフォリオ最適化、注文執行など、定量的投資全体をカバーしています。

ざっくりと言えば、株価予測に関する汎用的な処理のほとんどを有するAIプラットフォームと言えそうです。

Qlibの導入手順

セットアップ

それでは早速、開発環境にQlibをセットアップしていきます。
動作確認は下記の環境で行っています。

OS: Ubuntu 18.04.3 LTS
GPU: GeForce GTX 1080

なお、このデモはPythonで実装しています。
Pythonの実装に不安がある方、Pythonを使った機械学習について詳しく勉強したい方は、以下の書籍やオンライン講座などがおすすめです。

それでは、Qlibをインストールしていきます。他の機械学習環境に影響を与えないためにMinicondaの仮想環境上に構築していきます。Minicondaのインストール手順は公式ドキュメントをご参照ください。

# python version 3.8のconda環境を作成
$ conda create -n QLIB python=3.8

# 作成した環境をアクティベート
$ conda activate QLIB
$ cd QLIB

# Proxy配下の場合はインストール前に下記を設定
$ export http_proxy="http://"username":"password"@proxy:port"
$ export https_proxy="http://"username":"password"@proxy:port"

# 関連するライブラリをインストール
$ pip3 install numpy
$ pip3 install --upgrade  cython

# gitからコードをclone
$ git clone https://github.com/microsoft/qlib.git && cd qlib
$ python setup.py install

# error: pyparsing 3.0.4 is installed but pyparsing<3,>=2.0.2 is required by {'packaging'}
# 上記が出た場合は以下をインストール
$ pip3 install tomli
$ pip3 install pyparsing=="2.4.7"

# https://pytorch.org/get-started/previous-versions/ でバージョン確認
$ conda install pytorch==1.7.1 torchvision==0.8.2 torchaudio==0.7.2 cudatoolkit=10.1 -c pytorch

以上で、セットアップは完了です。

データ準備(Data Preparation)

次に、データを準備していきます。
なお--regioncn,us,inです。
それ以外のデータを使う場合は、自ら用意する必要があります。

$ cd qlib
$ python scripts/get_data.py qlib_data --target_dir "データ保存先ディレクトリ" --region cn
$ 例) python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn

# 指定日のデータを取得する場合
$ cd scripts/data_collector/yahoo
$ pip3 install -r requirements.txt
$ cd ../../../
$ python collector.py update_data_to_bin --qlib_data_1d_dir "データ保存先ディレクトリ" --trading_date "取得開始日" --end_date "取得終了日" --region cn
$ 例) python scripts/data_collector/yahoo/collector.py download_data --source_dir ~/.qlib/qlib_data/cn_data --start 2020-01-01 --end 2021-10-31 --delay 1 --interval 1d --region cn

このうち最後のyahoo/collector.pyは取得先のネットワークがあまり安定していないようなので
私見では非推奨です。(出典: https://github.com/microsoft/qlib/issues/613)

株価予測モデルの学習(トレーニング)

今回はLightGBMで予測を行っていきます。
先ほど用意した学習用データを使ってモデルを生成します。

$ qlib/examples/benchmarks/LightGBM
$ pip3 install -r requirements.txt
$ cd qlib/examples
$ qrun benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml

学習させたモデルの分析結果は以下の通りです。

[record_temp.py:411] - Portfolio analysis record 'port_analysis_1day.pkl' has been saved as the artifact of the Experiment 1
'The following are analysis results of benchmark return(1day).'
                       risk
mean               0.000477
std                0.012295
annualized_return  0.113561
information_ratio  0.598699
max_drawdown      -0.370479
'The following are analysis results of the excess return without cost(1day).'
                       risk
mean               0.000580
std                0.005751
annualized_return  0.138124
information_ratio  1.556923
max_drawdown      -0.094040
'The following are analysis results of the excess return with cost(1day).'
                       risk
mean               0.000385
std                0.005747
annualized_return  0.091711
information_ratio  1.034353
max_drawdown      -0.103803
[11244:MainThread](2021-11-03 19:13:06,719) INFO - qlib.workflow - [record_temp.py:438] - Indicator analysis record 'indicator_analysis_1day.pkl' has been saved as the artifact of the Experiment 1
'The following are analysis results of indicators(1day).'
     value
ffr    1.0
pa     0.0
pos    0.0

次に視覚化した予測結果を出力します。
examples/workflow_by_code.ipynbを実行します。

annualized_return

モデルのトレーニング、モデルの評価、視覚化などが非常に簡単に実行できます。

トラブルシューティング集

Requirement.parse('pyparsing<3,>=2.0.2')

エラー詳細
pkg_resources.ContextualVersionConflict: (pyparsing 3.0.4 (/home/k140411335/miniconda3/envs/QLIB/lib/python3.7/site-packages/pyparsing-3.0.4-py3.7.egg), Requirement.parse('pyparsing<3,>=2.0.2'), {'packaging'})

解決方法
pip3 install pyparsing=="2.4.7"

ModuleNotFoundError: No module named 'torch'

解決方法
conda install pytorch==1.7.1 torchvision==0.8.2 torchaudio==0.7.2 cudatoolkit=10.1 -c pytorch

ValueError: unsupported pickle protocol: 5

解決方法
pip3 install pickle5でpickle5をインストールした後に、
QLIB/lib/python3.7/site-packages/pandas-1.3.4-py3.7-linux-x86_64.egg/pandas/io/pickle.py
import pickleimport pickle5 as pickleに変更
参考: Python 3.7 Error: Unsupported Pickle Protocol 5

ImportError: IProgress not found. Please update jupyter and ipywidgets.

解決方法
conda install -y -c conda-forge ipywidgets
jupyter nbextension enable --py widgetsnbextension

"No module named 'pandas.core.sparse.series'"

解決方法
pip install -U pandas

まとめ

本記事では、QLibで株価予測を行う方法を紹介しました。
本記事ではデフォルトで用意されている中国のデータを使って予測しましたが
日本のデータを用意すれば同様に日本株の予測も可能です。

また本記事では、機械学習を動かすことにフォーカスしてご紹介しました。
もう少し学術的に体系立てて学びたいという方には以下の書籍などがお勧めです。ぜひご一読下さい。


また動かせるだけから理解して応用できるエンジニアの足掛かりに下記のUdemyなどもお勧めです。

参考文献

1. 論文 - Qlib: An AI-oriented Quantitative Investment Platform

2. 論文 - Learning Multiple Stock Trading Patterns with Temporal Routing Adaptor and Optimal Transport

3. GitHub - microsoft/qlib

4. Qlib Documentation

AIで副業ならココから!

まずは無料会員登録

プロフィール

メーカーで研究開発を行う現役エンジニア
組み込み機器開発や機会学習モデル開発に従事しています

本ブログでは最新AI技術を中心にソースコード付きでご紹介します


Twitter

カテゴリ

このブログを検索

ブログ アーカイブ

TeDokology