2022-08-15 11:46:12 +00:00
|
|
|
import logging
|
|
|
|
from typing import Any, Dict # , Tuple
|
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
# import numpy.typing as npt
|
|
|
|
# import pandas as pd
|
|
|
|
import torch as th
|
|
|
|
# from pandas import DataFrame
|
2022-08-15 16:56:53 +00:00
|
|
|
from stable_baselines3.common.monitor import Monitor
|
2022-08-15 11:46:12 +00:00
|
|
|
from typing import Callable
|
|
|
|
from stable_baselines3 import PPO
|
|
|
|
from stable_baselines3.common.callbacks import EvalCallback
|
|
|
|
from stable_baselines3.common.vec_env import SubprocVecEnv
|
|
|
|
from stable_baselines3.common.utils import set_random_seed
|
|
|
|
from freqtrade.freqai.RL.Base3ActionRLEnv import Base3ActionRLEnv, Actions, Positions
|
|
|
|
from freqtrade.freqai.RL.BaseReinforcementLearningModel import BaseReinforcementLearningModel
|
2022-08-15 16:01:15 +00:00
|
|
|
from freqtrade.freqai.data_kitchen import FreqaiDataKitchen
|
2022-08-15 11:46:12 +00:00
|
|
|
import gym
|
2022-08-15 16:01:15 +00:00
|
|
|
|
2022-08-15 11:46:12 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
def make_env(env_id: str, rank: int, seed: int, train_df, price,
|
2022-08-15 16:56:53 +00:00
|
|
|
reward_params, window_size, monitor=False) -> Callable:
|
2022-08-15 11:46:12 +00:00
|
|
|
"""
|
|
|
|
Utility function for multiprocessed env.
|
|
|
|
|
|
|
|
:param env_id: (str) the environment ID
|
|
|
|
:param num_env: (int) the number of environment you wish to have in subprocesses
|
|
|
|
:param seed: (int) the inital seed for RNG
|
|
|
|
:param rank: (int) index of the subprocess
|
|
|
|
:return: (Callable)
|
|
|
|
"""
|
|
|
|
def _init() -> gym.Env:
|
|
|
|
|
|
|
|
env = MyRLEnv(df=train_df, prices=price, window_size=window_size,
|
|
|
|
reward_kwargs=reward_params, id=env_id, seed=seed + rank)
|
2022-08-15 16:56:53 +00:00
|
|
|
if monitor:
|
|
|
|
env = Monitor(env, ".")
|
2022-08-15 11:46:12 +00:00
|
|
|
return env
|
|
|
|
set_random_seed(seed)
|
|
|
|
return _init
|
|
|
|
|
|
|
|
|
|
|
|
class ReinforcementLearningPPO_multiproc(BaseReinforcementLearningModel):
|
|
|
|
"""
|
|
|
|
User created Reinforcement Learning Model prediction model.
|
|
|
|
"""
|
|
|
|
|
2022-08-15 16:01:15 +00:00
|
|
|
def fit_rl(self, data_dictionary: Dict[str, Any], pair: str, dk: FreqaiDataKitchen):
|
2022-08-15 11:46:12 +00:00
|
|
|
|
|
|
|
agent_params = self.freqai_info['model_training_parameters']
|
|
|
|
reward_params = self.freqai_info['model_reward_parameters']
|
|
|
|
train_df = data_dictionary["train_features"]
|
|
|
|
test_df = data_dictionary["test_features"]
|
|
|
|
eval_freq = agent_params.get("eval_cycles", 4) * len(test_df)
|
|
|
|
total_timesteps = agent_params["train_cycles"] * len(train_df)
|
2022-08-15 15:35:41 +00:00
|
|
|
learning_rate = agent_params["learning_rate"]
|
2022-08-15 11:46:12 +00:00
|
|
|
|
|
|
|
# price data for model training and evaluation
|
|
|
|
price = self.dd.historic_data[pair][f"{self.config['timeframe']}"].tail(len(train_df.index))
|
|
|
|
price_test = self.dd.historic_data[pair][f"{self.config['timeframe']}"].tail(
|
|
|
|
len(test_df.index))
|
|
|
|
|
2022-08-15 15:35:41 +00:00
|
|
|
env_id = "train_env"
|
2022-08-15 16:01:15 +00:00
|
|
|
num_cpu = int(dk.thread_count / 2)
|
2022-08-15 11:46:12 +00:00
|
|
|
train_env = SubprocVecEnv([make_env(env_id, i, 1, train_df, price, reward_params,
|
2022-08-15 16:08:20 +00:00
|
|
|
self.CONV_WIDTH) for i in range(num_cpu)])
|
2022-08-15 11:46:12 +00:00
|
|
|
|
2022-08-15 15:35:41 +00:00
|
|
|
eval_env_id = 'eval_env'
|
|
|
|
eval_env = SubprocVecEnv([make_env(eval_env_id, i, 1, test_df, price_test, reward_params,
|
2022-08-15 16:56:53 +00:00
|
|
|
self.CONV_WIDTH, monitor=True) for i in range(num_cpu)])
|
2022-08-15 11:46:12 +00:00
|
|
|
|
2022-08-15 16:01:15 +00:00
|
|
|
path = dk.data_path
|
2022-08-15 11:46:12 +00:00
|
|
|
eval_callback = EvalCallback(eval_env, best_model_save_path=f"{path}/",
|
|
|
|
log_path=f"{path}/ppo/logs/", eval_freq=int(eval_freq),
|
|
|
|
deterministic=True, render=False)
|
|
|
|
|
|
|
|
# model arch
|
|
|
|
policy_kwargs = dict(activation_fn=th.nn.ReLU,
|
2022-08-15 15:35:41 +00:00
|
|
|
net_arch=[512, 512, 512])
|
2022-08-15 11:46:12 +00:00
|
|
|
|
|
|
|
model = PPO('MlpPolicy', train_env, policy_kwargs=policy_kwargs,
|
2022-08-15 15:35:41 +00:00
|
|
|
tensorboard_log=f"{path}/ppo/tensorboard/", learning_rate=learning_rate, gamma=0.9, verbose=1
|
2022-08-15 11:46:12 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
model.learn(
|
|
|
|
total_timesteps=int(total_timesteps),
|
|
|
|
callback=eval_callback
|
|
|
|
)
|
|
|
|
|
2022-08-15 16:56:53 +00:00
|
|
|
best_model = PPO.load(dk.data_path / "best_model.zip")
|
2022-08-15 11:46:12 +00:00
|
|
|
print('Training finished!')
|
2022-08-15 15:35:41 +00:00
|
|
|
eval_env.close()
|
2022-08-15 11:46:12 +00:00
|
|
|
|
2022-08-15 16:56:53 +00:00
|
|
|
return best_model
|
2022-08-15 11:46:12 +00:00
|
|
|
|
|
|
|
|
|
|
|
class MyRLEnv(Base3ActionRLEnv):
|
|
|
|
"""
|
|
|
|
User can override any function in BaseRLEnv and gym.Env
|
|
|
|
"""
|
|
|
|
|
|
|
|
def calculate_reward(self, action):
|
|
|
|
|
|
|
|
if self._last_trade_tick is None:
|
|
|
|
return 0.
|
|
|
|
|
|
|
|
# close long
|
|
|
|
if (action == Actions.Short.value or
|
|
|
|
action == Actions.Neutral.value) and self._position == Positions.Long:
|
|
|
|
last_trade_price = self.add_buy_fee(self.prices.iloc[self._last_trade_tick].open)
|
|
|
|
current_price = self.add_sell_fee(self.prices.iloc[self._current_tick].open)
|
|
|
|
return float(np.log(current_price) - np.log(last_trade_price))
|
|
|
|
|
|
|
|
# close short
|
|
|
|
if (action == Actions.Long.value or
|
|
|
|
action == Actions.Neutral.value) and self._position == Positions.Short:
|
|
|
|
last_trade_price = self.add_sell_fee(self.prices.iloc[self._last_trade_tick].open)
|
|
|
|
current_price = self.add_buy_fee(self.prices.iloc[self._current_tick].open)
|
|
|
|
return float(np.log(last_trade_price) - np.log(current_price))
|
|
|
|
|
|
|
|
return 0.
|