Merge branch 'feat/freqai' of https://github.com/freqtrade/freqtrade into feat/freqai

This commit is contained in:
longyu
2022-07-04 09:01:34 +02:00
143 changed files with 12472 additions and 10183 deletions

View File

@@ -70,7 +70,9 @@ class FreqaiExampleStrategy(IStrategy):
def bot_start(self):
self.model = CustomModel(self.config)
def populate_any_indicators(self, metadata, pair, df, tf, informative=None, coin=""):
def populate_any_indicators(
self, metadata, pair, df, tf, informative=None, coin="", set_generalized_indicators=False
):
"""
Function designed to automatically generate, name and merge features
from user indicated timeframes in the configuration file. User controls the indicators
@@ -120,9 +122,7 @@ class FreqaiExampleStrategy(IStrategy):
informative["close"] / informative[f"{coin}bb_lowerband-period_{t}"]
)
informative[f"%-{coin}roc-period_{t}"] = ta.ROC(
informative, timeperiod=t
)
informative[f"%-{coin}roc-period_{t}"] = ta.ROC(informative, timeperiod=t)
macd = ta.MACD(informative, timeperiod=t)
informative[f"%-{coin}macd-period_{t}"] = macd["macd"]
@@ -152,17 +152,17 @@ class FreqaiExampleStrategy(IStrategy):
# Add generalized indicators here (because in live, it will call this
# function to populate indicators during training). Notice how we ensure not to
# add them multiple times
if pair == self.freqai_info['corr_pairlist'][0] and tf == self.timeframe:
if set_generalized_indicators:
df["%-day_of_week"] = (df["date"].dt.dayofweek + 1) / 7
df["%-hour_of_day"] = (df["date"].dt.hour + 1) / 25
# user adds targets here by prepending them with &- (see convention below)
# If user wishes to use multiple targets, a multioutput prediction model
# needs to be used such as templates/CatboostPredictionMultiModel.py
df['&-s_close'] = (
df["&-s_close"] = (
df["close"]
.shift(-self.freqai_info['feature_parameters']["period"])
.rolling(self.freqai_info['feature_parameters']["period"])
.shift(-self.freqai_info["feature_parameters"]["period"])
.rolling(self.freqai_info["feature_parameters"]["period"])
.mean()
/ df["close"]
- 1
@@ -174,15 +174,21 @@ class FreqaiExampleStrategy(IStrategy):
self.freqai_info = self.config["freqai"]
self.pair = metadata["pair"]
sgi = True
# the following loops are necessary for building the features
# indicated by the user in the configuration file.
# All indicators must be populated by populate_any_indicators() for live functionality
# to work correctly.
for tf in self.freqai_info["timeframes"]:
dataframe = self.populate_any_indicators(
metadata, self.pair, dataframe.copy(), tf, coin=self.pair.split("/")[0] + "-"
metadata,
self.pair,
dataframe.copy(),
tf,
coin=self.pair.split("/")[0] + "-",
set_generalized_indicators=sgi,
)
sgi = False
for pair in self.freqai_info["corr_pairlist"]:
if metadata["pair"] in pair:
continue # do not include whitelisted pair twice if it is in corr_pairlist
@@ -231,51 +237,55 @@ class FreqaiExampleStrategy(IStrategy):
def get_ticker_indicator(self):
return int(self.config["timeframe"][:-1])
def custom_exit(self, pair: str, trade: Trade, current_time, current_rate,
current_profit, **kwargs):
def custom_exit(
self, pair: str, trade: Trade, current_time, current_rate, current_profit, **kwargs
):
dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe)
trade_date = timeframe_to_prev_date(self.config['timeframe'], trade.open_date_utc)
trade_candle = dataframe.loc[(dataframe['date'] == trade_date)]
trade_date = timeframe_to_prev_date(self.config["timeframe"], trade.open_date_utc)
trade_candle = dataframe.loc[(dataframe["date"] == trade_date)]
if trade_candle.empty:
return None
trade_candle = trade_candle.squeeze()
follow_mode = self.config.get('freqai', {}).get('follow_mode', False)
follow_mode = self.config.get("freqai", {}).get("follow_mode", False)
if not follow_mode:
pair_dict = self.model.bridge.data_drawer.pair_dict
pair_dict = self.model.bridge.dd.pair_dict
else:
pair_dict = self.model.bridge.data_drawer.follower_dict
pair_dict = self.model.bridge.dd.follower_dict
entry_tag = trade.enter_tag
if ('prediction' + entry_tag not in pair_dict[pair] or
pair_dict[pair]['prediction' + entry_tag] > 0):
if (
"prediction" + entry_tag not in pair_dict[pair]
or pair_dict[pair]["prediction" + entry_tag] > 0
):
with self.model.bridge.lock:
pair_dict[pair]['prediction' + entry_tag] = abs(trade_candle['&-s_close'])
pair_dict[pair]["prediction" + entry_tag] = abs(trade_candle["&-s_close"])
if not follow_mode:
self.model.bridge.data_drawer.save_drawer_to_disk()
self.model.bridge.dd.save_drawer_to_disk()
else:
self.model.bridge.data_drawer.save_follower_dict_to_disk()
self.model.bridge.dd.save_follower_dict_to_disk()
roi_price = pair_dict[pair]['prediction' + entry_tag]
roi_price = pair_dict[pair]["prediction" + entry_tag]
roi_time = self.max_roi_time_long.value
roi_decay = roi_price * (1 - ((current_time - trade.open_date_utc).seconds) /
(roi_time * 60))
roi_decay = roi_price * (
1 - ((current_time - trade.open_date_utc).seconds) / (roi_time * 60)
)
if roi_decay < 0:
roi_decay = self.linear_roi_offset.value
else:
roi_decay += self.linear_roi_offset.value
if current_profit > roi_decay:
return 'roi_custom_win'
return "roi_custom_win"
if current_profit < -roi_decay:
return 'roi_custom_loss'
return "roi_custom_loss"
def confirm_trade_exit(
self,
@@ -287,22 +297,22 @@ class FreqaiExampleStrategy(IStrategy):
time_in_force: str,
exit_reason: str,
current_time,
**kwargs
**kwargs,
) -> bool:
entry_tag = trade.enter_tag
follow_mode = self.config.get("freqai", {}).get("follow_mode", False)
if not follow_mode:
pair_dict = self.model.bridge.data_drawer.pair_dict
pair_dict = self.model.bridge.dd.pair_dict
else:
pair_dict = self.model.bridge.data_drawer.follower_dict
pair_dict = self.model.bridge.dd.follower_dict
with self.model.bridge.lock:
pair_dict[pair]["prediction" + entry_tag] = 0
if not follow_mode:
self.model.bridge.data_drawer.save_drawer_to_disk()
self.model.bridge.dd.save_drawer_to_disk()
else:
self.model.bridge.data_drawer.save_follower_dict_to_disk()
self.model.bridge.dd.save_follower_dict_to_disk()
return True
@@ -316,7 +326,7 @@ class FreqaiExampleStrategy(IStrategy):
current_time,
entry_tag,
side: str,
**kwargs
**kwargs,
) -> bool:
df, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)