4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

金融分野における強化学習のための取引環境「trading_gym_next」の使い方

Posted at

はじめに

今日はbacktesting.pyというバックテストツールを活用した取引環境「trading_gym_next」を開発したので、その使い方について解説していきます。金融分野の取引環境をいちから開発するのはなかなか大変ですが、backtesting.pyというライブラリを活用することで、簡単にかつ強力な機能をもつ環境を実装できました。
スクリーンショット 2021-10-16 20.26.03.png

GitHubはこちらです:
https://github.com/RuiHirano/trading_gym_next

Install

インストールは簡単で以下のコマンドでpipから取得できます。

pip install trading_gym_next

Quick Start

Exampleとしてデフォルトの環境をそのまま使うもの、環境をカスタマイズしたもの、バックテスト評価を行うものの三つ用意しました。
それぞれ試してみてください。

cd examples
python simple_env.py
python custom_env.py
python backtest.py

解説

基本となるコードについて解説していきます。

from backtesting.test import GOOG
import random
from trading_gym_next import EnvParameter, TradingEnv

param = EnvParameter(df=GOOG[:200], mode="sequential", window_size=10)
print(GOOG)
env = TradingEnv(param)

for i in range(20):
    print("episode: ", i)
    obs = env.reset()
    for k in range(10):
        action = random.choice([0,1,2])
        next_obs, reward, done, info = env.step(action, size=1)
        print("obs", obs.tail())
        print("action: ", action)
        print("date: {}, reward: {}, done: {}, timestamp: {}, episode_step: {}, position: {}".format(info["date"], reward, done, info["timestamp"], info["episode_step"], info["position"]))
        print("next_obs", next_obs.tail())
        print("-"*10)
        obs = next_obs
print("finished")
stats = env.stats()
print(stats)

基本的にはgym環境をラップしているのでgymを利用したことのある人であればすぐに使えると思います。
env.reset()で環境を初期化し、env.step()でエピソードを進めていきます。

env.step()の引数だけ少し変わっています。actionの値は0,1,2で(何もしない、買い、売り)と指定でき、オプション引数にsize(数量)、limit(上限価格),stop(下限価格),sl(stop loss), tp(take profit)を指定できるようになっています。

またenv.stats()で統計結果、env.plot()で可視化が可能になります。ただ、こちらは最後のエピソードの結果のみを計算するので、backtestモードで使用するのが主になると思います。

さいごに

そのほかの詳しいオプションについてはGithubのREADMEまたはbacktesting.pyなどを参考にしてください。
金融分野の強化学習に興味を持っている人の助けになれれば幸いです。

4
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?