2022-05-04 15:53:40 +00:00
|
|
|
import logging
|
2022-05-04 15:42:34 +00:00
|
|
|
from typing import Any, Dict, Tuple
|
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
import pandas as pd
|
|
|
|
from catboost import CatBoostRegressor, Pool
|
|
|
|
from pandas import DataFrame
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
from freqtrade.freqai.freqai_interface import IFreqaiModel
|
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-04 15:53:40 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
class ExamplePredictionModel(IFreqaiModel):
|
|
|
|
"""
|
|
|
|
User created prediction model. The class needs to override three necessary
|
|
|
|
functions, predict(), train(), fit(). The class inherits ModelHandler which
|
2022-05-04 15:42:34 +00:00
|
|
|
has its own DataHandler where data is held, saved, loaded, and managed.
|
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
|
|
|
|
"""
|
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
dataframe["s"] = (
|
|
|
|
dataframe["close"]
|
|
|
|
.shift(-self.feature_parameters["period"])
|
|
|
|
.rolling(self.feature_parameters["period"])
|
|
|
|
.max()
|
|
|
|
/ dataframe["close"]
|
|
|
|
- 1
|
|
|
|
)
|
|
|
|
self.dh.data["s_mean"] = dataframe["s"].mean()
|
|
|
|
self.dh.data["s_std"] = dataframe["s"].std()
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-05 12:37:37 +00:00
|
|
|
# logger.info("label mean", self.dh.data["s_mean"], "label std", self.dh.data["s_std"])
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
return dataframe["s"]
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
def train(self, unfiltered_dataframe: DataFrame, metadata: dict) -> Tuple[DataFrame, DataFrame]:
|
|
|
|
"""
|
2022-05-15 12:01:53 +00:00
|
|
|
Filter the training data and train a model to it. Train makes heavy use of the datahkitchen
|
|
|
|
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
|
|
|
logger.info("--------------------Starting training--------------------")
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
# create the full feature list based on user config info
|
2022-05-09 15:01:49 +00:00
|
|
|
self.dh.training_features_list = self.dh.build_feature_list(self.config, metadata)
|
2022-05-03 08:14:17 +00:00
|
|
|
unfiltered_labels = self.make_labels(unfiltered_dataframe)
|
|
|
|
|
|
|
|
# filter the features requested by user in the configuration file and elegantly handle NaNs
|
2022-05-04 15:42:34 +00:00
|
|
|
features_filtered, labels_filtered = self.dh.filter_features(
|
|
|
|
unfiltered_dataframe,
|
|
|
|
self.dh.training_features_list,
|
|
|
|
unfiltered_labels,
|
|
|
|
training_filter=True,
|
|
|
|
)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
# split data into train/test data.
|
|
|
|
data_dictionary = self.dh.make_train_test_datasets(features_filtered, labels_filtered)
|
|
|
|
# standardize all data based on train_dataset only
|
|
|
|
data_dictionary = self.dh.standardize_data(data_dictionary)
|
|
|
|
|
|
|
|
# optional additional data cleaning
|
2022-05-04 15:42:34 +00:00
|
|
|
if self.feature_parameters["principal_component_analysis"]:
|
2022-05-03 08:14:17 +00:00
|
|
|
self.dh.principal_component_analysis()
|
|
|
|
if self.feature_parameters["remove_outliers"]:
|
|
|
|
self.dh.remove_outliers(predict=False)
|
2022-05-04 15:42:34 +00:00
|
|
|
if self.feature_parameters["DI_threshold"]:
|
|
|
|
self.dh.data["avg_mean_dist"] = self.dh.compute_distances()
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-05 12:37:37 +00:00
|
|
|
logger.info("length of train data %s", len(data_dictionary["train_features"]))
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
model = self.fit(data_dictionary)
|
|
|
|
|
2022-05-04 15:53:40 +00:00
|
|
|
logger.info(f'--------------------done training {metadata["pair"]}--------------------')
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
return model
|
|
|
|
|
|
|
|
def fit(self, data_dictionary: Dict) -> 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.
|
|
|
|
"""
|
|
|
|
|
|
|
|
train_data = Pool(
|
2022-05-04 15:42:34 +00:00
|
|
|
data=data_dictionary["train_features"],
|
|
|
|
label=data_dictionary["train_labels"],
|
|
|
|
weight=data_dictionary["train_weights"],
|
2022-05-03 08:14:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
test_data = Pool(
|
2022-05-04 15:42:34 +00:00
|
|
|
data=data_dictionary["test_features"],
|
|
|
|
label=data_dictionary["test_labels"],
|
|
|
|
weight=data_dictionary["test_weights"],
|
2022-05-03 08:14:17 +00:00
|
|
|
)
|
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
model = CatBoostRegressor(
|
|
|
|
verbose=100, early_stopping_rounds=400, **self.model_training_parameters
|
|
|
|
)
|
2022-05-03 08:14:17 +00:00
|
|
|
model.fit(X=train_data, eval_set=test_data)
|
|
|
|
|
|
|
|
return model
|
|
|
|
|
2022-05-09 15:01:49 +00:00
|
|
|
def predict(self, unfiltered_dataframe: DataFrame, metadata: dict) -> Tuple[DataFrame,
|
|
|
|
DataFrame]:
|
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-09 13:25:00 +00:00
|
|
|
# logger.info("--------------------Starting prediction--------------------")
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-09 15:01:49 +00:00
|
|
|
original_feature_list = self.dh.build_feature_list(self.config, metadata)
|
2022-05-04 15:42:34 +00:00
|
|
|
filtered_dataframe, _ = self.dh.filter_features(
|
|
|
|
unfiltered_dataframe, original_feature_list, training_filter=False
|
|
|
|
)
|
2022-05-03 08:14:17 +00:00
|
|
|
filtered_dataframe = self.dh.standardize_data_from_metadata(filtered_dataframe)
|
2022-05-04 15:42:34 +00:00
|
|
|
self.dh.data_dictionary["prediction_features"] = filtered_dataframe
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
# optional additional data cleaning
|
|
|
|
if self.feature_parameters["principal_component_analysis"]:
|
2022-05-03 08:14:17 +00:00
|
|
|
pca_components = self.dh.pca.transform(filtered_dataframe)
|
2022-05-04 15:42:34 +00:00
|
|
|
self.dh.data_dictionary["prediction_features"] = pd.DataFrame(
|
|
|
|
data=pca_components,
|
|
|
|
columns=["PC" + str(i) for i in range(0, self.dh.data["n_kept_components"])],
|
|
|
|
index=filtered_dataframe.index,
|
|
|
|
)
|
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
if self.feature_parameters["remove_outliers"]:
|
2022-05-04 15:42:34 +00:00
|
|
|
self.dh.remove_outliers(predict=True) # creates dropped index
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
if self.feature_parameters["DI_threshold"]:
|
|
|
|
self.dh.check_if_pred_in_training_spaces() # sets do_predict
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
predictions = self.model.predict(self.dh.data_dictionary["prediction_features"])
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
# compute the non-standardized predictions
|
2022-05-09 13:25:00 +00:00
|
|
|
self.dh.predictions = predictions * self.dh.data["labels_std"] + self.dh.data["labels_mean"]
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-09 13:25:00 +00:00
|
|
|
# logger.info("--------------------Finished prediction--------------------")
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-09 13:25:00 +00:00
|
|
|
return (self.dh.predictions, self.dh.do_predict)
|