2023-02-10 14:48:18 +00:00
|
|
|
import copy
|
2022-11-17 20:50:02 +00:00
|
|
|
import importlib
|
2022-08-15 08:26:44 +00:00
|
|
|
import logging
|
2022-08-28 17:21:57 +00:00
|
|
|
from abc import abstractmethod
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
from pathlib import Path
|
2022-11-26 12:32:18 +00:00
|
|
|
from typing import Any, Callable, Dict, Optional, Tuple, Type, Union
|
2022-08-15 08:26:44 +00:00
|
|
|
|
2022-08-28 17:21:57 +00:00
|
|
|
import gym
|
2022-08-15 08:26:44 +00:00
|
|
|
import numpy as np
|
|
|
|
import numpy.typing as npt
|
|
|
|
import pandas as pd
|
2022-08-28 17:21:57 +00:00
|
|
|
import torch as th
|
|
|
|
import torch.multiprocessing
|
2022-08-15 08:26:44 +00:00
|
|
|
from pandas import DataFrame
|
2022-12-04 12:54:30 +00:00
|
|
|
from stable_baselines3.common.callbacks import EvalCallback
|
2022-08-28 17:21:57 +00:00
|
|
|
from stable_baselines3.common.monitor import Monitor
|
|
|
|
from stable_baselines3.common.utils import set_random_seed
|
2022-09-23 17:30:56 +00:00
|
|
|
from stable_baselines3.common.vec_env import SubprocVecEnv
|
2022-08-28 17:21:57 +00:00
|
|
|
|
2022-08-21 17:58:36 +00:00
|
|
|
from freqtrade.exceptions import OperationalException
|
2022-08-15 08:26:44 +00:00
|
|
|
from freqtrade.freqai.data_kitchen import FreqaiDataKitchen
|
|
|
|
from freqtrade.freqai.freqai_interface import IFreqaiModel
|
2022-08-28 17:21:57 +00:00
|
|
|
from freqtrade.freqai.RL.Base5ActionRLEnv import Actions, Base5ActionRLEnv
|
2022-12-04 12:54:30 +00:00
|
|
|
from freqtrade.freqai.RL.BaseEnvironment import BaseActions, Positions
|
|
|
|
from freqtrade.freqai.RL.TensorboardCallback import TensorboardCallback
|
2022-08-15 08:26:44 +00:00
|
|
|
from freqtrade.persistence import Trade
|
2022-09-17 15:51:06 +00:00
|
|
|
|
2022-08-28 17:21:57 +00:00
|
|
|
|
2022-08-15 08:26:44 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
2022-08-18 11:02:47 +00:00
|
|
|
|
2022-08-17 10:51:14 +00:00
|
|
|
torch.multiprocessing.set_sharing_strategy('file_system')
|
2022-08-15 08:26:44 +00:00
|
|
|
|
2022-08-25 09:46:18 +00:00
|
|
|
SB3_MODELS = ['PPO', 'A2C', 'DQN']
|
|
|
|
SB3_CONTRIB_MODELS = ['TRPO', 'ARS', 'RecurrentPPO', 'MaskablePPO']
|
2022-08-21 17:58:36 +00:00
|
|
|
|
2022-08-15 08:26:44 +00:00
|
|
|
|
|
|
|
class BaseReinforcementLearningModel(IFreqaiModel):
|
|
|
|
"""
|
2022-09-23 17:17:27 +00:00
|
|
|
User created Reinforcement Learning Model prediction class
|
2022-08-15 08:26:44 +00:00
|
|
|
"""
|
|
|
|
|
2022-11-26 12:03:07 +00:00
|
|
|
def __init__(self, **kwargs) -> None:
|
2022-08-18 11:02:47 +00:00
|
|
|
super().__init__(config=kwargs['config'])
|
2022-09-28 22:37:03 +00:00
|
|
|
self.max_threads = min(self.freqai_info['rl_config'].get(
|
2022-09-29 12:00:09 +00:00
|
|
|
'cpu_count', 1), max(int(self.max_system_threads / 2), 1))
|
2022-09-28 22:10:18 +00:00
|
|
|
th.set_num_threads(self.max_threads)
|
2022-08-18 11:02:47 +00:00
|
|
|
self.reward_params = self.freqai_info['rl_config']['model_reward_parameters']
|
2022-12-04 12:54:30 +00:00
|
|
|
self.train_env: Union[SubprocVecEnv, Type[gym.Env]] = gym.Env()
|
|
|
|
self.eval_env: Union[SubprocVecEnv, Type[gym.Env]] = gym.Env()
|
2022-11-26 12:32:18 +00:00
|
|
|
self.eval_callback: Optional[EvalCallback] = None
|
2022-08-21 17:58:36 +00:00
|
|
|
self.model_type = self.freqai_info['rl_config']['model_type']
|
2022-08-24 10:54:02 +00:00
|
|
|
self.rl_config = self.freqai_info['rl_config']
|
2023-02-10 14:48:18 +00:00
|
|
|
self.df_raw: DataFrame = DataFrame()
|
2022-09-14 22:46:35 +00:00
|
|
|
self.continual_learning = self.freqai_info.get('continual_learning', False)
|
2022-08-21 17:58:36 +00:00
|
|
|
if self.model_type in SB3_MODELS:
|
|
|
|
import_str = 'stable_baselines3'
|
|
|
|
elif self.model_type in SB3_CONTRIB_MODELS:
|
|
|
|
import_str = 'sb3_contrib'
|
|
|
|
else:
|
|
|
|
raise OperationalException(f'{self.model_type} not available in stable_baselines3 or '
|
|
|
|
f'sb3_contrib. please choose one of {SB3_MODELS} or '
|
|
|
|
f'{SB3_CONTRIB_MODELS}')
|
|
|
|
|
2022-11-17 20:50:02 +00:00
|
|
|
mod = importlib.import_module(import_str, self.model_type)
|
2022-08-21 17:58:36 +00:00
|
|
|
self.MODELCLASS = getattr(mod, self.model_type)
|
2022-08-20 14:35:29 +00:00
|
|
|
self.policy_type = self.freqai_info['rl_config']['policy_type']
|
2022-09-14 22:46:35 +00:00
|
|
|
self.unset_outlier_removal()
|
2022-10-08 10:10:38 +00:00
|
|
|
self.net_arch = self.rl_config.get('net_arch', [128, 128])
|
2022-12-01 07:08:42 +00:00
|
|
|
self.dd.model_type = import_str
|
2022-12-04 12:54:30 +00:00
|
|
|
self.tensorboard_callback: TensorboardCallback = \
|
|
|
|
TensorboardCallback(verbose=1, actions=BaseActions)
|
2022-09-14 22:46:35 +00:00
|
|
|
|
|
|
|
def unset_outlier_removal(self):
|
|
|
|
"""
|
|
|
|
If user has activated any function that may remove training points, this
|
|
|
|
function will set them to false and warn them
|
|
|
|
"""
|
|
|
|
if self.ft_params.get('use_SVM_to_remove_outliers', False):
|
|
|
|
self.ft_params.update({'use_SVM_to_remove_outliers': False})
|
|
|
|
logger.warning('User tried to use SVM with RL. Deactivating SVM.')
|
|
|
|
if self.ft_params.get('use_DBSCAN_to_remove_outliers', False):
|
2022-11-13 14:31:37 +00:00
|
|
|
self.ft_params.update({'use_DBSCAN_to_remove_outliers': False})
|
2022-09-14 22:46:35 +00:00
|
|
|
logger.warning('User tried to use DBSCAN with RL. Deactivating DBSCAN.')
|
|
|
|
if self.freqai_info['data_split_parameters'].get('shuffle', False):
|
2022-11-13 14:31:37 +00:00
|
|
|
self.freqai_info['data_split_parameters'].update({'shuffle': False})
|
2022-09-14 22:46:35 +00:00
|
|
|
logger.warning('User tried to shuffle training data. Setting shuffle to False')
|
2022-08-18 11:02:47 +00:00
|
|
|
|
2022-08-15 08:26:44 +00:00
|
|
|
def train(
|
2022-09-14 22:46:35 +00:00
|
|
|
self, unfiltered_df: DataFrame, pair: str, dk: FreqaiDataKitchen, **kwargs
|
2022-08-15 08:26:44 +00:00
|
|
|
) -> Any:
|
|
|
|
"""
|
|
|
|
Filter the training data and train a model to it. Train makes heavy use of the datakitchen
|
|
|
|
for storing, saving, loading, and analyzing the data.
|
2022-09-14 22:46:35 +00:00
|
|
|
:param unfiltered_df: Full dataframe for the current training period
|
2022-08-15 08:26:44 +00:00
|
|
|
:param metadata: pair metadata from strategy.
|
|
|
|
:returns:
|
|
|
|
:model: Trained model which can be used to inference (self.predict)
|
|
|
|
"""
|
|
|
|
|
|
|
|
logger.info("--------------------Starting training " f"{pair} --------------------")
|
|
|
|
|
|
|
|
features_filtered, labels_filtered = dk.filter_features(
|
2022-09-14 22:46:35 +00:00
|
|
|
unfiltered_df,
|
2022-08-15 08:26:44 +00:00
|
|
|
dk.training_features_list,
|
|
|
|
dk.label_list,
|
|
|
|
training_filter=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
data_dictionary: Dict[str, Any] = dk.make_train_test_datasets(
|
|
|
|
features_filtered, labels_filtered)
|
2023-02-10 14:48:18 +00:00
|
|
|
self.df_raw = copy.deepcopy(data_dictionary["train_features"])
|
2022-08-24 10:54:02 +00:00
|
|
|
dk.fit_labels() # FIXME useless for now, but just satiating append methods
|
2022-08-15 08:26:44 +00:00
|
|
|
|
|
|
|
# normalize all data based on train_dataset only
|
2022-08-17 10:51:14 +00:00
|
|
|
prices_train, prices_test = self.build_ohlc_price_dataframes(dk.data_dictionary, pair, dk)
|
2023-03-07 10:33:54 +00:00
|
|
|
|
2022-08-15 08:26:44 +00:00
|
|
|
data_dictionary = dk.normalize_data(data_dictionary)
|
|
|
|
|
2022-08-24 10:54:02 +00:00
|
|
|
# data cleaning/analysis
|
2022-08-15 08:26:44 +00:00
|
|
|
self.data_cleaning_train(dk)
|
|
|
|
|
|
|
|
logger.info(
|
2022-08-24 10:54:02 +00:00
|
|
|
f'Training model on {len(dk.data_dictionary["train_features"].columns)}'
|
|
|
|
f' features and {len(data_dictionary["train_features"])} data points'
|
2022-08-15 08:26:44 +00:00
|
|
|
)
|
|
|
|
|
2022-08-20 14:35:29 +00:00
|
|
|
self.set_train_and_eval_environments(data_dictionary, prices_train, prices_test, dk)
|
2022-08-18 14:07:19 +00:00
|
|
|
|
2022-09-14 22:46:35 +00:00
|
|
|
model = self.fit(data_dictionary, dk)
|
2022-08-15 08:26:44 +00:00
|
|
|
|
|
|
|
logger.info(f"--------------------done training {pair}--------------------")
|
|
|
|
|
|
|
|
return model
|
|
|
|
|
2022-08-24 10:54:02 +00:00
|
|
|
def set_train_and_eval_environments(self, data_dictionary: Dict[str, DataFrame],
|
|
|
|
prices_train: DataFrame, prices_test: DataFrame,
|
|
|
|
dk: FreqaiDataKitchen):
|
2022-08-18 14:07:19 +00:00
|
|
|
"""
|
2022-08-24 10:54:02 +00:00
|
|
|
User can override this if they are using a custom MyRLEnv
|
2022-11-13 16:43:52 +00:00
|
|
|
:param data_dictionary: dict = common data dictionary containing train and test
|
2022-09-23 17:17:27 +00:00
|
|
|
features/labels/weights.
|
2022-11-13 16:43:52 +00:00
|
|
|
:param prices_train/test: DataFrame = dataframe comprised of the prices to be used in the
|
2022-11-24 06:00:12 +00:00
|
|
|
environment during training or testing
|
2022-11-13 16:43:52 +00:00
|
|
|
:param dk: FreqaiDataKitchen = the datakitchen for the current pair
|
2022-08-18 14:07:19 +00:00
|
|
|
"""
|
|
|
|
train_df = data_dictionary["train_features"]
|
|
|
|
test_df = data_dictionary["test_features"]
|
|
|
|
|
2023-02-10 13:45:50 +00:00
|
|
|
env_info = self.pack_env_dict(dk.pair)
|
2022-12-14 19:03:05 +00:00
|
|
|
|
2023-03-07 10:33:54 +00:00
|
|
|
self.train_env = self.MyRLEnv(df=train_df, prices=prices_train, **env_info)
|
|
|
|
self.eval_env = Monitor(self.MyRLEnv(df=test_df, prices=prices_test, **env_info))
|
2022-08-24 16:32:40 +00:00
|
|
|
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-12-03 11:31:02 +00:00
|
|
|
|
2022-12-04 12:54:30 +00:00
|
|
|
actions = self.train_env.get_actions()
|
|
|
|
self.tensorboard_callback = TensorboardCallback(verbose=1, actions=actions)
|
2022-08-18 14:07:19 +00:00
|
|
|
|
2023-02-10 13:45:50 +00:00
|
|
|
def pack_env_dict(self, pair: str) -> Dict[str, Any]:
|
2022-12-15 11:25:33 +00:00
|
|
|
"""
|
|
|
|
Create dictionary of environment arguments
|
|
|
|
"""
|
|
|
|
env_info = {"window_size": self.CONV_WIDTH,
|
|
|
|
"reward_kwargs": self.reward_params,
|
|
|
|
"config": self.config,
|
2022-12-16 19:16:19 +00:00
|
|
|
"live": self.live,
|
2023-02-10 13:45:50 +00:00
|
|
|
"can_short": self.can_short,
|
2023-02-10 14:48:18 +00:00
|
|
|
"pair": pair,
|
|
|
|
"df_raw": self.df_raw}
|
2022-12-15 11:25:33 +00:00
|
|
|
if self.data_provider:
|
|
|
|
env_info["fee"] = self.data_provider._exchange \
|
|
|
|
.get_fee(symbol=self.data_provider.current_whitelist()[0]) # type: ignore
|
|
|
|
|
|
|
|
return env_info
|
|
|
|
|
2022-08-15 08:26:44 +00:00
|
|
|
@abstractmethod
|
2022-09-14 22:46:35 +00:00
|
|
|
def fit(self, data_dictionary: Dict[str, Any], dk: FreqaiDataKitchen, **kwargs):
|
2022-08-15 08:26:44 +00:00
|
|
|
"""
|
|
|
|
Agent customizations and abstract Reinforcement Learning customizations
|
|
|
|
go in here. Abstract method, so this function must be overridden by
|
|
|
|
user class.
|
|
|
|
"""
|
|
|
|
return
|
|
|
|
|
2022-09-23 17:17:27 +00:00
|
|
|
def get_state_info(self, pair: str) -> Tuple[float, float, int]:
|
|
|
|
"""
|
2022-11-24 17:46:54 +00:00
|
|
|
State info during dry/live (not backtesting) which is fed back
|
2022-09-23 17:17:27 +00:00
|
|
|
into the model.
|
2022-11-24 17:46:54 +00:00
|
|
|
:param pair: str = COIN/STAKE to get the environment information for
|
|
|
|
:return:
|
|
|
|
:market_side: float = representing short, long, or neutral for
|
2022-09-23 17:17:27 +00:00
|
|
|
pair
|
2022-11-24 17:46:54 +00:00
|
|
|
:current_profit: float = unrealized profit of the current trade
|
|
|
|
:trade_duration: int = the number of candles that the trade has
|
2022-09-23 17:17:27 +00:00
|
|
|
been open for
|
|
|
|
"""
|
2022-08-21 15:43:40 +00:00
|
|
|
open_trades = Trade.get_trades_proxy(is_open=True)
|
2022-08-15 08:26:44 +00:00
|
|
|
market_side = 0.5
|
2022-08-24 10:54:02 +00:00
|
|
|
current_profit: float = 0
|
2022-08-23 07:44:44 +00:00
|
|
|
trade_duration = 0
|
2022-08-15 08:26:44 +00:00
|
|
|
for trade in open_trades:
|
|
|
|
if trade.pair == pair:
|
2022-11-12 10:33:03 +00:00
|
|
|
if self.data_provider._exchange is None: # type: ignore
|
2022-09-14 22:56:51 +00:00
|
|
|
logger.error('No exchange available.')
|
2022-11-13 14:31:37 +00:00
|
|
|
return 0, 0, 0
|
2022-09-14 22:56:51 +00:00
|
|
|
else:
|
2022-11-13 12:41:17 +00:00
|
|
|
current_rate = self.data_provider._exchange.get_rate( # type: ignore
|
2022-09-14 22:56:51 +00:00
|
|
|
pair, refresh=False, side="exit", is_short=trade.is_short)
|
2022-11-13 12:41:17 +00:00
|
|
|
|
2022-08-23 07:44:44 +00:00
|
|
|
now = datetime.now(timezone.utc).timestamp()
|
2022-11-13 14:31:37 +00:00
|
|
|
trade_duration = int((now - trade.open_date_utc.timestamp()) / self.base_tf_seconds)
|
2022-11-13 12:41:17 +00:00
|
|
|
current_profit = trade.calc_profit_ratio(current_rate)
|
2022-11-30 11:36:26 +00:00
|
|
|
if trade.is_short:
|
|
|
|
market_side = 0
|
|
|
|
else:
|
|
|
|
market_side = 1
|
2022-08-15 08:26:44 +00:00
|
|
|
|
2022-08-23 07:44:44 +00:00
|
|
|
return market_side, current_profit, int(trade_duration)
|
2022-08-15 08:26:44 +00:00
|
|
|
|
|
|
|
def predict(
|
2022-09-14 22:46:35 +00:00
|
|
|
self, unfiltered_df: DataFrame, dk: FreqaiDataKitchen, **kwargs
|
2022-08-15 08:26:44 +00:00
|
|
|
) -> Tuple[DataFrame, npt.NDArray[np.int_]]:
|
|
|
|
"""
|
|
|
|
Filter the prediction features data and predict with it.
|
2022-11-24 06:00:12 +00:00
|
|
|
:param unfiltered_dataframe: Full dataframe for the current backtest period.
|
2022-08-15 08:26:44 +00:00
|
|
|
:return:
|
|
|
|
:pred_df: dataframe containing the predictions
|
|
|
|
:do_predict: np.array of 1s and 0s to indicate places where freqai needed to remove
|
|
|
|
data (NaNs) or felt uncertain about data (PCA and DI index)
|
|
|
|
"""
|
|
|
|
|
2022-09-14 22:46:35 +00:00
|
|
|
dk.find_features(unfiltered_df)
|
2022-08-15 08:26:44 +00:00
|
|
|
filtered_dataframe, _ = dk.filter_features(
|
2022-09-14 22:46:35 +00:00
|
|
|
unfiltered_df, dk.training_features_list, training_filter=False
|
2022-08-15 08:26:44 +00:00
|
|
|
)
|
2023-03-08 10:26:28 +00:00
|
|
|
|
|
|
|
filtered_dataframe = self.drop_ohlc_from_df(filtered_dataframe, dk)
|
|
|
|
|
2022-08-15 08:26:44 +00:00
|
|
|
filtered_dataframe = dk.normalize_data_from_metadata(filtered_dataframe)
|
|
|
|
dk.data_dictionary["prediction_features"] = filtered_dataframe
|
|
|
|
|
|
|
|
# optional additional data cleaning/analysis
|
2022-10-01 18:26:41 +00:00
|
|
|
self.data_cleaning_predict(dk)
|
2022-08-15 08:26:44 +00:00
|
|
|
|
2022-08-18 11:02:47 +00:00
|
|
|
pred_df = self.rl_model_predict(
|
|
|
|
dk.data_dictionary["prediction_features"], dk, self.model)
|
2022-08-15 08:26:44 +00:00
|
|
|
pred_df.fillna(0, inplace=True)
|
|
|
|
|
|
|
|
return (pred_df, dk.do_predict)
|
|
|
|
|
|
|
|
def rl_model_predict(self, dataframe: DataFrame,
|
|
|
|
dk: FreqaiDataKitchen, model: Any) -> DataFrame:
|
2022-09-23 17:17:27 +00:00
|
|
|
"""
|
|
|
|
A helper function to make predictions in the Reinforcement learning module.
|
2022-11-13 16:43:52 +00:00
|
|
|
:param dataframe: DataFrame = the dataframe of features to make the predictions on
|
|
|
|
:param dk: FreqaiDatakitchen = data kitchen for the current pair
|
|
|
|
:param model: Any = the trained model used to inference the features.
|
2022-09-23 17:17:27 +00:00
|
|
|
"""
|
2022-08-18 11:02:47 +00:00
|
|
|
output = pd.DataFrame(np.zeros(len(dataframe)), columns=dk.label_list)
|
2022-08-15 08:26:44 +00:00
|
|
|
|
|
|
|
def _predict(window):
|
|
|
|
observations = dataframe.iloc[window.index]
|
2022-11-17 20:50:02 +00:00
|
|
|
if self.live and self.rl_config.get('add_state_info', False):
|
2022-11-12 17:46:48 +00:00
|
|
|
market_side, current_profit, trade_duration = self.get_state_info(dk.pair)
|
|
|
|
observations['current_profit_pct'] = current_profit
|
|
|
|
observations['position'] = market_side
|
|
|
|
observations['trade_duration'] = trade_duration
|
2022-08-15 08:26:44 +00:00
|
|
|
res, _ = model.predict(observations, deterministic=True)
|
|
|
|
return res
|
|
|
|
|
|
|
|
output = output.rolling(window=self.CONV_WIDTH).apply(_predict)
|
|
|
|
|
|
|
|
return output
|
|
|
|
|
2022-08-17 10:51:14 +00:00
|
|
|
def build_ohlc_price_dataframes(self, data_dictionary: dict,
|
|
|
|
pair: str, dk: FreqaiDataKitchen) -> Tuple[DataFrame,
|
|
|
|
DataFrame]:
|
|
|
|
"""
|
|
|
|
Builds the train prices and test prices for the environment.
|
|
|
|
"""
|
|
|
|
|
2022-11-12 11:01:59 +00:00
|
|
|
pair = pair.replace(':', '')
|
2022-08-17 10:51:14 +00:00
|
|
|
train_df = data_dictionary["train_features"]
|
|
|
|
test_df = data_dictionary["test_features"]
|
|
|
|
|
|
|
|
# price data for model training and evaluation
|
|
|
|
tf = self.config['timeframe']
|
2022-12-30 12:02:39 +00:00
|
|
|
rename_dict = {'%-raw_open': 'open', '%-raw_low': 'low',
|
|
|
|
'%-raw_high': ' high', '%-raw_close': 'close'}
|
|
|
|
rename_dict_old = {f'%-{pair}raw_open_{tf}': 'open', f'%-{pair}raw_low_{tf}': 'low',
|
|
|
|
f'%-{pair}raw_high_{tf}': ' high', f'%-{pair}raw_close_{tf}': 'close'}
|
|
|
|
|
|
|
|
prices_train = train_df.filter(rename_dict.keys(), axis=1)
|
|
|
|
prices_train_old = train_df.filter(rename_dict_old.keys(), axis=1)
|
|
|
|
if prices_train.empty or not prices_train_old.empty:
|
|
|
|
if not prices_train_old.empty:
|
|
|
|
prices_train = prices_train_old
|
|
|
|
rename_dict = rename_dict_old
|
|
|
|
logger.warning('Reinforcement learning module didnt find the correct raw prices '
|
|
|
|
'assigned in feature_engineering_standard(). '
|
|
|
|
'Please assign them with:\n'
|
|
|
|
'dataframe["%-raw_close"] = dataframe["close"]\n'
|
|
|
|
'dataframe["%-raw_open"] = dataframe["open"]\n'
|
|
|
|
'dataframe["%-raw_high"] = dataframe["high"]\n'
|
|
|
|
'dataframe["%-raw_low"] = dataframe["low"]\n'
|
|
|
|
'inside `feature_engineering_standard()')
|
|
|
|
elif prices_train.empty:
|
|
|
|
raise OperationalException("No prices found, please follow log warning "
|
|
|
|
"instructions to correct the strategy.")
|
|
|
|
|
2022-08-17 10:51:14 +00:00
|
|
|
prices_train.rename(columns=rename_dict, inplace=True)
|
|
|
|
prices_train.reset_index(drop=True)
|
|
|
|
|
2022-12-30 12:02:39 +00:00
|
|
|
prices_test = test_df.filter(rename_dict.keys(), axis=1)
|
2022-08-17 10:51:14 +00:00
|
|
|
prices_test.rename(columns=rename_dict, inplace=True)
|
|
|
|
prices_test.reset_index(drop=True)
|
|
|
|
|
2023-03-08 10:26:28 +00:00
|
|
|
train_df = self.drop_ohlc_from_df(train_df, dk)
|
|
|
|
test_df = self.drop_ohlc_from_df(test_df, dk)
|
|
|
|
|
|
|
|
return prices_train, prices_test
|
|
|
|
|
|
|
|
def drop_ohlc_from_df(self, df: DataFrame, dk: FreqaiDataKitchen):
|
|
|
|
"""
|
|
|
|
Given a dataframe, drop the ohlc data
|
|
|
|
"""
|
|
|
|
drop_list = ['%-raw_open', '%-raw_low', '%-raw_high', '%-raw_close']
|
|
|
|
|
2023-03-07 10:33:54 +00:00
|
|
|
if self.rl_config["drop_ohlc_from_features"]:
|
2023-03-08 10:26:28 +00:00
|
|
|
df.drop(drop_list, axis=1, inplace=True)
|
2023-03-08 18:37:11 +00:00
|
|
|
feature_list = dk.training_features_list
|
|
|
|
dk.training_features_list = [e for e in feature_list if e not in drop_list]
|
2023-03-07 10:33:54 +00:00
|
|
|
|
2023-03-08 10:26:28 +00:00
|
|
|
return df
|
2022-08-17 10:51:14 +00:00
|
|
|
|
2022-08-25 17:05:51 +00:00
|
|
|
def load_model_from_disk(self, dk: FreqaiDataKitchen) -> Any:
|
|
|
|
"""
|
|
|
|
Can be used by user if they are trying to limit_ram_usage *and*
|
|
|
|
perform continual learning.
|
|
|
|
For now, this is unused.
|
|
|
|
"""
|
|
|
|
exists = Path(dk.data_path / f"{dk.model_filename}_model").is_file()
|
|
|
|
if exists:
|
|
|
|
model = self.MODELCLASS.load(dk.data_path / f"{dk.model_filename}_model")
|
|
|
|
else:
|
|
|
|
logger.info('No model file on disk to continue learning from.')
|
|
|
|
|
|
|
|
return model
|
|
|
|
|
2022-10-08 10:10:38 +00:00
|
|
|
def _on_stop(self):
|
|
|
|
"""
|
|
|
|
Hook called on bot shutdown. Close SubprocVecEnv subprocesses for clean shutdown.
|
|
|
|
"""
|
|
|
|
|
|
|
|
if self.train_env:
|
|
|
|
self.train_env.close()
|
|
|
|
|
|
|
|
if self.eval_env:
|
|
|
|
self.eval_env.close()
|
|
|
|
|
2022-08-25 17:05:51 +00:00
|
|
|
# Nested class which can be overridden by user to customize further
|
|
|
|
class MyRLEnv(Base5ActionRLEnv):
|
|
|
|
"""
|
|
|
|
User can override any function in BaseRLEnv and gym.Env. Here the user
|
|
|
|
sets a custom reward based on profit and trade duration.
|
|
|
|
"""
|
|
|
|
|
2023-02-10 14:26:17 +00:00
|
|
|
def calculate_reward(self, action: int) -> float: # noqa: C901
|
2022-09-23 17:17:27 +00:00
|
|
|
"""
|
|
|
|
An example reward function. This is the one function that users will likely
|
|
|
|
wish to inject their own creativity into.
|
2022-11-13 16:43:52 +00:00
|
|
|
:param action: int = The action made by the agent for the current candle.
|
|
|
|
:return:
|
2022-09-23 17:17:27 +00:00
|
|
|
float = the reward to give to the agent for current step (used for optimization
|
|
|
|
of weights in NN)
|
|
|
|
"""
|
2022-08-25 17:05:51 +00:00
|
|
|
# first, penalize if the action is not valid
|
|
|
|
if not self._is_valid(action):
|
|
|
|
return -2
|
|
|
|
|
|
|
|
pnl = self.get_unrealized_profit()
|
2022-09-23 17:17:27 +00:00
|
|
|
factor = 100.
|
2022-08-25 17:05:51 +00:00
|
|
|
|
2023-02-10 13:45:50 +00:00
|
|
|
# you can use feature values from dataframe
|
2023-02-10 14:48:18 +00:00
|
|
|
rsi_now = self.raw_features[f"%-rsi-period-10_shift-1_{self.pair}_"
|
|
|
|
f"{self.config['timeframe']}"].iloc[self._current_tick]
|
2023-02-10 13:45:50 +00:00
|
|
|
|
2022-08-25 17:05:51 +00:00
|
|
|
# reward agent for entering trades
|
2022-09-23 17:17:27 +00:00
|
|
|
if (action in (Actions.Long_enter.value, Actions.Short_enter.value)
|
|
|
|
and self._position == Positions.Neutral):
|
2023-02-10 13:45:50 +00:00
|
|
|
if rsi_now < 40:
|
|
|
|
factor = 40 / rsi_now
|
|
|
|
else:
|
|
|
|
factor = 1
|
|
|
|
return 25 * factor
|
|
|
|
|
2022-08-25 17:05:51 +00:00
|
|
|
# discourage agent from not entering trades
|
|
|
|
if action == Actions.Neutral.value and self._position == Positions.Neutral:
|
|
|
|
return -1
|
|
|
|
|
|
|
|
max_trade_duration = self.rl_config.get('max_trade_duration_candles', 300)
|
2022-09-23 17:17:27 +00:00
|
|
|
if self._last_trade_tick:
|
|
|
|
trade_duration = self._current_tick - self._last_trade_tick
|
|
|
|
else:
|
|
|
|
trade_duration = 0
|
2022-08-25 17:05:51 +00:00
|
|
|
|
|
|
|
if trade_duration <= max_trade_duration:
|
|
|
|
factor *= 1.5
|
|
|
|
elif trade_duration > max_trade_duration:
|
|
|
|
factor *= 0.5
|
|
|
|
|
|
|
|
# discourage sitting in position
|
2022-09-23 17:17:27 +00:00
|
|
|
if (self._position in (Positions.Short, Positions.Long) and
|
|
|
|
action == Actions.Neutral.value):
|
2022-08-25 17:05:51 +00:00
|
|
|
return -1 * trade_duration / max_trade_duration
|
|
|
|
|
|
|
|
# close long
|
|
|
|
if action == Actions.Long_exit.value and self._position == Positions.Long:
|
|
|
|
if pnl > self.profit_aim * self.rr:
|
|
|
|
factor *= self.rl_config['model_reward_parameters'].get('win_reward_factor', 2)
|
2022-10-05 18:55:50 +00:00
|
|
|
return float(pnl * factor)
|
2022-08-25 17:05:51 +00:00
|
|
|
|
|
|
|
# close short
|
|
|
|
if action == Actions.Short_exit.value and self._position == Positions.Short:
|
|
|
|
if pnl > self.profit_aim * self.rr:
|
|
|
|
factor *= self.rl_config['model_reward_parameters'].get('win_reward_factor', 2)
|
2022-10-05 18:55:50 +00:00
|
|
|
return float(pnl * factor)
|
2022-08-25 17:05:51 +00:00
|
|
|
|
|
|
|
return 0.
|
|
|
|
|
2022-08-21 17:58:36 +00:00
|
|
|
|
2022-09-23 17:17:27 +00:00
|
|
|
def make_env(MyRLEnv: Type[gym.Env], env_id: str, rank: int,
|
2022-08-25 17:05:51 +00:00
|
|
|
seed: int, train_df: DataFrame, price: DataFrame,
|
2022-12-15 11:25:33 +00:00
|
|
|
monitor: bool = False,
|
|
|
|
env_info: Dict[str, Any] = {}) -> Callable:
|
2022-08-20 14:35:29 +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
|
2022-12-15 15:50:08 +00:00
|
|
|
:param env_info: (dict) all required arguments to instantiate the environment.
|
2022-08-20 14:35:29 +00:00
|
|
|
:return: (Callable)
|
|
|
|
"""
|
2022-08-25 17:05:51 +00:00
|
|
|
|
2022-08-20 14:35:29 +00:00
|
|
|
def _init() -> gym.Env:
|
|
|
|
|
2022-12-15 11:25:33 +00:00
|
|
|
env = MyRLEnv(df=train_df, prices=price, id=env_id, seed=seed + rank,
|
|
|
|
**env_info)
|
2022-08-20 14:35:29 +00:00
|
|
|
if monitor:
|
2022-08-25 09:46:18 +00:00
|
|
|
env = Monitor(env)
|
2022-08-20 14:35:29 +00:00
|
|
|
return env
|
|
|
|
set_random_seed(seed)
|
|
|
|
return _init
|