2022-05-19 19:15:58 +00:00
|
|
|
# import contextlib
|
2022-05-31 16:42:27 +00:00
|
|
|
import datetime
|
2022-05-04 15:42:34 +00:00
|
|
|
import gc
|
2022-05-04 15:53:40 +00:00
|
|
|
import logging
|
2022-05-19 19:15:58 +00:00
|
|
|
# import sys
|
|
|
|
import threading
|
2022-05-04 15:53:40 +00:00
|
|
|
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
|
|
|
|
2022-06-17 12:55:40 +00:00
|
|
|
import numpy as np
|
2022-05-06 14:20:52 +00:00
|
|
|
import numpy.typing as npt
|
2022-05-03 08:14:17 +00:00
|
|
|
import pandas as pd
|
|
|
|
from pandas import DataFrame
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-22 22:06:26 +00:00
|
|
|
from freqtrade.configuration import TimeRange
|
2022-05-06 14:20:52 +00:00
|
|
|
from freqtrade.enums import RunMode
|
2022-05-25 10:37:25 +00:00
|
|
|
from freqtrade.exceptions import OperationalException
|
2022-05-23 19:05:05 +00:00
|
|
|
from freqtrade.freqai.data_drawer import FreqaiDataDrawer
|
2022-05-06 10:54:49 +00:00
|
|
|
from freqtrade.freqai.data_kitchen import FreqaiDataKitchen
|
2022-05-09 13:25:00 +00:00
|
|
|
from freqtrade.strategy.interface import IStrategy
|
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-19 19:15:58 +00:00
|
|
|
|
|
|
|
def threaded(fn):
|
|
|
|
def wrapper(*args, **kwargs):
|
|
|
|
threading.Thread(target=fn, args=args, kwargs=kwargs).start()
|
|
|
|
return wrapper
|
|
|
|
|
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-23 10:07:09 +00:00
|
|
|
self.assert_config(self.config)
|
2022-05-04 15:42:34 +00:00
|
|
|
self.freqai_info = config["freqai"]
|
2022-06-03 13:19:46 +00:00
|
|
|
self.data_split_parameters = config.get('freqai', {}).get("data_split_parameters")
|
|
|
|
self.model_training_parameters = config.get("freqai", {}).get("model_training_parameters")
|
|
|
|
self.feature_parameters = config.get("freqai", {}).get("feature_parameters")
|
2022-05-03 08:14:17 +00:00
|
|
|
self.time_last_trained = None
|
|
|
|
self.current_time = None
|
|
|
|
self.model = None
|
|
|
|
self.predictions = None
|
2022-05-19 19:15:58 +00:00
|
|
|
self.training_on_separate_thread = False
|
|
|
|
self.retrain = False
|
2022-05-22 15:51:49 +00:00
|
|
|
self.first = True
|
2022-06-03 13:19:46 +00:00
|
|
|
self.update_historic_data = 0
|
2022-05-23 19:05:05 +00:00
|
|
|
self.set_full_path()
|
2022-05-30 19:35:48 +00:00
|
|
|
self.follow_mode = self.freqai_info.get('follow_mode', False)
|
2022-05-24 13:28:38 +00:00
|
|
|
self.data_drawer = FreqaiDataDrawer(Path(self.full_path),
|
2022-05-31 12:35:04 +00:00
|
|
|
self.config,
|
2022-05-30 19:35:48 +00:00
|
|
|
self.follow_mode)
|
2022-05-29 12:45:46 +00:00
|
|
|
self.lock = threading.Lock()
|
2022-05-30 19:35:48 +00:00
|
|
|
self.follow_mode = self.freqai_info.get('follow_mode', False)
|
|
|
|
self.identifier = self.freqai_info.get('identifier', 'no_id_provided')
|
2022-06-08 04:14:01 +00:00
|
|
|
self.scanning = False
|
|
|
|
self.ready_to_scan = False
|
2022-06-17 12:55:40 +00:00
|
|
|
self.first = True
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-23 10:07:09 +00:00
|
|
|
def assert_config(self, config: Dict[str, Any]) -> None:
|
2022-05-25 10:37:25 +00:00
|
|
|
|
|
|
|
if not config.get('freqai', {}):
|
|
|
|
raise OperationalException(
|
|
|
|
"No freqai parameters found in configuration file."
|
|
|
|
)
|
2022-05-23 10:07:09 +00:00
|
|
|
|
2022-05-09 13:25:00 +00:00
|
|
|
def start(self, dataframe: DataFrame, metadata: dict, strategy: IStrategy) -> DataFrame:
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
2022-05-23 19:05:05 +00:00
|
|
|
Entry point to the FreqaiModel from a specific pair, it will train a new model if
|
2022-05-15 14:25:08 +00:00
|
|
|
necessary before making the prediction.
|
2022-05-25 09:31:03 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
: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-15 14:25:08 +00:00
|
|
|
:metadata: pair metadata coming from strategy.
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-05-22 15:51:49 +00:00
|
|
|
self.live = strategy.dp.runmode in (RunMode.DRY_RUN, RunMode.LIVE)
|
2022-05-25 12:40:32 +00:00
|
|
|
self.data_drawer.set_pair_dict_info(metadata)
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-05-25 09:31:03 +00:00
|
|
|
# For live, we may be training new models on a separate thread while other pairs still need
|
|
|
|
# to inference their historical models. Here we use a training queue system to handle this
|
|
|
|
# and we keep the flag self.training_on_separate_threaad in the current object to help
|
|
|
|
# determine what the current pair will do
|
2022-05-22 15:51:49 +00:00
|
|
|
if self.live:
|
2022-06-08 04:14:01 +00:00
|
|
|
self.dh = FreqaiDataKitchen(self.config, self.data_drawer,
|
|
|
|
self.live, metadata["pair"])
|
|
|
|
dh = self.start_live(dataframe, metadata, strategy, self.dh)
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-05-25 09:31:03 +00:00
|
|
|
# For backtesting, each pair enters and then gets trained for each window along the
|
|
|
|
# sliding window defined by "train_period" (training window) and "backtest_period"
|
|
|
|
# (backtest window, i.e. window immediately following the training window).
|
|
|
|
# FreqAI slides the window and sequentially builds the backtesting results before returning
|
|
|
|
# the concatenated results for the full backtesting period back to the strategy.
|
2022-05-30 19:35:48 +00:00
|
|
|
elif not self.follow_mode:
|
2022-05-25 09:31:03 +00:00
|
|
|
self.dh = FreqaiDataKitchen(self.config, self.data_drawer, self.live, metadata["pair"])
|
|
|
|
logger.info(f'Training {len(self.dh.training_timeranges)} timeranges')
|
|
|
|
dh = self.start_backtesting(dataframe, metadata, self.dh)
|
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
return self.return_values(dataframe, dh)
|
2022-06-08 04:14:01 +00:00
|
|
|
|
|
|
|
@threaded
|
|
|
|
def start_scanning(self, strategy: IStrategy) -> None:
|
2022-06-17 14:16:23 +00:00
|
|
|
"""
|
|
|
|
Function designed to constantly scan pairs for retraining on a separate thread (intracandle)
|
|
|
|
to improve model youth. This function is agnostic to data preparation/collection/storage,
|
|
|
|
it simply trains on what ever data is available in the self.data_drawer.
|
|
|
|
:params:
|
|
|
|
strategy: IStrategy = The user defined strategy class
|
|
|
|
"""
|
2022-06-08 04:14:01 +00:00
|
|
|
while 1:
|
|
|
|
for pair in self.config.get('exchange', {}).get('pair_whitelist'):
|
|
|
|
if self.data_drawer.pair_dict[pair]['priority'] != 1:
|
|
|
|
continue
|
|
|
|
dh = FreqaiDataKitchen(self.config, self.data_drawer,
|
|
|
|
self.live, pair)
|
|
|
|
|
|
|
|
(model_filename,
|
|
|
|
trained_timestamp,
|
|
|
|
_, _) = self.data_drawer.get_pair_dict_info(pair)
|
|
|
|
|
|
|
|
file_exists = False
|
|
|
|
|
2022-06-15 22:21:15 +00:00
|
|
|
dh.set_paths(pair, trained_timestamp)
|
2022-06-08 04:14:01 +00:00
|
|
|
file_exists = self.model_exists(pair,
|
|
|
|
dh,
|
|
|
|
trained_timestamp=trained_timestamp,
|
2022-06-15 22:21:15 +00:00
|
|
|
model_filename=model_filename,
|
|
|
|
scanning=True)
|
2022-06-08 04:14:01 +00:00
|
|
|
|
2022-06-15 22:21:15 +00:00
|
|
|
(retrain,
|
2022-06-08 04:14:01 +00:00
|
|
|
new_trained_timerange,
|
|
|
|
data_load_timerange) = dh.check_if_new_training_required(trained_timestamp)
|
|
|
|
dh.set_paths(pair, new_trained_timerange.stopts)
|
|
|
|
|
2022-06-15 22:21:15 +00:00
|
|
|
if retrain or not file_exists:
|
2022-06-08 04:14:01 +00:00
|
|
|
self.train_model_in_series(new_trained_timerange, pair,
|
|
|
|
strategy, dh, data_load_timerange)
|
2022-05-06 14:20:52 +00:00
|
|
|
|
2022-05-25 09:31:03 +00:00
|
|
|
def start_backtesting(self, dataframe: DataFrame, metadata: dict,
|
|
|
|
dh: FreqaiDataKitchen) -> FreqaiDataKitchen:
|
|
|
|
"""
|
|
|
|
The main broad execution for backtesting. For backtesting, each pair enters and then gets
|
|
|
|
trained for each window along the sliding window defined by "train_period" (training window)
|
|
|
|
and "backtest_period" (backtest window, i.e. window immediately following the
|
|
|
|
training window). FreqAI slides the window and sequentially builds the backtesting results
|
|
|
|
before returning the concatenated results for the full backtesting period back to the
|
|
|
|
strategy.
|
|
|
|
:params:
|
|
|
|
dataframe: DataFrame = strategy passed dataframe
|
|
|
|
metadata: Dict = pair metadata
|
|
|
|
dh: FreqaiDataKitchen = Data management/analysis tool assoicated to present pair only
|
|
|
|
:returns:
|
|
|
|
dh: FreqaiDataKitchen = Data management/analysis tool assoicated to present pair only
|
|
|
|
"""
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-15 14:25:08 +00:00
|
|
|
# Loop enforcing the sliding window training/backtesting paradigm
|
2022-05-03 08:14:17 +00:00
|
|
|
# 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(
|
2022-05-25 09:31:03 +00:00
|
|
|
dh.training_timeranges, dh.backtesting_timeranges
|
2022-05-04 15:42:34 +00:00
|
|
|
):
|
2022-06-08 04:14:01 +00:00
|
|
|
(_, _, _, _) = self.data_drawer.get_pair_dict_info(metadata['pair'])
|
2022-05-03 08:14:17 +00:00
|
|
|
gc.collect()
|
2022-05-25 09:31:03 +00:00
|
|
|
dh.data = {} # clean the pair specific data between training window sliding
|
2022-05-05 13:35:51 +00:00
|
|
|
self.training_timerange = tr_train
|
2022-05-29 15:44:35 +00:00
|
|
|
# self.training_timerange_timerange = tr_train
|
2022-05-25 09:31:03 +00:00
|
|
|
dataframe_train = dh.slice_dataframe(tr_train, dataframe)
|
|
|
|
dataframe_backtest = dh.slice_dataframe(tr_backtest, dataframe)
|
2022-05-31 16:42:27 +00:00
|
|
|
|
2022-05-29 15:44:35 +00:00
|
|
|
trained_timestamp = tr_train # TimeRange.parse_timerange(tr_train)
|
2022-05-31 16:42:27 +00:00
|
|
|
tr_train_startts_str = datetime.datetime.utcfromtimestamp(
|
|
|
|
tr_train.startts).strftime('%Y-%m-%d %H:%M:%S')
|
|
|
|
tr_train_stopts_str = datetime.datetime.utcfromtimestamp(
|
|
|
|
tr_train.stopts).strftime('%Y-%m-%d %H:%M:%S')
|
|
|
|
logger.info("Training %s", metadata["pair"])
|
|
|
|
logger.info(f'Training {tr_train_startts_str} to {tr_train_stopts_str}')
|
|
|
|
|
2022-05-25 09:31:03 +00:00
|
|
|
dh.data_path = Path(dh.full_path /
|
|
|
|
str("sub-train" + "-" + metadata['pair'].split("/")[0] +
|
|
|
|
str(int(trained_timestamp.stopts))))
|
|
|
|
if not self.model_exists(metadata["pair"], dh,
|
2022-05-24 10:01:01 +00:00
|
|
|
trained_timestamp=trained_timestamp.stopts):
|
2022-06-08 04:14:01 +00:00
|
|
|
self.model = self.train(dataframe_train, metadata['pair'], dh)
|
2022-05-25 12:40:32 +00:00
|
|
|
self.data_drawer.pair_dict[metadata['pair']][
|
|
|
|
'trained_timestamp'] = trained_timestamp.stopts
|
2022-06-19 14:41:09 +00:00
|
|
|
dh.set_new_model_names(metadata['pair'], trained_timestamp)
|
2022-05-25 12:40:32 +00:00
|
|
|
dh.save_data(self.model, metadata['pair'])
|
2022-05-03 08:14:17 +00:00
|
|
|
else:
|
2022-05-25 12:40:32 +00:00
|
|
|
self.model = dh.load_data(metadata['pair'])
|
2022-05-25 09:31:03 +00:00
|
|
|
|
2022-05-26 19:07:50 +00:00
|
|
|
self.check_if_feature_list_matches_strategy(dataframe_train, dh)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-25 09:31:03 +00:00
|
|
|
preds, do_preds = self.predict(dataframe_backtest, dh)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-25 09:31:03 +00:00
|
|
|
dh.append_predictions(preds, do_preds, len(dataframe_backtest))
|
|
|
|
print('predictions', len(dh.full_predictions),
|
|
|
|
'do_predict', len(dh.full_do_predict))
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-25 09:31:03 +00:00
|
|
|
dh.fill_predictions(len(dataframe))
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-25 09:31:03 +00:00
|
|
|
return dh
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-24 10:01:01 +00:00
|
|
|
def start_live(self, dataframe: DataFrame, metadata: dict,
|
2022-06-08 04:14:01 +00:00
|
|
|
strategy: IStrategy, dh: FreqaiDataKitchen) -> FreqaiDataKitchen:
|
2022-05-17 15:13:38 +00:00
|
|
|
"""
|
|
|
|
The main broad execution for dry/live. This function will check if a retraining should be
|
|
|
|
performed, and if so, retrain and reset the model.
|
2022-05-25 09:31:03 +00:00
|
|
|
:params:
|
|
|
|
dataframe: DataFrame = strategy passed dataframe
|
|
|
|
metadata: Dict = pair metadata
|
|
|
|
strategy: IStrategy = currently employed strategy
|
|
|
|
dh: FreqaiDataKitchen = Data management/analysis tool assoicated to present pair only
|
|
|
|
:returns:
|
|
|
|
dh: FreqaiDataKitchen = Data management/analysis tool assoicated to present pair only
|
2022-05-17 15:13:38 +00:00
|
|
|
"""
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
# update follower
|
2022-05-31 09:58:21 +00:00
|
|
|
if self.follow_mode:
|
2022-06-03 13:19:46 +00:00
|
|
|
self.data_drawer.update_follower_metadata()
|
2022-05-31 09:58:21 +00:00
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
# get the model metadata associated with the current pair
|
2022-06-08 04:14:01 +00:00
|
|
|
(_,
|
2022-05-23 19:05:05 +00:00
|
|
|
trained_timestamp,
|
2022-06-15 22:21:15 +00:00
|
|
|
_,
|
2022-06-08 04:14:01 +00:00
|
|
|
return_null_array) = self.data_drawer.get_pair_dict_info(metadata['pair'])
|
2022-05-30 19:35:48 +00:00
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
# if the metadata doesnt exist, the follower returns null arrays to strategy
|
2022-05-30 19:35:48 +00:00
|
|
|
if self.follow_mode and return_null_array:
|
2022-05-31 10:35:09 +00:00
|
|
|
logger.info('Returning null array from follower to strategy')
|
2022-05-30 19:35:48 +00:00
|
|
|
self.data_drawer.return_null_values_to_strategy(dataframe, dh)
|
|
|
|
return dh
|
2022-05-28 10:23:26 +00:00
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
# append the historic data once per round
|
2022-06-07 18:24:23 +00:00
|
|
|
if self.data_drawer.historic_data:
|
2022-06-03 13:19:46 +00:00
|
|
|
dh.update_historic_data(strategy)
|
2022-06-07 17:49:20 +00:00
|
|
|
logger.info(f'Updating historic data on pair {metadata["pair"]}')
|
2022-06-03 13:19:46 +00:00
|
|
|
|
|
|
|
# if trainable, check if model needs training, if so compute new timerange,
|
|
|
|
# then save model and metadata.
|
|
|
|
# if not trainable, load existing data
|
2022-06-08 04:14:01 +00:00
|
|
|
if not self.follow_mode:
|
2022-05-24 10:01:01 +00:00
|
|
|
|
2022-06-17 12:55:40 +00:00
|
|
|
(_,
|
2022-05-31 16:42:27 +00:00
|
|
|
new_trained_timerange,
|
|
|
|
data_load_timerange) = dh.check_if_new_training_required(trained_timestamp)
|
2022-06-08 04:14:01 +00:00
|
|
|
dh.set_paths(metadata['pair'], new_trained_timerange.stopts)
|
2022-05-24 10:01:01 +00:00
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
# download candle history if it is not already in memory
|
|
|
|
if not self.data_drawer.historic_data:
|
|
|
|
logger.info('Downloading all training data for all pairs in whitelist and '
|
|
|
|
'corr_pairlist, this may take a while if you do not have the '
|
|
|
|
'data saved')
|
|
|
|
dh.download_all_data_for_training(data_load_timerange)
|
|
|
|
dh.load_all_pair_histories(data_load_timerange)
|
|
|
|
|
2022-06-15 22:21:15 +00:00
|
|
|
if not self.scanning:
|
2022-06-08 04:14:01 +00:00
|
|
|
self.scanning = True
|
|
|
|
self.start_scanning(strategy)
|
|
|
|
|
2022-05-30 19:35:48 +00:00
|
|
|
elif self.follow_mode:
|
2022-06-18 10:05:28 +00:00
|
|
|
dh.set_paths(metadata['pair'], trained_timestamp)
|
2022-05-30 19:35:48 +00:00
|
|
|
logger.info('FreqAI instance set to follow_mode, finding existing pair'
|
|
|
|
f'using { self.identifier }')
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
# load the model and associated data into the data kitchen
|
2022-05-24 10:01:01 +00:00
|
|
|
self.model = dh.load_data(coin=metadata['pair'])
|
2022-06-17 12:55:40 +00:00
|
|
|
|
2022-06-15 22:21:15 +00:00
|
|
|
if not self.model:
|
|
|
|
logger.warning('No model ready, returning null values to strategy.')
|
|
|
|
self.data_drawer.return_null_values_to_strategy(dataframe, dh)
|
|
|
|
return dh
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
# ensure user is feeding the correct indicators to the model
|
2022-05-26 19:07:50 +00:00
|
|
|
self.check_if_feature_list_matches_strategy(dataframe, dh)
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-06-17 12:55:40 +00:00
|
|
|
self.build_strategy_return_arrays(dataframe, dh, metadata['pair'], trained_timestamp)
|
|
|
|
|
|
|
|
return dh
|
|
|
|
|
|
|
|
def build_strategy_return_arrays(self, dataframe: DataFrame,
|
|
|
|
dh: FreqaiDataKitchen, pair: str,
|
|
|
|
trained_timestamp: int) -> None:
|
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
# hold the historical predictions in memory so we are sending back
|
|
|
|
# correct array to strategy FIXME currently broken, but only affecting
|
|
|
|
# Frequi reporting. Signals remain unaffeted.
|
2022-06-17 12:55:40 +00:00
|
|
|
|
|
|
|
if pair not in self.data_drawer.model_return_values:
|
2022-05-30 09:37:05 +00:00
|
|
|
preds, do_preds = self.predict(dataframe, dh)
|
|
|
|
dh.append_predictions(preds, do_preds, len(dataframe))
|
|
|
|
dh.fill_predictions(len(dataframe))
|
2022-06-17 12:55:40 +00:00
|
|
|
self.data_drawer.set_initial_return_values(pair, dh)
|
|
|
|
return
|
|
|
|
elif self.dh.check_if_model_expired(trained_timestamp):
|
|
|
|
preds, do_preds, dh.DI_values = np.zeros(2), np.ones(2) * 2, np.zeros(2)
|
|
|
|
logger.warning('Model expired, returning null values to strategy. Strategy '
|
|
|
|
'construction should take care to consider this event with '
|
|
|
|
'prediction == 0 and do_predict == 2')
|
2022-05-30 09:37:05 +00:00
|
|
|
else:
|
|
|
|
preds, do_preds = self.predict(dataframe.iloc[-2:], dh)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-06-17 12:55:40 +00:00
|
|
|
self.data_drawer.append_model_predictions(pair, preds, do_preds,
|
|
|
|
dh.data["target_mean"],
|
|
|
|
dh.data["target_std"],
|
|
|
|
dh,
|
|
|
|
len(dataframe))
|
|
|
|
return
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-26 19:07:50 +00:00
|
|
|
def check_if_feature_list_matches_strategy(self, dataframe: DataFrame,
|
|
|
|
dh: FreqaiDataKitchen) -> None:
|
2022-06-03 13:19:46 +00:00
|
|
|
"""
|
|
|
|
Ensure user is passing the proper feature set if they are reusing an `identifier` pointing
|
|
|
|
to a folder holding existing models.
|
|
|
|
:params:
|
|
|
|
dataframe: DataFrame = strategy provided dataframe
|
|
|
|
dh: FreqaiDataKitchen = non-persistent data container/analyzer for current coin/bot loop
|
|
|
|
"""
|
2022-05-26 19:07:50 +00:00
|
|
|
strategy_provided_features = dh.find_features(dataframe)
|
2022-05-28 09:22:32 +00:00
|
|
|
if 'training_features_list_raw' in dh.data:
|
2022-05-28 09:11:41 +00:00
|
|
|
feature_list = dh.data['training_features_list_raw']
|
|
|
|
else:
|
|
|
|
feature_list = dh.training_features_list
|
|
|
|
if strategy_provided_features != feature_list:
|
2022-05-26 19:07:50 +00:00
|
|
|
raise OperationalException("Trying to access pretrained model with `identifier` "
|
|
|
|
"but found different features furnished by current strategy."
|
|
|
|
"Change `identifer` to train from scratch, or ensure the"
|
|
|
|
"strategy is furnishing the same features as the pretrained"
|
|
|
|
"model")
|
|
|
|
|
2022-05-24 10:01:01 +00:00
|
|
|
def data_cleaning_train(self, dh: FreqaiDataKitchen) -> None:
|
2022-05-22 15:51:49 +00:00
|
|
|
"""
|
2022-05-23 10:07:09 +00:00
|
|
|
Base data cleaning method for train
|
2022-05-22 15:51:49 +00:00
|
|
|
Any function inside this method should drop training data points from the filtered_dataframe
|
|
|
|
based on user decided logic. See FreqaiDataKitchen::remove_outliers() for an example
|
|
|
|
of how outlier data points are dropped from the dataframe used for training.
|
|
|
|
"""
|
2022-05-26 19:07:50 +00:00
|
|
|
|
2022-05-23 10:07:09 +00:00
|
|
|
if self.freqai_info.get('feature_parameters', {}).get('principal_component_analysis'):
|
2022-05-24 10:01:01 +00:00
|
|
|
dh.principal_component_analysis()
|
2022-05-22 15:51:49 +00:00
|
|
|
|
2022-05-23 10:07:09 +00:00
|
|
|
if self.freqai_info.get('feature_parameters', {}).get('use_SVM_to_remove_outliers'):
|
2022-05-24 10:01:01 +00:00
|
|
|
dh.use_SVM_to_remove_outliers(predict=False)
|
2022-05-23 10:07:09 +00:00
|
|
|
|
|
|
|
if self.freqai_info.get('feature_parameters', {}).get('DI_threshold'):
|
2022-05-24 10:01:01 +00:00
|
|
|
dh.data["avg_mean_dist"] = dh.compute_distances()
|
2022-05-23 10:07:09 +00:00
|
|
|
|
2022-05-25 09:31:03 +00:00
|
|
|
# if self.feature_parameters["determine_statistical_distributions"]:
|
|
|
|
# dh.determine_statistical_distributions()
|
|
|
|
# if self.feature_parameters["remove_outliers"]:
|
|
|
|
# dh.remove_outliers(predict=False)
|
|
|
|
|
2022-05-28 09:11:41 +00:00
|
|
|
def data_cleaning_predict(self, dh: FreqaiDataKitchen, dataframe: DataFrame) -> None:
|
2022-05-22 15:51:49 +00:00
|
|
|
"""
|
2022-05-23 10:07:09 +00:00
|
|
|
Base data cleaning method for predict.
|
2022-05-24 10:01:01 +00:00
|
|
|
These functions each modify dh.do_predict, which is a dataframe with equal length
|
2022-05-22 15:51:49 +00:00
|
|
|
to the number of candles coming from and returning to the strategy. Inside do_predict,
|
|
|
|
1 allows prediction and < 0 signals to the strategy that the model is not confident in
|
|
|
|
the prediction.
|
|
|
|
See FreqaiDataKitchen::remove_outliers() for an example
|
|
|
|
of how the do_predict vector is modified. do_predict is ultimately passed back to strategy
|
|
|
|
for buy signals.
|
|
|
|
"""
|
2022-05-23 10:07:09 +00:00
|
|
|
if self.freqai_info.get('feature_parameters', {}).get('principal_component_analysis'):
|
2022-05-28 09:11:41 +00:00
|
|
|
dh.pca_transform(dataframe)
|
2022-05-23 10:07:09 +00:00
|
|
|
|
|
|
|
if self.freqai_info.get('feature_parameters', {}).get('use_SVM_to_remove_outliers'):
|
2022-05-24 10:01:01 +00:00
|
|
|
dh.use_SVM_to_remove_outliers(predict=True)
|
2022-05-23 10:07:09 +00:00
|
|
|
|
|
|
|
if self.freqai_info.get('feature_parameters', {}).get('DI_threshold'):
|
2022-05-25 09:31:03 +00:00
|
|
|
dh.check_if_pred_in_training_spaces()
|
|
|
|
|
|
|
|
# if self.feature_parameters["determine_statistical_distributions"]:
|
|
|
|
# dh.determine_statistical_distributions()
|
|
|
|
# if self.feature_parameters["remove_outliers"]:
|
|
|
|
# dh.remove_outliers(predict=True) # creates dropped index
|
2022-05-22 15:51:49 +00:00
|
|
|
|
2022-05-24 10:01:01 +00:00
|
|
|
def model_exists(self, pair: str, dh: FreqaiDataKitchen, trained_timestamp: int = None,
|
2022-06-15 22:21:15 +00:00
|
|
|
model_filename: str = '', scanning: bool = False) -> 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("/")
|
2022-05-23 19:05:05 +00:00
|
|
|
|
2022-05-24 10:01:01 +00:00
|
|
|
if not self.live:
|
|
|
|
dh.model_filename = model_filename = "cb_" + coin.lower() + "_" + str(trained_timestamp)
|
2022-05-23 19:05:05 +00:00
|
|
|
|
2022-05-24 10:01:01 +00:00
|
|
|
path_to_modelfile = Path(dh.data_path / str(model_filename + "_model.joblib"))
|
2022-05-04 15:42:34 +00:00
|
|
|
file_exists = path_to_modelfile.is_file()
|
2022-06-15 22:21:15 +00:00
|
|
|
if file_exists and not scanning:
|
2022-05-24 10:01:01 +00:00
|
|
|
logger.info("Found model at %s", dh.data_path / dh.model_filename)
|
2022-06-15 22:21:15 +00:00
|
|
|
elif not scanning:
|
2022-05-24 10:01:01 +00:00
|
|
|
logger.info("Could not find model at %s", dh.data_path / dh.model_filename)
|
2022-05-03 08:14:17 +00:00
|
|
|
return file_exists
|
2022-05-19 19:15:58 +00:00
|
|
|
|
2022-05-23 19:05:05 +00:00
|
|
|
def set_full_path(self) -> None:
|
|
|
|
self.full_path = Path(self.config['user_data_dir'] /
|
|
|
|
"models" /
|
2022-05-25 12:40:32 +00:00
|
|
|
str(self.freqai_info.get('identifier')))
|
2022-05-23 19:05:05 +00:00
|
|
|
|
2022-05-19 19:15:58 +00:00
|
|
|
@threaded
|
2022-06-08 04:14:01 +00:00
|
|
|
def retrain_model_on_separate_thread(self, new_trained_timerange: TimeRange, pair: str,
|
2022-05-31 16:42:27 +00:00
|
|
|
strategy: IStrategy, dh: FreqaiDataKitchen,
|
|
|
|
data_load_timerange: TimeRange):
|
2022-06-03 13:19:46 +00:00
|
|
|
"""
|
|
|
|
Retreive data and train model on separate thread. Always called if the model folder already
|
|
|
|
contains a full set of trained models.
|
|
|
|
:params:
|
|
|
|
new_trained_timerange: TimeRange = the timerange to train the model on
|
|
|
|
metadata: dict = strategy provided metadata
|
|
|
|
strategy: IStrategy = user defined strategy object
|
|
|
|
dh: FreqaiDataKitchen = non-persistent data container for current coin/loop
|
|
|
|
data_load_timerange: TimeRange = the amount of data to be loaded for populate_any_indicators
|
|
|
|
(larger than new_trained_timerange so that new_trained_timerange does not contain any NaNs)
|
|
|
|
"""
|
2022-05-19 19:15:58 +00:00
|
|
|
|
|
|
|
# with nostdout():
|
2022-06-03 13:19:46 +00:00
|
|
|
# dh.download_new_data_for_retraining(data_load_timerange, metadata, strategy)
|
|
|
|
# corr_dataframes, base_dataframes = dh.load_pairs_histories(data_load_timerange,
|
|
|
|
# metadata)
|
2022-06-07 17:49:20 +00:00
|
|
|
|
|
|
|
corr_dataframes, base_dataframes = dh.get_base_and_corr_dataframes(data_load_timerange,
|
2022-06-08 04:14:01 +00:00
|
|
|
pair)
|
2022-05-28 16:26:19 +00:00
|
|
|
|
|
|
|
# protecting from common benign errors associated with grabbing new data from exchange:
|
|
|
|
try:
|
|
|
|
unfiltered_dataframe = dh.use_strategy_to_populate_indicators(strategy,
|
|
|
|
corr_dataframes,
|
|
|
|
base_dataframes,
|
2022-06-08 04:14:01 +00:00
|
|
|
pair)
|
2022-05-31 16:42:27 +00:00
|
|
|
unfiltered_dataframe = dh.slice_dataframe(new_trained_timerange, unfiltered_dataframe)
|
|
|
|
|
2022-06-05 02:40:58 +00:00
|
|
|
except Exception as err:
|
|
|
|
logger.exception(err)
|
2022-05-28 16:26:19 +00:00
|
|
|
self.training_on_separate_thread = False
|
|
|
|
self.retrain = False
|
|
|
|
return
|
2022-05-19 19:15:58 +00:00
|
|
|
|
2022-05-28 12:55:07 +00:00
|
|
|
try:
|
2022-06-08 04:14:01 +00:00
|
|
|
model = self.train(unfiltered_dataframe, pair, dh)
|
2022-05-28 12:55:07 +00:00
|
|
|
except ValueError:
|
|
|
|
logger.warning('Value error encountered during training')
|
|
|
|
self.training_on_separate_thread = False
|
|
|
|
self.retrain = False
|
|
|
|
return
|
2022-05-23 19:05:05 +00:00
|
|
|
|
2022-06-08 04:14:01 +00:00
|
|
|
self.data_drawer.pair_dict[pair][
|
2022-05-23 19:05:05 +00:00
|
|
|
'trained_timestamp'] = new_trained_timerange.stopts
|
2022-06-08 04:14:01 +00:00
|
|
|
dh.set_new_model_names(pair, new_trained_timerange)
|
2022-05-28 16:26:19 +00:00
|
|
|
# logger.info('Training queue'
|
|
|
|
# f'{sorted(self.data_drawer.pair_dict.items(), key=lambda item: item[1])}')
|
2022-05-19 19:15:58 +00:00
|
|
|
|
2022-06-08 04:14:01 +00:00
|
|
|
if self.data_drawer.pair_dict[pair]['priority'] == 1:
|
2022-06-01 06:05:38 +00:00
|
|
|
with self.lock:
|
2022-06-08 04:14:01 +00:00
|
|
|
self.data_drawer.pair_to_end_of_training_queue(pair)
|
|
|
|
dh.save_data(model, coin=pair)
|
2022-06-15 22:21:15 +00:00
|
|
|
# self.training_on_separate_thread = False
|
|
|
|
# self.retrain = False
|
2022-05-31 09:58:21 +00:00
|
|
|
|
|
|
|
# each time we finish a training, we check the directory to purge old models.
|
|
|
|
if self.freqai_info.get('purge_old_models', False):
|
|
|
|
self.data_drawer.purge_old_models()
|
|
|
|
|
2022-05-28 12:55:07 +00:00
|
|
|
return
|
2022-05-19 19:15:58 +00:00
|
|
|
|
2022-06-08 04:14:01 +00:00
|
|
|
def train_model_in_series(self, new_trained_timerange: TimeRange, pair: str,
|
2022-05-31 16:42:27 +00:00
|
|
|
strategy: IStrategy, dh: FreqaiDataKitchen,
|
|
|
|
data_load_timerange: TimeRange):
|
2022-06-03 13:19:46 +00:00
|
|
|
"""
|
|
|
|
Retreive data and train model in single threaded mode (only used if model directory is empty
|
|
|
|
upon startup for dry/live )
|
|
|
|
:params:
|
|
|
|
new_trained_timerange: TimeRange = the timerange to train the model on
|
|
|
|
metadata: dict = strategy provided metadata
|
|
|
|
strategy: IStrategy = user defined strategy object
|
|
|
|
dh: FreqaiDataKitchen = non-persistent data container for current coin/loop
|
|
|
|
data_load_timerange: TimeRange = the amount of data to be loaded for populate_any_indicators
|
|
|
|
(larger than new_trained_timerange so that new_trained_timerange does not contain any NaNs)
|
|
|
|
"""
|
|
|
|
# dh.download_new_data_for_retraining(data_load_timerange, metadata, strategy)
|
|
|
|
# corr_dataframes, base_dataframes = dh.load_pairs_histories(data_load_timerange,
|
|
|
|
# metadata)
|
|
|
|
corr_dataframes, base_dataframes = dh.get_base_and_corr_dataframes(data_load_timerange,
|
2022-06-08 04:14:01 +00:00
|
|
|
pair)
|
2022-05-19 19:15:58 +00:00
|
|
|
|
2022-05-24 10:01:01 +00:00
|
|
|
unfiltered_dataframe = dh.use_strategy_to_populate_indicators(strategy,
|
|
|
|
corr_dataframes,
|
|
|
|
base_dataframes,
|
2022-06-08 04:14:01 +00:00
|
|
|
pair)
|
2022-05-19 19:15:58 +00:00
|
|
|
|
2022-05-31 16:42:27 +00:00
|
|
|
unfiltered_dataframe = dh.slice_dataframe(new_trained_timerange, unfiltered_dataframe)
|
|
|
|
|
2022-06-08 04:14:01 +00:00
|
|
|
model = self.train(unfiltered_dataframe, pair, dh)
|
2022-05-23 19:05:05 +00:00
|
|
|
|
2022-06-08 04:14:01 +00:00
|
|
|
self.data_drawer.pair_dict[pair][
|
2022-05-23 19:05:05 +00:00
|
|
|
'trained_timestamp'] = new_trained_timerange.stopts
|
2022-06-08 04:14:01 +00:00
|
|
|
dh.set_new_model_names(pair, new_trained_timerange)
|
|
|
|
self.data_drawer.pair_dict[pair]['first'] = False
|
|
|
|
if self.data_drawer.pair_dict[pair]['priority'] == 1 and self.scanning:
|
|
|
|
with self.lock:
|
|
|
|
self.data_drawer.pair_to_end_of_training_queue(pair)
|
|
|
|
dh.save_data(model, coin=pair)
|
2022-06-16 14:12:38 +00:00
|
|
|
|
|
|
|
if self.freqai_info.get('purge_old_models', False):
|
|
|
|
self.data_drawer.purge_old_models()
|
2022-06-15 22:21:15 +00:00
|
|
|
# self.retrain = False
|
2022-05-23 10:07:09 +00:00
|
|
|
|
2022-05-28 16:26:19 +00:00
|
|
|
# Following methods which are overridden by user made prediction models.
|
2022-05-23 10:07:09 +00:00
|
|
|
# See freqai/prediction_models/CatboostPredictionModlel.py for an example.
|
|
|
|
|
|
|
|
@abstractmethod
|
2022-06-08 04:14:01 +00:00
|
|
|
def train(self, unfiltered_dataframe: DataFrame, pair: str, dh: FreqaiDataKitchen) -> Any:
|
2022-05-23 10:07:09 +00:00
|
|
|
"""
|
|
|
|
Filter the training data and train a model to it. Train makes heavy use of the datahandler
|
|
|
|
for storing, saving, loading, and analyzing the data.
|
|
|
|
:params:
|
|
|
|
:unfiltered_dataframe: Full dataframe for the current training period
|
|
|
|
:metadata: pair metadata from strategy.
|
|
|
|
:returns:
|
|
|
|
:model: Trained model which can be used to inference (self.predict)
|
|
|
|
"""
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def fit(self) -> Any:
|
|
|
|
"""
|
|
|
|
Most regressors use the same function names and arguments e.g. user
|
|
|
|
can drop in LGBMRegressor in place of CatBoostRegressor and all data
|
|
|
|
management will be properly handled by Freqai.
|
|
|
|
:params:
|
2022-05-25 09:31:03 +00:00
|
|
|
data_dictionary: Dict = the dictionary constructed by DataHandler to hold
|
2022-05-23 10:07:09 +00:00
|
|
|
all the training and test data/labels.
|
|
|
|
"""
|
|
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
@abstractmethod
|
2022-05-24 10:01:01 +00:00
|
|
|
def predict(self, dataframe: DataFrame,
|
|
|
|
dh: FreqaiDataKitchen) -> Tuple[npt.ArrayLike, npt.ArrayLike]:
|
2022-05-23 10:07:09 +00:00
|
|
|
"""
|
|
|
|
Filter the prediction features data and predict with it.
|
2022-05-25 09:31:03 +00:00
|
|
|
:param:
|
|
|
|
unfiltered_dataframe: Full dataframe for the current backtest period.
|
|
|
|
dh: FreqaiDataKitchen = Data management/analysis tool assoicated to present pair only
|
2022-05-23 10:07:09 +00:00
|
|
|
:return:
|
|
|
|
:predictions: np.array of predictions
|
|
|
|
:do_predict: np.array of 1s and 0s to indicate places where freqai needed to remove
|
2022-05-25 09:31:03 +00:00
|
|
|
data (NaNs) or felt uncertain about data (i.e. SVM and/or DI index)
|
2022-05-23 10:07:09 +00:00
|
|
|
"""
|
2022-05-24 10:01:01 +00:00
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def make_labels(self, dataframe: DataFrame, dh: FreqaiDataKitchen) -> DataFrame:
|
|
|
|
"""
|
|
|
|
User defines the labels here (target values).
|
|
|
|
:params:
|
2022-05-25 09:31:03 +00:00
|
|
|
dataframe: DataFrame = the full dataframe for the present training period
|
|
|
|
dh: FreqaiDataKitchen = Data management/analysis tool assoicated to present pair only
|
2022-05-24 10:01:01 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
return
|
2022-06-03 13:19:46 +00:00
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def return_values(self, dataframe: DataFrame, dh: FreqaiDataKitchen) -> DataFrame:
|
|
|
|
"""
|
|
|
|
User defines the dataframe to be returned to strategy here.
|
|
|
|
:params:
|
|
|
|
dataframe: DataFrame = the full dataframe for the current prediction (live)
|
|
|
|
or --timerange (backtesting)
|
|
|
|
dh: FreqaiDataKitchen = Data management/analysis tool assoicated to present pair only
|
|
|
|
:returns:
|
|
|
|
dataframe: DataFrame = dataframe filled with user defined data
|
|
|
|
"""
|
|
|
|
|
|
|
|
return
|