2022-08-20 14:35:29 +00:00
|
|
|
import logging
|
2022-08-24 10:54:02 +00:00
|
|
|
from typing import Any, Dict
|
2022-08-20 14:35:29 +00:00
|
|
|
|
|
|
|
import torch as th
|
|
|
|
from freqtrade.freqai.data_kitchen import FreqaiDataKitchen
|
|
|
|
from freqtrade.freqai.RL.Base5ActionRLEnv import Actions, Base5ActionRLEnv, Positions
|
|
|
|
from freqtrade.freqai.RL.BaseReinforcementLearningModel import BaseReinforcementLearningModel
|
|
|
|
from pathlib import Path
|
2022-08-24 16:32:40 +00:00
|
|
|
from pandas import DataFrame
|
|
|
|
from stable_baselines3.common.callbacks import EvalCallback
|
|
|
|
from stable_baselines3.common.monitor import Monitor
|
|
|
|
import numpy as np
|
2022-08-20 14:35:29 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class ReinforcementLearner(BaseReinforcementLearningModel):
|
|
|
|
"""
|
|
|
|
User created Reinforcement Learning Model prediction model.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def fit_rl(self, data_dictionary: Dict[str, Any], dk: FreqaiDataKitchen):
|
|
|
|
|
|
|
|
train_df = data_dictionary["train_features"]
|
|
|
|
total_timesteps = self.freqai_info["rl_config"]["train_cycles"] * len(train_df)
|
|
|
|
|
|
|
|
policy_kwargs = dict(activation_fn=th.nn.ReLU,
|
2022-08-24 10:54:02 +00:00
|
|
|
net_arch=[512, 512, 256])
|
|
|
|
|
2022-08-25 09:46:18 +00:00
|
|
|
if dk.pair not in self.dd.model_dictionary or not self.continual_learning:
|
2022-08-24 10:54:02 +00:00
|
|
|
model = self.MODELCLASS(self.policy_type, self.train_env, policy_kwargs=policy_kwargs,
|
|
|
|
tensorboard_log=Path(dk.data_path / "tensorboard"),
|
|
|
|
**self.freqai_info['model_training_parameters']
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
logger.info('Continual training activated - starting training from previously '
|
|
|
|
'trained agent.')
|
|
|
|
model = self.dd.model_dictionary[dk.pair]
|
2022-08-24 14:32:14 +00:00
|
|
|
model.tensorboard_log = Path(dk.data_path / "tensorboard")
|
2022-08-24 10:54:02 +00:00
|
|
|
model.set_env(self.train_env)
|
2022-08-20 14:35:29 +00:00
|
|
|
|
|
|
|
model.learn(
|
|
|
|
total_timesteps=int(total_timesteps),
|
|
|
|
callback=self.eval_callback
|
|
|
|
)
|
|
|
|
|
|
|
|
if Path(dk.data_path / "best_model.zip").is_file():
|
|
|
|
logger.info('Callback found a best model.')
|
|
|
|
best_model = self.MODELCLASS.load(dk.data_path / "best_model")
|
|
|
|
return best_model
|
|
|
|
|
|
|
|
logger.info('Couldnt find best model, using final model instead.')
|
|
|
|
|
|
|
|
return model
|
|
|
|
|
2022-08-24 16:32:40 +00:00
|
|
|
def set_train_and_eval_environments(self, data_dictionary: Dict[str, DataFrame],
|
|
|
|
prices_train: DataFrame, prices_test: DataFrame,
|
|
|
|
dk: FreqaiDataKitchen):
|
|
|
|
"""
|
|
|
|
User can override this if they are using a custom MyRLEnv
|
|
|
|
"""
|
|
|
|
train_df = data_dictionary["train_features"]
|
|
|
|
test_df = data_dictionary["test_features"]
|
|
|
|
|
|
|
|
self.train_env = MyRLEnv(df=train_df, prices=prices_train, window_size=self.CONV_WIDTH,
|
|
|
|
reward_kwargs=self.reward_params, config=self.config)
|
|
|
|
self.eval_env = Monitor(MyRLEnv(df=test_df, prices=prices_test,
|
|
|
|
window_size=self.CONV_WIDTH,
|
|
|
|
reward_kwargs=self.reward_params, config=self.config))
|
|
|
|
self.eval_callback = EvalCallback(self.eval_env, deterministic=True,
|
2022-08-25 09:46:18 +00:00
|
|
|
render=False, eval_freq=len(train_df),
|
2022-08-24 16:32:40 +00:00
|
|
|
best_model_save_path=str(dk.data_path))
|
|
|
|
|
2022-08-20 14:35:29 +00:00
|
|
|
|
|
|
|
class MyRLEnv(Base5ActionRLEnv):
|
|
|
|
"""
|
2022-08-23 12:58:38 +00:00
|
|
|
User can override any function in BaseRLEnv and gym.Env. Here the user
|
|
|
|
sets a custom reward based on profit and trade duration.
|
2022-08-20 14:35:29 +00:00
|
|
|
"""
|
2022-08-23 12:58:38 +00:00
|
|
|
|
2022-08-20 14:35:29 +00:00
|
|
|
def calculate_reward(self, action):
|
|
|
|
|
2022-08-24 16:32:40 +00:00
|
|
|
# first, penalize if the action is not valid
|
|
|
|
if not self._is_valid(action):
|
2022-08-25 09:46:18 +00:00
|
|
|
return -2
|
2022-08-20 14:35:29 +00:00
|
|
|
|
2022-08-23 12:58:38 +00:00
|
|
|
pnl = self.get_unrealized_profit()
|
2022-08-24 16:32:40 +00:00
|
|
|
rew = np.sign(pnl) * (pnl + 1)
|
|
|
|
factor = 100
|
|
|
|
|
|
|
|
# reward agent for entering trades
|
2022-08-25 09:46:18 +00:00
|
|
|
if action in (Actions.Long_enter.value, Actions.Short_enter.value) \
|
|
|
|
and self._position == Positions.Neutral:
|
2022-08-24 16:32:40 +00:00
|
|
|
return 25
|
|
|
|
# discourage agent from not entering trades
|
|
|
|
if action == Actions.Neutral.value and self._position == Positions.Neutral:
|
2022-08-25 09:46:18 +00:00
|
|
|
return -1
|
2022-08-24 16:32:40 +00:00
|
|
|
|
|
|
|
max_trade_duration = self.rl_config.get('max_trade_duration_candles', 300)
|
2022-08-23 12:58:38 +00:00
|
|
|
trade_duration = self._current_tick - self._last_trade_tick
|
|
|
|
|
|
|
|
if trade_duration <= max_trade_duration:
|
|
|
|
factor *= 1.5
|
|
|
|
elif trade_duration > max_trade_duration:
|
|
|
|
factor *= 0.5
|
|
|
|
|
2022-08-24 16:32:40 +00:00
|
|
|
# discourage sitting in position
|
2022-08-25 09:46:18 +00:00
|
|
|
if self._position in (Positions.Short, Positions.Long) and action == Actions.Neutral.value:
|
|
|
|
return -1 * trade_duration / max_trade_duration
|
2022-08-24 16:32:40 +00:00
|
|
|
|
2022-08-20 14:35:29 +00:00
|
|
|
# close long
|
|
|
|
if action == Actions.Long_exit.value and self._position == Positions.Long:
|
2022-08-24 16:32:40 +00:00
|
|
|
if pnl > self.profit_aim * self.rr:
|
2022-08-23 12:58:38 +00:00
|
|
|
factor *= self.rl_config['model_reward_parameters'].get('win_reward_factor', 2)
|
2022-08-24 16:32:40 +00:00
|
|
|
return float(rew * factor)
|
2022-08-20 14:35:29 +00:00
|
|
|
|
|
|
|
# close short
|
|
|
|
if action == Actions.Short_exit.value and self._position == Positions.Short:
|
2022-08-24 16:32:40 +00:00
|
|
|
if pnl > self.profit_aim * self.rr:
|
2022-08-23 12:58:38 +00:00
|
|
|
factor *= self.rl_config['model_reward_parameters'].get('win_reward_factor', 2)
|
2022-08-24 16:32:40 +00:00
|
|
|
return float(rew * factor)
|
2022-08-20 14:35:29 +00:00
|
|
|
|
|
|
|
return 0.
|