2022-05-04 15:42:34 +00:00
|
|
|
import gc
|
2022-05-04 15:53:40 +00:00
|
|
|
import logging
|
|
|
|
from abc import ABC, abstractmethod
|
2022-05-04 15:42:34 +00:00
|
|
|
from pathlib import Path
|
|
|
|
from typing import Any, Dict, Tuple
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
import pandas as pd
|
|
|
|
from pandas import DataFrame
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-06 10:54:49 +00:00
|
|
|
from freqtrade.freqai.data_kitchen import FreqaiDataKitchen
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
pd.options.mode.chained_assignment = None
|
2022-05-04 15:53:40 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
class IFreqaiModel(ABC):
|
|
|
|
"""
|
|
|
|
Class containing all tools for training and prediction in the strategy.
|
2022-05-04 15:42:34 +00:00
|
|
|
User models should inherit from this class as shown in
|
2022-05-03 08:14:17 +00:00
|
|
|
templates/ExamplePredictionModel.py where the user overrides
|
|
|
|
train(), predict(), fit(), and make_labels().
|
2022-05-03 08:28:13 +00:00
|
|
|
Author: Robert Caulk, rob.caulk@gmail.com
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, config: Dict[str, Any]) -> None:
|
|
|
|
|
|
|
|
self.config = config
|
2022-05-04 15:42:34 +00:00
|
|
|
self.freqai_info = config["freqai"]
|
|
|
|
self.data_split_parameters = config["freqai"]["data_split_parameters"]
|
|
|
|
self.model_training_parameters = config["freqai"]["model_training_parameters"]
|
|
|
|
self.feature_parameters = config["freqai"]["feature_parameters"]
|
2022-05-05 13:35:51 +00:00
|
|
|
self.backtest_timerange = config["timerange"]
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
self.time_last_trained = None
|
|
|
|
self.current_time = None
|
|
|
|
self.model = None
|
|
|
|
self.predictions = None
|
|
|
|
|
|
|
|
def start(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
|
|
"""
|
2022-05-04 15:42:34 +00:00
|
|
|
Entry point to the FreqaiModel, it will train a new model if
|
2022-05-03 08:14:17 +00:00
|
|
|
necesssary before making the prediction.
|
|
|
|
The backtesting and training paradigm is a sliding training window
|
|
|
|
with a following backtest window. Both windows slide according to the
|
2022-05-04 15:42:34 +00:00
|
|
|
length of the backtest window. This function is not intended to be
|
|
|
|
overridden by children of IFreqaiModel, but technically, it can be
|
2022-05-03 08:14:17 +00:00
|
|
|
if the user wishes to make deeper changes to the sliding window
|
|
|
|
logic.
|
|
|
|
:params:
|
|
|
|
:dataframe: Full dataframe coming from strategy - it contains entire
|
2022-05-04 15:42:34 +00:00
|
|
|
backtesting timerange + additional historical data necessary to train
|
2022-05-03 08:14:17 +00:00
|
|
|
the model.
|
2022-05-04 15:42:34 +00:00
|
|
|
:metadata: pair metadataa coming from strategy.
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
2022-05-04 15:42:34 +00:00
|
|
|
self.pair = metadata["pair"]
|
2022-05-06 10:54:49 +00:00
|
|
|
self.dh = FreqaiDataKitchen(self.config, dataframe)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-05 12:37:37 +00:00
|
|
|
logger.info("going to train %s timeranges", len(self.dh.training_timeranges))
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
# Loop enforcing the sliding window training/backtesting paragigm
|
|
|
|
# tr_train is the training time range e.g. 1 historical month
|
2022-05-04 15:42:34 +00:00
|
|
|
# tr_backtest is the backtesting time range e.g. the week directly
|
|
|
|
# following tr_train. Both of these windows slide through the
|
2022-05-03 08:14:17 +00:00
|
|
|
# entire backtest
|
2022-05-04 15:42:34 +00:00
|
|
|
for tr_train, tr_backtest in zip(
|
|
|
|
self.dh.training_timeranges, self.dh.backtesting_timeranges
|
|
|
|
):
|
2022-05-03 08:14:17 +00:00
|
|
|
gc.collect()
|
2022-05-04 15:42:34 +00:00
|
|
|
# self.config['timerange'] = tr_train
|
|
|
|
self.dh.data = {} # clean the pair specific data between models
|
2022-05-05 13:35:51 +00:00
|
|
|
self.training_timerange = tr_train
|
2022-05-03 08:14:17 +00:00
|
|
|
dataframe_train = self.dh.slice_dataframe(tr_train, dataframe)
|
|
|
|
dataframe_backtest = self.dh.slice_dataframe(tr_backtest, dataframe)
|
2022-05-05 12:37:37 +00:00
|
|
|
logger.info("training %s for %s", self.pair, tr_train)
|
2022-05-05 13:35:51 +00:00
|
|
|
self.dh.model_path = Path(self.dh.full_path / str("sub-train" + "-" + str(tr_train)))
|
2022-05-03 08:14:17 +00:00
|
|
|
if not self.model_exists(self.pair, training_timerange=tr_train):
|
|
|
|
self.model = self.train(dataframe_train, metadata)
|
|
|
|
self.dh.save_data(self.model)
|
|
|
|
else:
|
2022-05-05 12:37:37 +00:00
|
|
|
self.model = self.dh.load_data()
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
preds, do_preds = self.predict(dataframe_backtest)
|
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
self.dh.append_predictions(preds, do_preds, len(dataframe_backtest))
|
2022-05-06 13:10:11 +00:00
|
|
|
print('predictions', len(self.dh.full_predictions),
|
|
|
|
'do_predict', len(self.dh.full_do_predict))
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
self.dh.fill_predictions(len(dataframe))
|
|
|
|
|
2022-05-06 13:10:11 +00:00
|
|
|
return (self.dh.full_predictions, self.dh.full_do_predict,
|
|
|
|
self.dh.full_target_mean, self.dh.full_target_std)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
def make_labels(self, dataframe: DataFrame) -> DataFrame:
|
|
|
|
"""
|
|
|
|
User defines the labels here (target values).
|
|
|
|
:params:
|
|
|
|
:dataframe: the full dataframe for the present training period
|
|
|
|
"""
|
|
|
|
|
|
|
|
return dataframe
|
|
|
|
|
2022-05-04 15:53:40 +00:00
|
|
|
@abstractmethod
|
2022-05-03 08:28:13 +00:00
|
|
|
def train(self, unfiltered_dataframe: DataFrame, metadata: dict) -> Any:
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
|
|
|
Filter the training data and train a model to it. Train makes heavy use of the datahandler
|
2022-05-03 08:28:13 +00:00
|
|
|
for storing, saving, loading, and analyzing the data.
|
2022-05-03 08:14:17 +00:00
|
|
|
:params:
|
|
|
|
:unfiltered_dataframe: Full dataframe for the current training period
|
2022-05-04 15:42:34 +00:00
|
|
|
:metadata: pair metadata from strategy.
|
2022-05-03 08:14:17 +00:00
|
|
|
:returns:
|
|
|
|
:model: Trained model which can be used to inference (self.predict)
|
|
|
|
"""
|
|
|
|
|
2022-05-04 15:53:40 +00:00
|
|
|
@abstractmethod
|
2022-05-03 08:14:17 +00:00
|
|
|
def fit(self) -> Any:
|
|
|
|
"""
|
2022-05-04 15:42:34 +00:00
|
|
|
Most regressors use the same function names and arguments e.g. user
|
2022-05-03 08:14:17 +00:00
|
|
|
can drop in LGBMRegressor in place of CatBoostRegressor and all data
|
|
|
|
management will be properly handled by Freqai.
|
|
|
|
:params:
|
2022-05-04 15:42:34 +00:00
|
|
|
:data_dictionary: the dictionary constructed by DataHandler to hold
|
2022-05-03 08:14:17 +00:00
|
|
|
all the training and test data/labels.
|
|
|
|
"""
|
|
|
|
|
2022-05-04 15:53:40 +00:00
|
|
|
@abstractmethod
|
2022-05-04 15:42:34 +00:00
|
|
|
def predict(self, dataframe: DataFrame) -> Tuple[np.array, np.array]:
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
|
|
|
Filter the prediction features data and predict with it.
|
|
|
|
:param: unfiltered_dataframe: Full dataframe for the current backtest period.
|
2022-05-04 15:42:34 +00:00
|
|
|
:return:
|
2022-05-03 08:14:17 +00:00
|
|
|
:predictions: np.array of 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-05-04 15:42:34 +00:00
|
|
|
def model_exists(self, pair: str, training_timerange: str) -> bool:
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
|
|
|
Given a pair and path, check if a model already exists
|
|
|
|
:param pair: pair e.g. BTC/USD
|
|
|
|
:param path: path to model
|
|
|
|
"""
|
2022-05-04 15:42:34 +00:00
|
|
|
coin, _ = pair.split("/")
|
|
|
|
self.dh.model_filename = "cb_" + coin.lower() + "_" + training_timerange
|
|
|
|
path_to_modelfile = Path(self.dh.model_path / str(self.dh.model_filename + "_model.joblib"))
|
|
|
|
file_exists = path_to_modelfile.is_file()
|
2022-05-03 08:14:17 +00:00
|
|
|
if file_exists:
|
2022-05-05 12:37:37 +00:00
|
|
|
logger.info("Found model at %s", self.dh.model_path / self.dh.model_filename)
|
2022-05-04 15:42:34 +00:00
|
|
|
else:
|
2022-05-05 12:37:37 +00:00
|
|
|
logger.info("Could not find model at %s", self.dh.model_path / self.dh.model_filename)
|
2022-05-03 08:14:17 +00:00
|
|
|
return file_exists
|