2022-05-03 08:14:17 +00:00
|
|
|
import copy
|
2022-12-27 14:37:01 +00:00
|
|
|
import inspect
|
2022-05-04 15:53:40 +00:00
|
|
|
import logging
|
2022-12-16 10:20:37 +00:00
|
|
|
import random
|
2022-05-05 13:35:51 +00:00
|
|
|
import shutil
|
2022-11-22 16:09:09 +00:00
|
|
|
from datetime import datetime, timezone
|
2022-05-04 15:42:34 +00:00
|
|
|
from pathlib import Path
|
2023-01-21 14:01:56 +00:00
|
|
|
from typing import Any, Dict, List, Optional, Tuple
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-03 08:14:17 +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
|
2022-09-28 22:10:18 +00:00
|
|
|
import psutil
|
2023-05-29 11:33:29 +00:00
|
|
|
from datasieve.pipeline import Pipeline
|
2022-11-30 11:41:44 +00:00
|
|
|
from pandas import DataFrame
|
2022-05-04 15:42:34 +00:00
|
|
|
from sklearn.model_selection import train_test_split
|
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
from freqtrade.configuration import TimeRange
|
2023-06-17 07:10:54 +00:00
|
|
|
from freqtrade.constants import DOCS_LINK, Config
|
2022-11-12 09:38:25 +00:00
|
|
|
from freqtrade.data.converter import reduce_dataframe_footprint
|
2022-05-26 22:43:52 +00:00
|
|
|
from freqtrade.exceptions import OperationalException
|
2022-08-09 13:30:25 +00:00
|
|
|
from freqtrade.exchange import timeframe_to_seconds
|
2022-12-27 14:37:01 +00:00
|
|
|
from freqtrade.strategy import merge_informative_pair
|
2022-05-09 13:25:00 +00:00
|
|
|
from freqtrade.strategy.interface import IStrategy
|
2022-08-04 15:00:59 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
pd.set_option("future.no_silent_downcasting", True)
|
2024-04-06 21:34:07 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
SECONDS_IN_DAY = 86400
|
2022-07-10 10:34:09 +00:00
|
|
|
SECONDS_IN_HOUR = 3600
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:53:40 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-05-06 10:54:49 +00:00
|
|
|
class FreqaiDataKitchen:
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
2022-05-23 19:05:05 +00:00
|
|
|
Class designed to analyze data for a single pair. Employed by the IFreqaiModel class.
|
2022-05-03 08:14:17 +00:00
|
|
|
Functionalities include holding, saving, loading, and analyzing the data.
|
2022-07-23 11:32:04 +00:00
|
|
|
|
2022-08-14 18:24:29 +00:00
|
|
|
This object is not persistent, it is reinstantiated for each coin, each time the coin
|
|
|
|
model needs to be inferenced or trained.
|
|
|
|
|
2022-07-23 11:32:04 +00:00
|
|
|
Record of contribution:
|
|
|
|
FreqAI was developed by a group of individuals who all contributed specific skillsets to the
|
|
|
|
project.
|
|
|
|
|
|
|
|
Conception and software development:
|
|
|
|
Robert Caulk @robcaulk
|
|
|
|
|
|
|
|
Theoretical brainstorming:
|
2022-08-02 18:14:02 +00:00
|
|
|
Elin Törnquist @th0rntwig
|
2022-07-23 11:32:04 +00:00
|
|
|
|
|
|
|
Code review, software architecture brainstorming:
|
|
|
|
@xmatthias
|
|
|
|
|
|
|
|
Beta testing and bug reporting:
|
|
|
|
@bloodhunter4rc, Salah Lamkadem @ikonx, @ken11o2, @longyu, @paranoidandy, @smidelis, @smarm
|
2022-08-14 18:24:29 +00:00
|
|
|
Juha Nykänen @suikula, Wagner Costa @wagnercosta, Johan Vlugt @Jooopieeert
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
|
|
|
|
2022-07-03 08:59:38 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
2022-09-18 11:20:36 +00:00
|
|
|
config: Config,
|
2022-07-03 08:59:38 +00:00
|
|
|
live: bool = False,
|
|
|
|
pair: str = "",
|
|
|
|
):
|
2022-08-09 13:30:25 +00:00
|
|
|
self.data: Dict[str, Any] = {}
|
|
|
|
self.data_dictionary: Dict[str, DataFrame] = {}
|
2022-05-03 08:14:17 +00:00
|
|
|
self.config = config
|
2022-08-06 12:55:46 +00:00
|
|
|
self.freqai_config: Dict[str, Any] = config["freqai"]
|
2022-07-03 15:34:44 +00:00
|
|
|
self.full_df: DataFrame = DataFrame()
|
|
|
|
self.append_df: DataFrame = DataFrame()
|
2022-05-23 19:05:05 +00:00
|
|
|
self.data_path = Path()
|
2022-07-02 16:09:38 +00:00
|
|
|
self.label_list: List = []
|
2022-07-26 08:24:14 +00:00
|
|
|
self.training_features_list: List = []
|
2022-05-09 13:25:00 +00:00
|
|
|
self.model_filename: str = ""
|
2022-09-01 10:09:23 +00:00
|
|
|
self.backtesting_results_path = Path()
|
2022-09-03 12:00:01 +00:00
|
|
|
self.backtest_predictions_folder: str = "backtesting_predictions"
|
2022-05-19 17:27:38 +00:00
|
|
|
self.live = live
|
2022-05-23 19:05:05 +00:00
|
|
|
self.pair = pair
|
2022-08-06 12:55:46 +00:00
|
|
|
self.keras: bool = self.freqai_config.get("keras", False)
|
2022-06-03 13:19:46 +00:00
|
|
|
self.set_all_pairs()
|
2022-09-26 02:14:00 +00:00
|
|
|
self.backtest_live_models = config.get("freqai_backtest_live_models", False)
|
2023-05-29 11:33:29 +00:00
|
|
|
self.feature_pipeline = Pipeline()
|
2023-05-26 16:40:14 +00:00
|
|
|
self.label_pipeline = Pipeline()
|
2023-06-08 10:19:42 +00:00
|
|
|
self.DI_values: npt.NDArray = np.array([])
|
2022-09-26 02:14:00 +00:00
|
|
|
|
2022-05-19 17:27:38 +00:00
|
|
|
if not self.live:
|
2022-10-20 17:53:25 +00:00
|
|
|
self.full_path = self.get_full_models_path(self.config)
|
2022-05-05 13:35:51 +00:00
|
|
|
|
2022-11-22 16:09:09 +00:00
|
|
|
if not self.backtest_live_models:
|
2022-10-20 17:53:25 +00:00
|
|
|
self.full_timerange = self.create_fulltimerange(
|
|
|
|
self.config["timerange"], self.freqai_config.get("train_period_days", 0)
|
|
|
|
)
|
2022-09-25 13:35:55 +00:00
|
|
|
(self.training_timeranges, self.backtesting_timeranges) = self.split_timerange(
|
|
|
|
self.full_timerange,
|
|
|
|
config["freqai"]["train_period_days"],
|
|
|
|
config["freqai"]["backtest_period_days"],
|
|
|
|
)
|
2022-07-21 20:11:46 +00:00
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
self.data["extra_returns_per_train"] = self.freqai_config.get("extra_returns_per_train", {})
|
2022-09-28 22:10:18 +00:00
|
|
|
if not self.freqai_config.get("data_kitchen_thread_count", 0):
|
2022-09-29 12:02:00 +00:00
|
|
|
self.thread_count = max(int(psutil.cpu_count() * 2 - 2), 1)
|
2022-09-28 22:10:18 +00:00
|
|
|
else:
|
|
|
|
self.thread_count = self.freqai_config["data_kitchen_thread_count"]
|
2022-08-09 13:30:25 +00:00
|
|
|
self.train_dates: DataFrame = pd.DataFrame()
|
2022-08-09 15:31:38 +00:00
|
|
|
self.unique_classes: Dict[str, list] = {}
|
2022-08-10 13:16:50 +00:00
|
|
|
self.unique_class_list: list = []
|
2022-09-24 16:01:53 +00:00
|
|
|
self.backtest_live_models_data: Dict[str, Any] = {}
|
2022-08-02 18:14:02 +00:00
|
|
|
|
2022-07-03 08:59:38 +00:00
|
|
|
def set_paths(
|
|
|
|
self,
|
|
|
|
pair: str,
|
2023-01-21 14:01:56 +00:00
|
|
|
trained_timestamp: Optional[int] = None,
|
2022-07-03 08:59:38 +00:00
|
|
|
) -> None:
|
2022-06-03 13:19:46 +00:00
|
|
|
"""
|
|
|
|
Set the paths to the data for the present coin/botloop
|
2022-10-10 12:15:30 +00:00
|
|
|
:param metadata: dict = strategy furnished pair metadata
|
|
|
|
:param trained_timestamp: int = timestamp of most recent training
|
2022-06-03 13:19:46 +00:00
|
|
|
"""
|
2022-10-20 17:53:25 +00:00
|
|
|
self.full_path = self.get_full_models_path(self.config)
|
2022-07-03 08:59:38 +00:00
|
|
|
self.data_path = Path(
|
2024-05-12 15:12:20 +00:00
|
|
|
self.full_path / f"sub-train-{pair.split('/')[0]}_{trained_timestamp}"
|
2022-07-03 08:59:38 +00:00
|
|
|
)
|
2022-05-09 13:25:00 +00:00
|
|
|
|
|
|
|
return
|
2022-05-05 13:35:51 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
def make_train_test_datasets(
|
|
|
|
self, filtered_dataframe: DataFrame, labels: DataFrame
|
|
|
|
) -> Dict[Any, Any]:
|
|
|
|
"""
|
|
|
|
Given the dataframe for the full history for training, split the data into
|
|
|
|
training and test data according to user specified parameters in configuration
|
|
|
|
file.
|
2022-10-10 12:15:30 +00:00
|
|
|
:param filtered_dataframe: cleaned dataframe ready to be split.
|
|
|
|
:param labels: cleaned labels ready to be split.
|
2022-05-04 15:42:34 +00:00
|
|
|
"""
|
2022-07-29 06:12:50 +00:00
|
|
|
feat_dict = self.freqai_config["feature_parameters"]
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
if "shuffle" not in self.freqai_config["data_split_parameters"]:
|
|
|
|
self.freqai_config["data_split_parameters"].update({"shuffle": False})
|
2022-09-28 16:23:56 +00:00
|
|
|
|
2022-05-06 14:20:52 +00:00
|
|
|
weights: npt.ArrayLike
|
2022-07-10 10:34:09 +00:00
|
|
|
if feat_dict.get("weight_factor", 0) > 0:
|
2022-05-03 08:14:17 +00:00
|
|
|
weights = self.set_weights_higher_recent(len(filtered_dataframe))
|
2022-05-04 15:42:34 +00:00
|
|
|
else:
|
|
|
|
weights = np.ones(len(filtered_dataframe))
|
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
if self.freqai_config.get("data_split_parameters", {}).get("test_size", 0.1) != 0:
|
2022-07-25 17:40:13 +00:00
|
|
|
(
|
|
|
|
train_features,
|
|
|
|
test_features,
|
|
|
|
train_labels,
|
|
|
|
test_labels,
|
|
|
|
train_weights,
|
|
|
|
test_weights,
|
|
|
|
) = train_test_split(
|
|
|
|
filtered_dataframe[: filtered_dataframe.shape[0]],
|
|
|
|
labels,
|
|
|
|
weights,
|
|
|
|
**self.config["freqai"]["data_split_parameters"],
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
test_labels = np.zeros(2)
|
|
|
|
test_features = pd.DataFrame()
|
|
|
|
test_weights = np.zeros(2)
|
|
|
|
train_features = filtered_dataframe
|
|
|
|
train_labels = labels
|
|
|
|
train_weights = weights
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2023-02-16 17:50:11 +00:00
|
|
|
if feat_dict["shuffle_after_split"]:
|
2022-12-16 10:20:37 +00:00
|
|
|
rint1 = random.randint(0, 100)
|
|
|
|
rint2 = random.randint(0, 100)
|
2024-05-12 15:12:20 +00:00
|
|
|
train_features = train_features.sample(frac=1, random_state=rint1).reset_index(
|
|
|
|
drop=True
|
|
|
|
)
|
2022-12-16 10:20:37 +00:00
|
|
|
train_labels = train_labels.sample(frac=1, random_state=rint1).reset_index(drop=True)
|
2024-05-12 15:12:20 +00:00
|
|
|
train_weights = (
|
|
|
|
pd.DataFrame(train_weights)
|
|
|
|
.sample(frac=1, random_state=rint1)
|
|
|
|
.reset_index(drop=True)
|
|
|
|
.to_numpy()[:, 0]
|
|
|
|
)
|
2022-12-16 10:20:37 +00:00
|
|
|
test_features = test_features.sample(frac=1, random_state=rint2).reset_index(drop=True)
|
|
|
|
test_labels = test_labels.sample(frac=1, random_state=rint2).reset_index(drop=True)
|
2024-05-12 15:12:20 +00:00
|
|
|
test_weights = (
|
|
|
|
pd.DataFrame(test_weights)
|
|
|
|
.sample(frac=1, random_state=rint2)
|
|
|
|
.reset_index(drop=True)
|
|
|
|
.to_numpy()[:, 0]
|
|
|
|
)
|
2022-12-16 10:20:37 +00:00
|
|
|
|
2022-08-29 09:04:58 +00:00
|
|
|
# Simplest way to reverse the order of training and test data:
|
2024-05-12 15:12:20 +00:00
|
|
|
if self.freqai_config["feature_parameters"].get("reverse_train_test_order", False):
|
2022-08-29 09:04:58 +00:00
|
|
|
return self.build_data_dictionary(
|
2024-05-12 15:12:20 +00:00
|
|
|
test_features,
|
|
|
|
train_features,
|
|
|
|
test_labels,
|
|
|
|
train_labels,
|
|
|
|
test_weights,
|
|
|
|
train_weights,
|
|
|
|
)
|
2022-08-29 09:04:58 +00:00
|
|
|
else:
|
|
|
|
return self.build_data_dictionary(
|
2024-05-12 15:12:20 +00:00
|
|
|
train_features,
|
|
|
|
test_features,
|
|
|
|
train_labels,
|
|
|
|
test_labels,
|
|
|
|
train_weights,
|
|
|
|
test_weights,
|
2022-08-29 09:04:58 +00:00
|
|
|
)
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
def filter_features(
|
|
|
|
self,
|
2022-09-07 15:47:27 +00:00
|
|
|
unfiltered_df: DataFrame,
|
2022-05-04 15:42:34 +00:00
|
|
|
training_feature_list: List,
|
2022-07-02 16:09:38 +00:00
|
|
|
label_list: List = list(),
|
2022-05-04 15:42:34 +00:00
|
|
|
training_filter: bool = True,
|
|
|
|
) -> Tuple[DataFrame, DataFrame]:
|
|
|
|
"""
|
2022-07-02 16:09:38 +00:00
|
|
|
Filter the unfiltered dataframe to extract the user requested features/labels and properly
|
2022-05-04 15:42:34 +00:00
|
|
|
remove all NaNs. Any row with a NaN is removed from training dataset or replaced with
|
|
|
|
0s in the prediction dataset. However, prediction dataset do_predict will reflect any
|
2022-05-03 08:14:17 +00:00
|
|
|
row that had a NaN and will shield user from that prediction.
|
2022-10-10 12:15:30 +00:00
|
|
|
|
|
|
|
:param unfiltered_df: the full dataframe for the present training period
|
|
|
|
:param training_feature_list: list, the training feature list constructed by
|
|
|
|
self.build_feature_list() according to user specified
|
|
|
|
parameters in the configuration file.
|
|
|
|
:param labels: the labels for the dataset
|
|
|
|
:param training_filter: boolean which lets the function know if it is training data or
|
|
|
|
prediction data to be filtered.
|
2022-05-03 08:14:17 +00:00
|
|
|
:returns:
|
2022-09-07 15:47:27 +00:00
|
|
|
:filtered_df: dataframe cleaned of NaNs and only containing the user
|
2022-05-03 08:14:17 +00:00
|
|
|
requested feature set.
|
|
|
|
:labels: labels cleaned of NaNs.
|
2022-05-04 15:42:34 +00:00
|
|
|
"""
|
2022-09-07 15:47:27 +00:00
|
|
|
filtered_df = unfiltered_df.filter(training_feature_list, axis=1)
|
|
|
|
filtered_df = filtered_df.replace([np.inf, -np.inf], np.nan)
|
2022-07-02 16:09:38 +00:00
|
|
|
|
2022-09-30 13:43:05 +00:00
|
|
|
drop_index = pd.isnull(filtered_df).any(axis=1) # get the rows that have NaNs,
|
2024-04-06 21:34:07 +00:00
|
|
|
drop_index = drop_index.replace(True, 1).replace(False, 0).infer_objects(copy=False)
|
2024-05-12 15:12:20 +00:00
|
|
|
if training_filter:
|
2022-08-06 12:55:46 +00:00
|
|
|
# we don't care about total row number (total no. datapoints) in training, we only care
|
2022-05-04 15:42:34 +00:00
|
|
|
# about removing any row with NaNs
|
2022-08-09 13:30:25 +00:00
|
|
|
# if labels has multiple columns (user wants to train multiple modelEs), we detect here
|
2022-09-07 15:47:27 +00:00
|
|
|
labels = unfiltered_df.filter(label_list, axis=1)
|
2022-09-30 13:43:05 +00:00
|
|
|
drop_index_labels = pd.isnull(labels).any(axis=1)
|
2024-05-12 15:12:20 +00:00
|
|
|
drop_index_labels = (
|
|
|
|
drop_index_labels.replace(True, 1).replace(False, 0).infer_objects(copy=False)
|
|
|
|
)
|
|
|
|
dates = unfiltered_df["date"]
|
2022-09-07 15:47:27 +00:00
|
|
|
filtered_df = filtered_df[
|
2022-05-04 15:42:34 +00:00
|
|
|
(drop_index == 0) & (drop_index_labels == 0)
|
|
|
|
] # dropping values
|
|
|
|
labels = labels[
|
|
|
|
(drop_index == 0) & (drop_index_labels == 0)
|
|
|
|
] # assuming the labels depend entirely on the dataframe here.
|
2024-05-12 15:12:20 +00:00
|
|
|
self.train_dates = dates[(drop_index == 0) & (drop_index_labels == 0)]
|
2022-05-31 16:42:27 +00:00
|
|
|
logger.info(
|
2023-03-18 16:32:07 +00:00
|
|
|
f"{self.pair}: dropped {len(unfiltered_df) - len(filtered_df)} training points"
|
2022-09-07 15:47:27 +00:00
|
|
|
f" due to NaNs in populated dataset {len(unfiltered_df)}."
|
2022-05-31 16:42:27 +00:00
|
|
|
)
|
2023-12-10 11:26:39 +00:00
|
|
|
if len(filtered_df) == 0 and not self.live:
|
2023-09-19 10:24:44 +00:00
|
|
|
raise OperationalException(
|
|
|
|
f"{self.pair}: all training data dropped due to NaNs. "
|
|
|
|
"You likely did not download enough training data prior "
|
|
|
|
"to your backtest timerange. Hint:\n"
|
2023-09-23 10:02:34 +00:00
|
|
|
f"{DOCS_LINK}/freqai-running/"
|
2023-09-19 10:24:44 +00:00
|
|
|
"#downloading-data-to-cover-the-full-backtest-period"
|
|
|
|
)
|
2022-09-07 15:47:27 +00:00
|
|
|
if (1 - len(filtered_df) / len(unfiltered_df)) > 0.1 and self.live:
|
|
|
|
worst_indicator = str(unfiltered_df.count().idxmin())
|
2022-05-31 16:42:27 +00:00
|
|
|
logger.warning(
|
2024-01-24 19:25:25 +00:00
|
|
|
f" {(1 - len(filtered_df) / len(unfiltered_df)) * 100:.0f} percent "
|
2022-07-05 10:42:32 +00:00
|
|
|
" of training data dropped due to NaNs, model may perform inconsistent "
|
|
|
|
f"with expectations. Verify {worst_indicator}"
|
2022-05-31 16:42:27 +00:00
|
|
|
)
|
2022-05-04 15:42:34 +00:00
|
|
|
self.data["filter_drop_index_training"] = drop_index
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
else:
|
|
|
|
# we are backtesting so we need to preserve row number to send back to strategy,
|
|
|
|
# so now we use do_predict to avoid any prediction based on a NaN
|
2022-09-30 13:43:05 +00:00
|
|
|
drop_index = pd.isnull(filtered_df).any(axis=1)
|
2022-05-04 15:42:34 +00:00
|
|
|
self.data["filter_drop_index_prediction"] = drop_index
|
2022-09-07 15:47:27 +00:00
|
|
|
filtered_df.fillna(0, inplace=True)
|
2022-05-04 15:42:34 +00:00
|
|
|
# replacing all NaNs with zeros to avoid issues in 'prediction', but any prediction
|
|
|
|
# that was based on a single NaN is ultimately protected from buys with do_predict
|
2022-05-03 08:14:17 +00:00
|
|
|
drop_index = ~drop_index
|
2022-05-04 15:42:34 +00:00
|
|
|
self.do_predict = np.array(drop_index.replace(True, 1).replace(False, 0))
|
2022-06-26 17:02:17 +00:00
|
|
|
if (len(self.do_predict) - self.do_predict.sum()) > 0:
|
|
|
|
logger.info(
|
|
|
|
"dropped %s of %s prediction data points due to NaNs.",
|
|
|
|
len(self.do_predict) - self.do_predict.sum(),
|
2022-09-07 15:47:27 +00:00
|
|
|
len(filtered_df),
|
2022-06-26 17:02:17 +00:00
|
|
|
)
|
2022-07-02 16:09:38 +00:00
|
|
|
labels = []
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-09-07 15:47:27 +00:00
|
|
|
return filtered_df, labels
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
def build_data_dictionary(
|
|
|
|
self,
|
|
|
|
train_df: DataFrame,
|
|
|
|
test_df: DataFrame,
|
|
|
|
train_labels: DataFrame,
|
|
|
|
test_labels: DataFrame,
|
|
|
|
train_weights: Any,
|
|
|
|
test_weights: Any,
|
|
|
|
) -> Dict:
|
|
|
|
self.data_dictionary = {
|
|
|
|
"train_features": train_df,
|
|
|
|
"test_features": test_df,
|
|
|
|
"train_labels": train_labels,
|
|
|
|
"test_labels": test_labels,
|
|
|
|
"train_weights": train_weights,
|
|
|
|
"test_weights": test_weights,
|
2024-05-12 15:12:20 +00:00
|
|
|
"train_dates": self.train_dates,
|
2022-05-04 15:42:34 +00:00
|
|
|
}
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
return self.data_dictionary
|
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
def split_timerange(
|
2022-08-09 13:30:25 +00:00
|
|
|
self, tr: str, train_split: int = 28, bt_split: float = 7
|
2022-05-04 15:42:34 +00:00
|
|
|
) -> Tuple[list, list]:
|
|
|
|
"""
|
2022-05-03 08:14:17 +00:00
|
|
|
Function which takes a single time range (tr) and splits it
|
|
|
|
into sub timeranges to train and backtest on based on user input
|
|
|
|
tr: str, full timerange to train on
|
|
|
|
train_split: the period length for the each training (days). Specified in user
|
|
|
|
configuration file
|
2022-08-09 13:30:25 +00:00
|
|
|
bt_split: the backtesting length (days). Specified in user configuration file
|
2022-05-04 15:42:34 +00:00
|
|
|
"""
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-07-19 14:16:44 +00:00
|
|
|
if not isinstance(train_split, int) or train_split < 1:
|
|
|
|
raise OperationalException(
|
2022-08-06 12:55:46 +00:00
|
|
|
f"train_period_days must be an integer greater than 0. Got {train_split}."
|
2022-07-19 14:16:44 +00:00
|
|
|
)
|
2022-07-10 10:34:09 +00:00
|
|
|
train_period_days = train_split * SECONDS_IN_DAY
|
2022-05-03 08:14:17 +00:00
|
|
|
bt_period = bt_split * SECONDS_IN_DAY
|
|
|
|
|
|
|
|
full_timerange = TimeRange.parse_timerange(tr)
|
2022-05-06 10:54:49 +00:00
|
|
|
config_timerange = TimeRange.parse_timerange(self.config["timerange"])
|
2022-05-17 17:50:06 +00:00
|
|
|
if config_timerange.stopts == 0:
|
2024-05-12 15:12:20 +00:00
|
|
|
config_timerange.stopts = int(datetime.now(tz=timezone.utc).timestamp())
|
2022-05-03 08:14:17 +00:00
|
|
|
timerange_train = copy.deepcopy(full_timerange)
|
|
|
|
timerange_backtest = copy.deepcopy(full_timerange)
|
|
|
|
|
|
|
|
tr_training_list = []
|
|
|
|
tr_backtesting_list = []
|
2022-05-29 15:44:35 +00:00
|
|
|
tr_training_list_timerange = []
|
|
|
|
tr_backtesting_list_timerange = []
|
2022-05-03 08:14:17 +00:00
|
|
|
first = True
|
2022-07-22 15:37:51 +00:00
|
|
|
|
2022-05-03 08:14:17 +00:00
|
|
|
while True:
|
2022-05-04 15:42:34 +00:00
|
|
|
if not first:
|
2022-08-09 13:30:25 +00:00
|
|
|
timerange_train.startts = timerange_train.startts + int(bt_period)
|
2022-07-10 10:34:09 +00:00
|
|
|
timerange_train.stopts = timerange_train.startts + train_period_days
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
first = False
|
2022-11-10 17:26:14 +00:00
|
|
|
tr_training_list.append(timerange_train.timerange_str)
|
2022-05-29 15:44:35 +00:00
|
|
|
tr_training_list_timerange.append(copy.deepcopy(timerange_train))
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-04 15:42:34 +00:00
|
|
|
# associated backtest period
|
2022-05-06 11:06:54 +00:00
|
|
|
timerange_backtest.startts = timerange_train.stopts
|
2022-08-09 13:30:25 +00:00
|
|
|
timerange_backtest.stopts = timerange_backtest.startts + int(bt_period)
|
2022-05-06 13:10:11 +00:00
|
|
|
|
2022-05-06 10:54:49 +00:00
|
|
|
if timerange_backtest.stopts > config_timerange.stopts:
|
|
|
|
timerange_backtest.stopts = config_timerange.stopts
|
|
|
|
|
2022-11-10 17:26:14 +00:00
|
|
|
tr_backtesting_list.append(timerange_backtest.timerange_str)
|
2022-05-29 15:44:35 +00:00
|
|
|
tr_backtesting_list_timerange.append(copy.deepcopy(timerange_backtest))
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-06 10:54:49 +00:00
|
|
|
# ensure we are predicting on exactly same amount of data as requested by user defined
|
|
|
|
# --timerange
|
|
|
|
if timerange_backtest.stopts == config_timerange.stopts:
|
|
|
|
break
|
|
|
|
|
2022-05-29 15:44:35 +00:00
|
|
|
# print(tr_training_list, tr_backtesting_list)
|
|
|
|
return tr_training_list_timerange, tr_backtesting_list_timerange
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-29 15:44:35 +00:00
|
|
|
def slice_dataframe(self, timerange: TimeRange, df: DataFrame) -> DataFrame:
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
|
|
|
Given a full dataframe, extract the user desired window
|
2022-08-06 12:55:46 +00:00
|
|
|
:param tr: timerange string that we wish to extract from df
|
|
|
|
:param df: Dataframe containing all candles to run the entire backtest. Here
|
|
|
|
it is sliced down to just the present training period.
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
2022-09-04 22:07:05 +00:00
|
|
|
if not self.live:
|
2022-12-01 15:53:19 +00:00
|
|
|
df = df.loc[(df["date"] >= timerange.startdt) & (df["date"] < timerange.stopdt), :]
|
|
|
|
else:
|
|
|
|
df = df.loc[df["date"] >= timerange.startdt, :]
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
return df
|
|
|
|
|
2022-07-02 16:09:38 +00:00
|
|
|
def find_features(self, dataframe: DataFrame) -> None:
|
2022-06-03 13:19:46 +00:00
|
|
|
"""
|
|
|
|
Find features in the strategy provided dataframe
|
2022-08-06 12:55:46 +00:00
|
|
|
:param dataframe: DataFrame = strategy provided dataframe
|
|
|
|
:return:
|
2022-06-03 13:19:46 +00:00
|
|
|
features: list = the features to be used for training/prediction
|
|
|
|
"""
|
2022-05-17 16:15:03 +00:00
|
|
|
column_names = dataframe.columns
|
2022-07-03 08:59:38 +00:00
|
|
|
features = [c for c in column_names if "%" in c]
|
2022-09-30 22:22:05 +00:00
|
|
|
|
2022-05-28 09:11:41 +00:00
|
|
|
if not features:
|
|
|
|
raise OperationalException("Could not find any features!")
|
2022-07-02 16:09:38 +00:00
|
|
|
|
|
|
|
self.training_features_list = features
|
2022-09-25 09:18:10 +00:00
|
|
|
|
|
|
|
def find_labels(self, dataframe: DataFrame) -> None:
|
|
|
|
column_names = dataframe.columns
|
|
|
|
labels = [c for c in column_names if "&" in c]
|
2022-07-02 16:09:38 +00:00
|
|
|
self.label_list = labels
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-05-06 14:20:52 +00:00
|
|
|
def set_weights_higher_recent(self, num_weights: int) -> npt.ArrayLike:
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
|
|
|
Set weights so that recent data is more heavily weighted during
|
|
|
|
training than older data.
|
|
|
|
"""
|
2022-07-19 15:49:18 +00:00
|
|
|
wfactor = self.config["freqai"]["feature_parameters"]["weight_factor"]
|
2022-07-21 09:25:28 +00:00
|
|
|
weights = np.exp(-np.arange(num_weights) / (wfactor * num_weights))[::-1]
|
2022-05-03 08:14:17 +00:00
|
|
|
return weights
|
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
def get_predictions_to_append(
|
|
|
|
self, predictions: DataFrame, do_predict: npt.ArrayLike, dataframe_backtest: DataFrame
|
|
|
|
) -> DataFrame:
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
2022-08-31 14:23:48 +00:00
|
|
|
Get backtest prediction from current backtest period
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
|
|
|
|
2022-07-29 15:27:35 +00:00
|
|
|
append_df = DataFrame()
|
2022-08-06 11:51:19 +00:00
|
|
|
for label in predictions.columns:
|
2022-07-29 15:27:35 +00:00
|
|
|
append_df[label] = predictions[label]
|
2022-08-06 11:51:19 +00:00
|
|
|
if append_df[label].dtype == object:
|
|
|
|
continue
|
2022-11-03 16:27:56 +00:00
|
|
|
if "labels_mean" in self.data:
|
|
|
|
append_df[f"{label}_mean"] = self.data["labels_mean"][label]
|
|
|
|
if "labels_std" in self.data:
|
|
|
|
append_df[f"{label}_std"] = self.data["labels_std"][label]
|
2022-05-03 08:14:17 +00:00
|
|
|
|
2022-10-20 11:05:37 +00:00
|
|
|
for extra_col in self.data["extra_returns_per_train"]:
|
2022-10-30 08:19:59 +00:00
|
|
|
append_df[f"{extra_col}"] = self.data["extra_returns_per_train"][extra_col]
|
2022-10-20 11:05:37 +00:00
|
|
|
|
2022-07-29 15:27:35 +00:00
|
|
|
append_df["do_predict"] = do_predict
|
2022-07-29 06:12:50 +00:00
|
|
|
if self.freqai_config["feature_parameters"].get("DI_threshold", 0) > 0:
|
2022-07-29 15:27:35 +00:00
|
|
|
append_df["DI_values"] = self.DI_values
|
2022-07-03 15:34:44 +00:00
|
|
|
|
2024-01-19 16:46:34 +00:00
|
|
|
user_cols = [col for col in dataframe_backtest.columns if col.startswith("%%")]
|
|
|
|
cols = ["date"]
|
|
|
|
cols.extend(user_cols)
|
|
|
|
|
2022-11-08 13:32:18 +00:00
|
|
|
dataframe_backtest.reset_index(drop=True, inplace=True)
|
2024-01-19 16:46:34 +00:00
|
|
|
merged_df = pd.concat([dataframe_backtest[cols], append_df], axis=1)
|
2022-11-08 13:32:18 +00:00
|
|
|
return merged_df
|
2022-08-31 14:23:48 +00:00
|
|
|
|
|
|
|
def append_predictions(self, append_df: DataFrame) -> None:
|
|
|
|
"""
|
|
|
|
Append backtest prediction from current backtest period to all previous periods
|
|
|
|
"""
|
|
|
|
|
2022-07-03 15:34:44 +00:00
|
|
|
if self.full_df.empty:
|
2022-07-29 15:27:35 +00:00
|
|
|
self.full_df = append_df
|
2022-07-03 15:34:44 +00:00
|
|
|
else:
|
2022-11-08 21:20:39 +00:00
|
|
|
self.full_df = pd.concat([self.full_df, append_df], axis=0, ignore_index=True)
|
2022-07-03 15:34:44 +00:00
|
|
|
|
|
|
|
def fill_predictions(self, dataframe):
|
2022-05-03 08:14:17 +00:00
|
|
|
"""
|
|
|
|
Back fill values to before the backtesting range so that the dataframe matches size
|
|
|
|
when it goes back to the strategy. These rows are not included in the backtest.
|
|
|
|
"""
|
2024-05-12 15:12:20 +00:00
|
|
|
to_keep = [
|
|
|
|
col for col in dataframe.columns if not col.startswith("&") and not col.startswith("%%")
|
|
|
|
]
|
|
|
|
self.return_dataframe = pd.merge(dataframe[to_keep], self.full_df, how="left", on="date")
|
|
|
|
self.return_dataframe[self.full_df.columns] = self.return_dataframe[
|
|
|
|
self.full_df.columns
|
|
|
|
].fillna(value=0)
|
2022-07-03 15:34:44 +00:00
|
|
|
self.full_df = DataFrame()
|
2022-05-03 08:14:17 +00:00
|
|
|
|
|
|
|
return
|
2022-05-04 15:42:34 +00:00
|
|
|
|
2022-07-10 10:34:09 +00:00
|
|
|
def create_fulltimerange(self, backtest_tr: str, backtest_period_days: int) -> str:
|
2022-07-19 14:16:44 +00:00
|
|
|
if not isinstance(backtest_period_days, int):
|
2022-07-21 09:25:28 +00:00
|
|
|
raise OperationalException("backtest_period_days must be an integer")
|
2022-07-19 14:16:44 +00:00
|
|
|
|
|
|
|
if backtest_period_days < 0:
|
2022-07-21 09:25:28 +00:00
|
|
|
raise OperationalException("backtest_period_days must be positive")
|
2022-07-19 14:16:44 +00:00
|
|
|
|
2022-05-05 13:35:51 +00:00
|
|
|
backtest_timerange = TimeRange.parse_timerange(backtest_tr)
|
|
|
|
|
2022-05-17 17:50:06 +00:00
|
|
|
if backtest_timerange.stopts == 0:
|
2022-07-21 11:02:52 +00:00
|
|
|
# typically open ended time ranges do work, however, there are some edge cases where
|
2022-08-06 12:55:46 +00:00
|
|
|
# it does not. accommodating these kinds of edge cases just to allow open-ended
|
2022-07-21 11:02:52 +00:00
|
|
|
# timerange is not high enough priority to warrant the effort. It is safer for now
|
|
|
|
# to simply ask user to add their end date
|
2024-05-12 15:12:20 +00:00
|
|
|
raise OperationalException(
|
|
|
|
"FreqAI backtesting does not allow open ended timeranges. "
|
|
|
|
"Please indicate the end date of your desired backtesting. "
|
|
|
|
"timerange."
|
|
|
|
)
|
2022-07-21 11:02:52 +00:00
|
|
|
# backtest_timerange.stopts = int(
|
2022-09-03 13:52:29 +00:00
|
|
|
# datetime.now(tz=timezone.utc).timestamp()
|
2022-07-21 11:02:52 +00:00
|
|
|
# )
|
2022-05-17 17:50:06 +00:00
|
|
|
|
2022-07-21 09:25:28 +00:00
|
|
|
backtest_timerange.startts = (
|
|
|
|
backtest_timerange.startts - backtest_period_days * SECONDS_IN_DAY
|
|
|
|
)
|
2022-11-10 17:26:14 +00:00
|
|
|
full_timerange = backtest_timerange.timerange_str
|
2022-05-09 13:25:00 +00:00
|
|
|
config_path = Path(self.config["config_files"][0])
|
|
|
|
|
2022-05-05 13:35:51 +00:00
|
|
|
if not self.full_path.is_dir():
|
|
|
|
self.full_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
shutil.copy(
|
2022-05-15 13:26:09 +00:00
|
|
|
config_path.resolve(),
|
2022-05-09 13:25:00 +00:00
|
|
|
Path(self.full_path / config_path.parts[-1]),
|
2022-05-05 13:35:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
return full_timerange
|
|
|
|
|
2022-06-17 12:55:40 +00:00
|
|
|
def check_if_model_expired(self, trained_timestamp: int) -> bool:
|
2022-06-17 14:16:23 +00:00
|
|
|
"""
|
|
|
|
A model age checker to determine if the model is trustworthy based on user defined
|
|
|
|
`expiration_hours` in the configuration file.
|
2022-08-06 12:55:46 +00:00
|
|
|
:param trained_timestamp: int = The time of training for the most recent model.
|
|
|
|
:return:
|
|
|
|
bool = If the model is expired or not.
|
2022-06-17 14:16:23 +00:00
|
|
|
"""
|
2022-09-03 13:52:29 +00:00
|
|
|
time = datetime.now(tz=timezone.utc).timestamp()
|
2022-06-17 12:55:40 +00:00
|
|
|
elapsed_time = (time - trained_timestamp) / 3600 # hours
|
2022-07-03 08:59:38 +00:00
|
|
|
max_time = self.freqai_config.get("expiration_hours", 0)
|
2022-06-21 06:12:51 +00:00
|
|
|
if max_time > 0:
|
|
|
|
return elapsed_time > max_time
|
2022-06-28 13:12:25 +00:00
|
|
|
else:
|
2022-06-21 06:12:51 +00:00
|
|
|
return False
|
2022-06-17 12:55:40 +00:00
|
|
|
|
2022-07-03 08:59:38 +00:00
|
|
|
def check_if_new_training_required(
|
|
|
|
self, trained_timestamp: int
|
|
|
|
) -> Tuple[bool, TimeRange, TimeRange]:
|
2022-09-03 13:52:29 +00:00
|
|
|
time = datetime.now(tz=timezone.utc).timestamp()
|
2022-05-28 09:38:57 +00:00
|
|
|
trained_timerange = TimeRange()
|
2022-05-31 16:42:27 +00:00
|
|
|
data_load_timerange = TimeRange()
|
|
|
|
|
2022-08-09 13:30:25 +00:00
|
|
|
timeframes = self.freqai_config["feature_parameters"].get("include_timeframes")
|
2022-05-31 16:42:27 +00:00
|
|
|
|
2022-08-09 13:30:25 +00:00
|
|
|
max_tf_seconds = 0
|
|
|
|
for tf in timeframes:
|
|
|
|
secs = timeframe_to_seconds(tf)
|
|
|
|
if secs > max_tf_seconds:
|
|
|
|
max_tf_seconds = secs
|
|
|
|
|
|
|
|
# We notice that users like to use exotic indicators where
|
|
|
|
# they do not know the required timeperiod. Here we include a factor
|
|
|
|
# of safety by multiplying the user considered "max" by 2.
|
2024-05-12 15:12:20 +00:00
|
|
|
max_period = self.config.get("startup_candle_count", 20) * 2
|
2022-08-09 13:30:25 +00:00
|
|
|
additional_seconds = max_period * max_tf_seconds
|
2022-06-03 13:19:46 +00:00
|
|
|
|
2022-05-23 19:05:05 +00:00
|
|
|
if trained_timestamp != 0:
|
2022-07-10 10:34:09 +00:00
|
|
|
elapsed_time = (time - trained_timestamp) / SECONDS_IN_HOUR
|
|
|
|
retrain = elapsed_time > self.freqai_config.get("live_retrain_hours", 0)
|
2022-05-22 22:06:26 +00:00
|
|
|
if retrain:
|
2022-07-03 08:59:38 +00:00
|
|
|
trained_timerange.startts = int(
|
2022-07-10 10:34:09 +00:00
|
|
|
time - self.freqai_config.get("train_period_days", 0) * SECONDS_IN_DAY
|
2022-07-03 08:59:38 +00:00
|
|
|
)
|
2022-05-23 19:05:05 +00:00
|
|
|
trained_timerange.stopts = int(time)
|
2022-05-31 16:42:27 +00:00
|
|
|
# we want to load/populate indicators on more data than we plan to train on so
|
|
|
|
# because most of the indicators have a rolling timeperiod, and are thus NaNs
|
|
|
|
# unless they have data further back in time before the start of the train period
|
2022-07-03 08:59:38 +00:00
|
|
|
data_load_timerange.startts = int(
|
|
|
|
time
|
2022-07-10 10:34:09 +00:00
|
|
|
- self.freqai_config.get("train_period_days", 0) * SECONDS_IN_DAY
|
2022-07-03 08:59:38 +00:00
|
|
|
- additional_seconds
|
|
|
|
)
|
2022-05-31 16:42:27 +00:00
|
|
|
data_load_timerange.stopts = int(time)
|
2022-05-22 22:06:26 +00:00
|
|
|
else: # user passed no live_trained_timerange in config
|
2022-07-03 08:59:38 +00:00
|
|
|
trained_timerange.startts = int(
|
2022-08-06 12:55:46 +00:00
|
|
|
time - self.freqai_config.get("train_period_days", 0) * SECONDS_IN_DAY
|
2022-07-03 08:59:38 +00:00
|
|
|
)
|
2022-05-22 15:51:49 +00:00
|
|
|
trained_timerange.stopts = int(time)
|
2022-05-31 16:42:27 +00:00
|
|
|
|
2022-07-03 08:59:38 +00:00
|
|
|
data_load_timerange.startts = int(
|
|
|
|
time
|
2022-07-10 10:34:09 +00:00
|
|
|
- self.freqai_config.get("train_period_days", 0) * SECONDS_IN_DAY
|
2022-07-03 08:59:38 +00:00
|
|
|
- additional_seconds
|
|
|
|
)
|
2022-05-31 16:42:27 +00:00
|
|
|
data_load_timerange.stopts = int(time)
|
2022-05-22 15:51:49 +00:00
|
|
|
retrain = True
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-05-31 16:42:27 +00:00
|
|
|
return retrain, trained_timerange, data_load_timerange
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-09-25 13:35:55 +00:00
|
|
|
def set_new_model_names(self, pair: str, timestamp_id: int):
|
2022-06-08 04:14:01 +00:00
|
|
|
coin, _ = pair.split("/")
|
2024-05-12 15:12:20 +00:00
|
|
|
self.data_path = Path(self.full_path / f"sub-train-{pair.split('/')[0]}_{timestamp_id}")
|
2022-05-23 19:05:05 +00:00
|
|
|
|
2022-09-25 13:35:55 +00:00
|
|
|
self.model_filename = f"cb_{coin.lower()}_{timestamp_id}"
|
2022-05-25 12:40:32 +00:00
|
|
|
|
2022-06-03 13:19:46 +00:00
|
|
|
def set_all_pairs(self) -> None:
|
2022-07-21 09:25:28 +00:00
|
|
|
self.all_pairs = copy.deepcopy(
|
2022-07-29 06:12:50 +00:00
|
|
|
self.freqai_config["feature_parameters"].get("include_corr_pairlist", [])
|
2022-07-21 09:25:28 +00:00
|
|
|
)
|
2022-07-03 08:59:38 +00:00
|
|
|
for pair in self.config.get("exchange", "").get("pair_whitelist"):
|
2022-06-03 13:19:46 +00:00
|
|
|
if pair not in self.all_pairs:
|
|
|
|
self.all_pairs.append(pair)
|
|
|
|
|
2022-10-20 14:30:32 +00:00
|
|
|
def extract_corr_pair_columns_from_populated_indicators(
|
2024-05-12 15:12:20 +00:00
|
|
|
self, dataframe: DataFrame
|
2022-10-20 14:30:32 +00:00
|
|
|
) -> Dict[str, DataFrame]:
|
|
|
|
"""
|
|
|
|
Find the columns of the dataframe corresponding to the corr_pairlist, save them
|
|
|
|
in a dictionary to be reused and attached to other pairs.
|
2022-10-29 20:26:49 +00:00
|
|
|
|
|
|
|
:param dataframe: fully populated dataframe (current pair + corr_pairs)
|
|
|
|
:return: corr_dataframes, dictionary of dataframes to be attached
|
|
|
|
to other pairs in same candle.
|
2022-10-20 14:30:32 +00:00
|
|
|
"""
|
|
|
|
corr_dataframes: Dict[str, DataFrame] = {}
|
|
|
|
pairs = self.freqai_config["feature_parameters"].get("include_corr_pairlist", [])
|
|
|
|
|
|
|
|
for pair in pairs:
|
2024-05-12 15:12:20 +00:00
|
|
|
pair = pair.replace(":", "") # lightgbm does not like colons
|
|
|
|
pair_cols = [
|
|
|
|
col for col in dataframe.columns if col.startswith("%") and f"{pair}_" in col
|
|
|
|
]
|
2023-01-09 19:04:36 +00:00
|
|
|
|
2022-11-02 19:20:35 +00:00
|
|
|
if pair_cols:
|
2024-05-12 15:12:20 +00:00
|
|
|
pair_cols.insert(0, "date")
|
2022-11-03 20:03:48 +00:00
|
|
|
corr_dataframes[pair] = dataframe.filter(pair_cols, axis=1)
|
2022-10-20 14:30:32 +00:00
|
|
|
|
|
|
|
return corr_dataframes
|
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
def attach_corr_pair_columns(
|
|
|
|
self, dataframe: DataFrame, corr_dataframes: Dict[str, DataFrame], current_pair: str
|
|
|
|
) -> DataFrame:
|
2022-10-20 14:30:32 +00:00
|
|
|
"""
|
|
|
|
Attach the existing corr_pair dataframes to the current pair dataframe before training
|
2022-10-29 20:26:49 +00:00
|
|
|
|
|
|
|
:param dataframe: current pair strategy dataframe, indicators populated already
|
|
|
|
:param corr_dataframes: dictionary of saved dataframes from earlier in the same candle
|
|
|
|
:param current_pair: current pair to which we will attach corr pair dataframe
|
2022-10-20 14:30:32 +00:00
|
|
|
:return:
|
|
|
|
:dataframe: current pair dataframe of populated indicators, concatenated with corr_pairs
|
|
|
|
ready for training
|
|
|
|
"""
|
|
|
|
pairs = self.freqai_config["feature_parameters"].get("include_corr_pairlist", [])
|
2024-05-12 15:12:20 +00:00
|
|
|
current_pair = current_pair.replace(":", "")
|
2022-10-20 14:30:32 +00:00
|
|
|
for pair in pairs:
|
2024-05-12 15:12:20 +00:00
|
|
|
pair = pair.replace(":", "") # lightgbm does not work with colons
|
2022-10-29 20:26:49 +00:00
|
|
|
if current_pair != pair:
|
2024-05-12 15:12:20 +00:00
|
|
|
dataframe = dataframe.merge(corr_dataframes[pair], how="left", on="date")
|
2022-10-20 14:30:32 +00:00
|
|
|
|
|
|
|
return dataframe
|
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
def get_pair_data_for_features(
|
|
|
|
self,
|
|
|
|
pair: str,
|
|
|
|
tf: str,
|
|
|
|
strategy: IStrategy,
|
|
|
|
corr_dataframes: dict = {},
|
|
|
|
base_dataframes: dict = {},
|
|
|
|
is_corr_pairs: bool = False,
|
|
|
|
) -> DataFrame:
|
2022-12-27 14:37:01 +00:00
|
|
|
"""
|
|
|
|
Get the data for the pair. If it's not in the dictionary, get it from the data provider
|
|
|
|
:param pair: str = pair to get data for
|
|
|
|
:param tf: str = timeframe to get data for
|
|
|
|
:param strategy: IStrategy = user defined strategy object
|
|
|
|
:param corr_dataframes: dict = dict containing the df pair dataframes
|
|
|
|
(for user defined timeframes)
|
|
|
|
:param base_dataframes: dict = dict containing the current pair dataframes
|
|
|
|
(for user defined timeframes)
|
|
|
|
:param is_corr_pairs: bool = whether the pair is a corr pair or not
|
|
|
|
:return: dataframe = dataframe containing the pair data
|
|
|
|
"""
|
|
|
|
if is_corr_pairs:
|
|
|
|
dataframe = corr_dataframes[pair][tf]
|
|
|
|
if not dataframe.empty:
|
|
|
|
return dataframe
|
|
|
|
else:
|
|
|
|
dataframe = strategy.dp.get_pair_dataframe(pair=pair, timeframe=tf)
|
|
|
|
return dataframe
|
|
|
|
else:
|
|
|
|
dataframe = base_dataframes[tf]
|
|
|
|
if not dataframe.empty:
|
|
|
|
return dataframe
|
|
|
|
else:
|
|
|
|
dataframe = strategy.dp.get_pair_dataframe(pair=pair, timeframe=tf)
|
|
|
|
return dataframe
|
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
def merge_features(
|
|
|
|
self, df_main: DataFrame, df_to_merge: DataFrame, tf: str, timeframe_inf: str, suffix: str
|
|
|
|
) -> DataFrame:
|
2022-12-27 14:37:01 +00:00
|
|
|
"""
|
|
|
|
Merge the features of the dataframe and remove HLCV and date added columns
|
|
|
|
:param df_main: DataFrame = main dataframe
|
|
|
|
:param df_to_merge: DataFrame = dataframe to merge
|
|
|
|
:param tf: str = timeframe of the main dataframe
|
|
|
|
:param timeframe_inf: str = timeframe of the dataframe to merge
|
|
|
|
:param suffix: str = suffix to add to the columns of the dataframe to merge
|
|
|
|
:return: dataframe = merged dataframe
|
|
|
|
"""
|
2024-05-12 15:12:20 +00:00
|
|
|
dataframe = merge_informative_pair(
|
|
|
|
df_main,
|
|
|
|
df_to_merge,
|
|
|
|
tf,
|
|
|
|
timeframe_inf=timeframe_inf,
|
|
|
|
append_timeframe=False,
|
|
|
|
suffix=suffix,
|
|
|
|
ffill=True,
|
|
|
|
)
|
2022-12-27 14:37:01 +00:00
|
|
|
skip_columns = [
|
|
|
|
(f"{s}_{suffix}") for s in ["date", "open", "high", "low", "close", "volume"]
|
|
|
|
]
|
|
|
|
dataframe = dataframe.drop(columns=skip_columns)
|
|
|
|
return dataframe
|
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
def populate_features(
|
|
|
|
self,
|
|
|
|
dataframe: DataFrame,
|
|
|
|
pair: str,
|
|
|
|
strategy: IStrategy,
|
|
|
|
corr_dataframes: dict,
|
|
|
|
base_dataframes: dict,
|
|
|
|
is_corr_pairs: bool = False,
|
|
|
|
) -> DataFrame:
|
2022-12-27 14:37:01 +00:00
|
|
|
"""
|
|
|
|
Use the user defined strategy functions for populating features
|
|
|
|
:param dataframe: DataFrame = dataframe to populate
|
|
|
|
:param pair: str = pair to populate
|
|
|
|
:param strategy: IStrategy = user defined strategy object
|
|
|
|
:param corr_dataframes: dict = dict containing the df pair dataframes
|
|
|
|
:param base_dataframes: dict = dict containing the current pair dataframes
|
|
|
|
:param is_corr_pairs: bool = whether the pair is a corr pair or not
|
|
|
|
:return: dataframe = populated dataframe
|
|
|
|
"""
|
|
|
|
tfs: List[str] = self.freqai_config["feature_parameters"].get("include_timeframes")
|
|
|
|
|
|
|
|
for tf in tfs:
|
2023-02-04 12:47:11 +00:00
|
|
|
metadata = {"pair": pair, "tf": tf}
|
2022-12-27 14:37:01 +00:00
|
|
|
informative_df = self.get_pair_data_for_features(
|
2024-05-12 15:12:20 +00:00
|
|
|
pair, tf, strategy, corr_dataframes, base_dataframes, is_corr_pairs
|
|
|
|
)
|
2022-12-27 14:37:01 +00:00
|
|
|
informative_copy = informative_df.copy()
|
|
|
|
|
2023-12-15 10:47:56 +00:00
|
|
|
logger.debug(f"Populating features for {pair} {tf}")
|
|
|
|
|
2022-12-27 14:37:01 +00:00
|
|
|
for t in self.freqai_config["feature_parameters"]["indicator_periods_candles"]:
|
2022-12-28 12:25:40 +00:00
|
|
|
df_features = strategy.feature_engineering_expand_all(
|
2024-05-12 15:12:20 +00:00
|
|
|
informative_copy.copy(), t, metadata=metadata
|
|
|
|
)
|
2022-12-27 14:37:01 +00:00
|
|
|
suffix = f"{t}"
|
|
|
|
informative_df = self.merge_features(informative_df, df_features, tf, tf, suffix)
|
|
|
|
|
2023-02-04 12:47:11 +00:00
|
|
|
generic_df = strategy.feature_engineering_expand_basic(
|
2024-05-12 15:12:20 +00:00
|
|
|
informative_copy.copy(), metadata=metadata
|
|
|
|
)
|
2022-12-27 14:37:01 +00:00
|
|
|
suffix = "gen"
|
|
|
|
|
|
|
|
informative_df = self.merge_features(informative_df, generic_df, tf, tf, suffix)
|
|
|
|
|
|
|
|
indicators = [col for col in informative_df if col.startswith("%")]
|
|
|
|
for n in range(self.freqai_config["feature_parameters"]["include_shifted_candles"] + 1):
|
|
|
|
if n == 0:
|
|
|
|
continue
|
|
|
|
df_shift = informative_df[indicators].shift(n)
|
|
|
|
df_shift = df_shift.add_suffix("_shift-" + str(n))
|
|
|
|
informative_df = pd.concat((informative_df, df_shift), axis=1)
|
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
dataframe = self.merge_features(
|
|
|
|
dataframe.copy(), informative_df, self.config["timeframe"], tf, f"{pair}_{tf}"
|
|
|
|
)
|
2022-12-27 14:37:01 +00:00
|
|
|
|
|
|
|
return dataframe
|
|
|
|
|
2023-03-26 11:43:59 +00:00
|
|
|
def use_strategy_to_populate_indicators( # noqa: C901
|
2022-07-21 10:24:22 +00:00
|
|
|
self,
|
|
|
|
strategy: IStrategy,
|
|
|
|
corr_dataframes: dict = {},
|
|
|
|
base_dataframes: dict = {},
|
|
|
|
pair: str = "",
|
|
|
|
prediction_dataframe: DataFrame = pd.DataFrame(),
|
2022-10-20 14:30:32 +00:00
|
|
|
do_corr_pairs: bool = True,
|
2022-07-03 08:59:38 +00:00
|
|
|
) -> DataFrame:
|
2022-06-03 13:19:46 +00:00
|
|
|
"""
|
2022-10-10 12:15:30 +00:00
|
|
|
Use the user defined strategy for populating indicators during retrain
|
|
|
|
:param strategy: IStrategy = user defined strategy object
|
2022-12-27 14:37:01 +00:00
|
|
|
:param corr_dataframes: dict = dict containing the df pair dataframes
|
|
|
|
(for user defined timeframes)
|
|
|
|
:param base_dataframes: dict = dict containing the current pair dataframes
|
|
|
|
(for user defined timeframes)
|
|
|
|
:param pair: str = pair to populate
|
|
|
|
:param prediction_dataframe: DataFrame = dataframe containing the pair data
|
|
|
|
used for prediction
|
|
|
|
:param do_corr_pairs: bool = whether to populate corr pairs or not
|
|
|
|
:return:
|
|
|
|
dataframe: DataFrame = dataframe containing populated indicators
|
|
|
|
"""
|
|
|
|
|
2023-02-21 13:22:40 +00:00
|
|
|
# check if the user is using the deprecated populate_any_indicators function
|
2022-12-27 14:37:01 +00:00
|
|
|
new_version = inspect.getsource(strategy.populate_any_indicators) == (
|
2024-05-12 15:12:20 +00:00
|
|
|
inspect.getsource(IStrategy.populate_any_indicators)
|
|
|
|
)
|
2022-12-27 14:37:01 +00:00
|
|
|
|
2023-02-21 13:22:40 +00:00
|
|
|
if not new_version:
|
|
|
|
raise OperationalException(
|
|
|
|
"You are using the `populate_any_indicators()` function"
|
|
|
|
" which was deprecated on March 1, 2023. Please refer "
|
|
|
|
"to the strategy migration guide to use the new "
|
|
|
|
"feature_engineering_* methods: \n"
|
2023-06-17 07:10:54 +00:00
|
|
|
f"{DOCS_LINK}/strategy_migration/#freqai-strategy \n"
|
2023-02-21 13:22:40 +00:00
|
|
|
"And the feature_engineering_* documentation: \n"
|
2023-06-17 07:10:54 +00:00
|
|
|
f"{DOCS_LINK}/freqai-feature-engineering/"
|
2024-05-12 15:12:20 +00:00
|
|
|
)
|
2022-12-27 14:37:01 +00:00
|
|
|
|
2023-02-21 13:22:40 +00:00
|
|
|
tfs: List[str] = self.freqai_config["feature_parameters"].get("include_timeframes")
|
2024-05-12 15:12:20 +00:00
|
|
|
pairs: List[str] = self.freqai_config["feature_parameters"].get("include_corr_pairlist", [])
|
2022-12-27 14:37:01 +00:00
|
|
|
|
2023-02-21 13:22:40 +00:00
|
|
|
for tf in tfs:
|
|
|
|
if tf not in base_dataframes:
|
|
|
|
base_dataframes[tf] = pd.DataFrame()
|
|
|
|
for p in pairs:
|
|
|
|
if p not in corr_dataframes:
|
|
|
|
corr_dataframes[p] = {}
|
|
|
|
if tf not in corr_dataframes[p]:
|
|
|
|
corr_dataframes[p][tf] = pd.DataFrame()
|
2022-07-21 10:24:22 +00:00
|
|
|
|
|
|
|
if not prediction_dataframe.empty:
|
|
|
|
dataframe = prediction_dataframe.copy()
|
2023-12-15 10:47:56 +00:00
|
|
|
base_dataframes[self.config["timeframe"]] = dataframe.copy()
|
2022-07-21 10:24:22 +00:00
|
|
|
else:
|
|
|
|
dataframe = base_dataframes[self.config["timeframe"]].copy()
|
|
|
|
|
2023-02-21 13:22:40 +00:00
|
|
|
corr_pairs: List[str] = self.freqai_config["feature_parameters"].get(
|
2024-05-12 15:12:20 +00:00
|
|
|
"include_corr_pairlist", []
|
|
|
|
)
|
|
|
|
dataframe = self.populate_features(
|
|
|
|
dataframe.copy(), pair, strategy, corr_dataframes, base_dataframes
|
|
|
|
)
|
2023-02-21 13:22:40 +00:00
|
|
|
metadata = {"pair": pair}
|
|
|
|
dataframe = strategy.feature_engineering_standard(dataframe.copy(), metadata=metadata)
|
2022-10-20 14:30:32 +00:00
|
|
|
# ensure corr pairs are always last
|
2023-02-21 13:22:40 +00:00
|
|
|
for corr_pair in corr_pairs:
|
2022-10-29 20:26:49 +00:00
|
|
|
if pair == corr_pair:
|
2022-10-20 14:30:32 +00:00
|
|
|
continue # dont repeat anything from whitelist
|
2023-02-21 13:22:40 +00:00
|
|
|
if corr_pairs and do_corr_pairs:
|
2024-05-12 15:12:20 +00:00
|
|
|
dataframe = self.populate_features(
|
|
|
|
dataframe.copy(), corr_pair, strategy, corr_dataframes, base_dataframes, True
|
|
|
|
)
|
2023-02-21 13:22:40 +00:00
|
|
|
|
2023-03-26 11:43:59 +00:00
|
|
|
if self.live:
|
|
|
|
dataframe = strategy.set_freqai_targets(dataframe.copy(), metadata=metadata)
|
|
|
|
dataframe = self.remove_special_chars_from_feature_names(dataframe)
|
2022-05-09 13:25:00 +00:00
|
|
|
|
2022-08-09 15:31:38 +00:00
|
|
|
self.get_unique_classes_from_labels(dataframe)
|
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
if self.config.get("reduce_df_footprint", False):
|
2022-11-12 09:38:25 +00:00
|
|
|
dataframe = reduce_dataframe_footprint(dataframe)
|
2022-11-04 16:42:10 +00:00
|
|
|
|
2022-05-09 13:25:00 +00:00
|
|
|
return dataframe
|
|
|
|
|
2022-05-26 19:07:50 +00:00
|
|
|
def fit_labels(self) -> None:
|
2022-06-03 13:19:46 +00:00
|
|
|
"""
|
|
|
|
Fit the labels with a gaussian distribution
|
|
|
|
"""
|
2022-05-26 19:07:50 +00:00
|
|
|
import scipy as spy
|
|
|
|
|
2022-07-03 08:59:38 +00:00
|
|
|
self.data["labels_mean"], self.data["labels_std"] = {}, {}
|
2022-08-06 11:51:19 +00:00
|
|
|
for label in self.data_dictionary["train_labels"].columns:
|
2022-07-09 08:13:33 +00:00
|
|
|
if self.data_dictionary["train_labels"][label].dtype == object:
|
|
|
|
continue
|
2022-07-02 16:09:38 +00:00
|
|
|
f = spy.stats.norm.fit(self.data_dictionary["train_labels"][label])
|
|
|
|
self.data["labels_mean"][label], self.data["labels_std"][label] = f[0], f[1]
|
2022-05-26 19:07:50 +00:00
|
|
|
|
2024-04-18 20:51:25 +00:00
|
|
|
# in case targets are classifications
|
2022-08-10 13:16:50 +00:00
|
|
|
for label in self.unique_class_list:
|
|
|
|
self.data["labels_mean"][label], self.data["labels_std"][label] = 0, 0
|
|
|
|
|
2022-05-26 19:07:50 +00:00
|
|
|
return
|
|
|
|
|
2022-07-22 10:17:15 +00:00
|
|
|
def remove_features_from_df(self, dataframe: DataFrame) -> DataFrame:
|
|
|
|
"""
|
|
|
|
Remove the features from the dataframe before returning it to strategy. This keeps it
|
|
|
|
compact for Frequi purposes.
|
|
|
|
"""
|
|
|
|
to_keep = [
|
|
|
|
col for col in dataframe.columns if not col.startswith("%") or col.startswith("%%")
|
|
|
|
]
|
|
|
|
return dataframe[to_keep]
|
2022-08-09 15:31:38 +00:00
|
|
|
|
|
|
|
def get_unique_classes_from_labels(self, dataframe: DataFrame) -> None:
|
2022-09-25 09:18:10 +00:00
|
|
|
# self.find_features(dataframe)
|
|
|
|
self.find_labels(dataframe)
|
2022-08-09 15:31:38 +00:00
|
|
|
|
|
|
|
for key in self.label_list:
|
|
|
|
if dataframe[key].dtype == object:
|
|
|
|
self.unique_classes[key] = dataframe[key].dropna().unique()
|
2022-08-10 13:16:50 +00:00
|
|
|
|
|
|
|
if self.unique_classes:
|
|
|
|
for label in self.unique_classes:
|
|
|
|
self.unique_class_list += list(self.unique_classes[label])
|
2022-08-31 14:23:48 +00:00
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
def save_backtesting_prediction(self, append_df: DataFrame) -> None:
|
2022-08-31 14:23:48 +00:00
|
|
|
"""
|
2022-11-29 13:38:35 +00:00
|
|
|
Save prediction dataframe from backtesting to feather file format
|
2022-09-01 10:09:23 +00:00
|
|
|
:param append_df: dataframe for backtesting period
|
2022-08-31 14:23:48 +00:00
|
|
|
"""
|
2022-09-03 12:00:01 +00:00
|
|
|
full_predictions_folder = Path(self.full_path / self.backtest_predictions_folder)
|
2022-09-01 10:09:23 +00:00
|
|
|
if not full_predictions_folder.is_dir():
|
|
|
|
full_predictions_folder.mkdir(parents=True, exist_ok=True)
|
2022-08-31 14:23:48 +00:00
|
|
|
|
2022-11-29 13:38:35 +00:00
|
|
|
append_df.to_feather(self.backtesting_results_path)
|
2022-08-31 18:36:29 +00:00
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
def get_backtesting_prediction(self) -> DataFrame:
|
2022-08-31 14:23:48 +00:00
|
|
|
"""
|
2022-11-29 13:38:35 +00:00
|
|
|
Get prediction dataframe from feather file format
|
2022-08-31 14:23:48 +00:00
|
|
|
"""
|
2022-11-29 13:38:35 +00:00
|
|
|
append_df = pd.read_feather(self.backtesting_results_path)
|
2022-08-31 14:23:48 +00:00
|
|
|
return append_df
|
2022-09-03 12:00:01 +00:00
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
def check_if_backtest_prediction_is_valid(self, len_backtest_df: int) -> bool:
|
2022-09-03 12:00:01 +00:00
|
|
|
"""
|
2022-11-02 18:49:51 +00:00
|
|
|
Check if a backtesting prediction already exists and if the predictions
|
2022-11-04 15:10:46 +00:00
|
|
|
to append have the same size as the backtesting dataframe slice
|
2022-11-02 18:49:51 +00:00
|
|
|
:param length_backtesting_dataframe: Length of backtesting dataframe slice
|
2022-09-03 12:00:01 +00:00
|
|
|
:return:
|
2022-11-02 18:49:51 +00:00
|
|
|
:boolean: whether the prediction file is valid.
|
2022-09-03 12:00:01 +00:00
|
|
|
"""
|
2024-05-12 15:12:20 +00:00
|
|
|
path_to_predictionfile = Path(
|
|
|
|
self.full_path
|
|
|
|
/ self.backtest_predictions_folder
|
|
|
|
/ f"{self.model_filename}_prediction.feather"
|
|
|
|
)
|
2022-11-29 13:38:35 +00:00
|
|
|
self.backtesting_results_path = path_to_predictionfile
|
|
|
|
|
|
|
|
file_exists = path_to_predictionfile.is_file()
|
|
|
|
|
|
|
|
if file_exists:
|
2022-11-02 18:49:51 +00:00
|
|
|
append_df = self.get_backtesting_prediction()
|
2024-05-12 15:12:20 +00:00
|
|
|
if len(append_df) == len_backtest_df and "date" in append_df:
|
2022-11-29 13:38:35 +00:00
|
|
|
logger.info(f"Found backtesting prediction file at {path_to_predictionfile}")
|
2022-11-02 18:49:51 +00:00
|
|
|
return True
|
|
|
|
else:
|
2024-05-12 15:12:20 +00:00
|
|
|
logger.info(
|
|
|
|
"A new backtesting prediction file is required. "
|
|
|
|
"(Number of predictions is different from dataframe length or "
|
|
|
|
"old prediction file version)."
|
|
|
|
)
|
2022-11-02 18:49:51 +00:00
|
|
|
return False
|
2022-09-03 12:00:01 +00:00
|
|
|
else:
|
2024-05-12 15:12:20 +00:00
|
|
|
logger.info(f"Could not find backtesting prediction file at {path_to_predictionfile}")
|
2022-11-02 18:49:51 +00:00
|
|
|
return False
|
2022-09-24 15:28:52 +00:00
|
|
|
|
2022-10-20 17:53:25 +00:00
|
|
|
def get_full_models_path(self, config: Config) -> Path:
|
|
|
|
"""
|
|
|
|
Returns default FreqAI model path
|
|
|
|
:param config: Configuration dictionary
|
|
|
|
"""
|
|
|
|
freqai_config: Dict[str, Any] = config["freqai"]
|
2024-05-12 15:12:20 +00:00
|
|
|
return Path(config["user_data_dir"] / "models" / str(freqai_config.get("identifier")))
|
2022-10-20 17:53:25 +00:00
|
|
|
|
2022-11-03 17:49:39 +00:00
|
|
|
def remove_special_chars_from_feature_names(self, dataframe: pd.DataFrame) -> pd.DataFrame:
|
|
|
|
"""
|
|
|
|
Remove all special characters from feature strings (:)
|
|
|
|
:param dataframe: the dataframe that just finished indicator population. (unfiltered)
|
|
|
|
:return: dataframe with cleaned featrue names
|
|
|
|
"""
|
|
|
|
|
2024-05-12 15:12:20 +00:00
|
|
|
spec_chars = [":"]
|
2022-11-03 17:49:39 +00:00
|
|
|
for c in spec_chars:
|
|
|
|
dataframe.columns = dataframe.columns.str.replace(c, "")
|
|
|
|
|
2022-11-03 18:13:24 +00:00
|
|
|
return dataframe
|
2023-02-21 20:08:34 +00:00
|
|
|
|
|
|
|
def buffer_timerange(self, timerange: TimeRange):
|
|
|
|
"""
|
|
|
|
Buffer the start and end of the timerange. This is used *after* the indicators
|
|
|
|
are populated.
|
|
|
|
|
|
|
|
The main example use is when predicting maxima and minima, the argrelextrema
|
|
|
|
function cannot know the maxima/minima at the edges of the timerange. To improve
|
|
|
|
model accuracy, it is best to compute argrelextrema on the full timerange
|
|
|
|
and then use this function to cut off the edges (buffer) by the kernel.
|
|
|
|
|
|
|
|
In another case, if the targets are set to a shifted price movement, this
|
|
|
|
buffer is unnecessary because the shifted candles at the end of the timerange
|
|
|
|
will be NaN and FreqAI will automatically cut those off of the training
|
|
|
|
dataset.
|
|
|
|
"""
|
|
|
|
buffer = self.freqai_config["feature_parameters"]["buffer_train_data_candles"]
|
|
|
|
if buffer:
|
|
|
|
timerange.stopts -= buffer * timeframe_to_seconds(self.config["timeframe"])
|
|
|
|
timerange.startts += buffer * timeframe_to_seconds(self.config["timeframe"])
|
|
|
|
|
|
|
|
return timerange
|
2023-06-10 10:48:27 +00:00
|
|
|
|
|
|
|
# deprecated functions
|
|
|
|
def normalize_data(self, data_dictionary: Dict) -> Dict[Any, Any]:
|
|
|
|
"""
|
|
|
|
Deprecation warning, migration assistance
|
|
|
|
"""
|
2024-05-12 15:12:20 +00:00
|
|
|
logger.warning(
|
|
|
|
f"Your custom IFreqaiModel relies on the deprecated"
|
|
|
|
" data pipeline. Please update your model to use the new data pipeline."
|
|
|
|
" This can be achieved by following the migration guide at "
|
|
|
|
f"{DOCS_LINK}/strategy_migration/#freqai-new-data-pipeline "
|
|
|
|
"We added a basic pipeline for you, but this will be removed "
|
|
|
|
"in a future version."
|
|
|
|
)
|
2023-06-10 10:48:27 +00:00
|
|
|
|
2023-06-16 11:06:21 +00:00
|
|
|
return data_dictionary
|
2023-06-10 10:48:27 +00:00
|
|
|
|
|
|
|
def denormalize_labels_from_metadata(self, df: DataFrame) -> DataFrame:
|
|
|
|
"""
|
|
|
|
Deprecation warning, migration assistance
|
|
|
|
"""
|
2024-05-12 15:12:20 +00:00
|
|
|
logger.warning(
|
|
|
|
f"Your custom IFreqaiModel relies on the deprecated"
|
|
|
|
" data pipeline. Please update your model to use the new data pipeline."
|
|
|
|
" This can be achieved by following the migration guide at "
|
|
|
|
f"{DOCS_LINK}/strategy_migration/#freqai-new-data-pipeline "
|
|
|
|
"We added a basic pipeline for you, but this will be removed "
|
|
|
|
"in a future version."
|
|
|
|
)
|
2023-06-10 10:48:27 +00:00
|
|
|
|
|
|
|
pred_df, _, _ = self.label_pipeline.inverse_transform(df)
|
|
|
|
|
|
|
|
return pred_df
|