2023-05-20 09:45:06 +00:00
|
|
|
import logging
|
2023-05-20 09:35:17 +00:00
|
|
|
import time
|
|
|
|
from pathlib import Path
|
|
|
|
from typing import Any, Dict, List
|
|
|
|
|
|
|
|
import pandas as pd
|
2024-07-07 07:56:49 +00:00
|
|
|
from rich.text import Text
|
2023-05-20 09:35:17 +00:00
|
|
|
|
2023-05-20 09:45:06 +00:00
|
|
|
from freqtrade.constants import Config
|
|
|
|
from freqtrade.exceptions import OperationalException
|
2023-10-01 05:58:46 +00:00
|
|
|
from freqtrade.optimize.analysis.lookahead import LookaheadAnalysis
|
2023-05-20 09:45:06 +00:00
|
|
|
from freqtrade.resolvers import StrategyResolver
|
2024-07-07 07:56:49 +00:00
|
|
|
from freqtrade.util import print_rich_table
|
2023-05-20 09:45:06 +00:00
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
2023-05-20 09:35:17 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LookaheadAnalysisSubFunctions:
|
|
|
|
@staticmethod
|
2023-05-28 18:52:58 +00:00
|
|
|
def text_table_lookahead_analysis_instances(
|
2024-09-07 02:03:17 +00:00
|
|
|
config: Dict[str, Any],
|
|
|
|
lookahead_instances: List[LookaheadAnalysis],
|
|
|
|
caption: str | None = None,
|
2024-05-12 15:16:55 +00:00
|
|
|
):
|
|
|
|
headers = [
|
|
|
|
"filename",
|
|
|
|
"strategy",
|
|
|
|
"has_bias",
|
|
|
|
"total_signals",
|
|
|
|
"biased_entry_signals",
|
|
|
|
"biased_exit_signals",
|
|
|
|
"biased_indicators",
|
|
|
|
]
|
2023-05-20 09:35:17 +00:00
|
|
|
data = []
|
|
|
|
for inst in lookahead_instances:
|
2024-05-12 15:16:55 +00:00
|
|
|
if config["minimum_trade_amount"] > inst.current_analysis.total_signals:
|
2023-05-28 18:52:58 +00:00
|
|
|
data.append(
|
|
|
|
[
|
2024-05-12 15:16:55 +00:00
|
|
|
inst.strategy_obj["location"].parts[-1],
|
|
|
|
inst.strategy_obj["name"],
|
2023-05-28 18:52:58 +00:00
|
|
|
"too few trades caught "
|
|
|
|
f"({inst.current_analysis.total_signals}/{config['minimum_trade_amount']})."
|
2024-05-12 15:16:55 +00:00
|
|
|
f"Test failed.",
|
2023-05-28 18:52:58 +00:00
|
|
|
]
|
|
|
|
)
|
|
|
|
elif inst.failed_bias_check:
|
2023-05-20 09:35:17 +00:00
|
|
|
data.append(
|
|
|
|
[
|
2024-05-12 15:16:55 +00:00
|
|
|
inst.strategy_obj["location"].parts[-1],
|
|
|
|
inst.strategy_obj["name"],
|
|
|
|
"error while checking",
|
2023-05-20 09:35:17 +00:00
|
|
|
]
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
data.append(
|
|
|
|
[
|
2024-05-12 15:16:55 +00:00
|
|
|
inst.strategy_obj["location"].parts[-1],
|
|
|
|
inst.strategy_obj["name"],
|
2024-07-07 07:56:49 +00:00
|
|
|
Text("Yes", style="bold red")
|
|
|
|
if inst.current_analysis.has_bias
|
|
|
|
else Text("No", style="bold green"),
|
2023-05-20 09:35:17 +00:00
|
|
|
inst.current_analysis.total_signals,
|
|
|
|
inst.current_analysis.false_entry_signals,
|
|
|
|
inst.current_analysis.false_exit_signals,
|
2024-05-12 15:16:55 +00:00
|
|
|
", ".join(inst.current_analysis.false_indicators),
|
2023-05-20 09:35:17 +00:00
|
|
|
]
|
|
|
|
)
|
2024-05-12 15:16:55 +00:00
|
|
|
|
2024-09-07 02:03:17 +00:00
|
|
|
print_rich_table(
|
|
|
|
data,
|
|
|
|
headers,
|
|
|
|
summary="Lookahead Analysis",
|
|
|
|
table_kwargs={"caption": caption}
|
|
|
|
)
|
2024-07-07 07:43:44 +00:00
|
|
|
return data
|
2023-05-20 09:35:17 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def export_to_csv(config: Dict[str, Any], lookahead_analysis: List[LookaheadAnalysis]):
|
|
|
|
def add_or_update_row(df, row_data):
|
|
|
|
if (
|
2024-05-12 15:16:55 +00:00
|
|
|
(df["filename"] == row_data["filename"]) & (df["strategy"] == row_data["strategy"])
|
2023-05-20 09:35:17 +00:00
|
|
|
).any():
|
|
|
|
# Update existing row
|
|
|
|
pd_series = pd.DataFrame([row_data])
|
|
|
|
df.loc[
|
2024-05-12 15:16:55 +00:00
|
|
|
(df["filename"] == row_data["filename"])
|
|
|
|
& (df["strategy"] == row_data["strategy"])
|
|
|
|
] = pd_series
|
2023-05-20 09:35:17 +00:00
|
|
|
else:
|
|
|
|
# Add new row
|
|
|
|
df = pd.concat([df, pd.DataFrame([row_data], columns=df.columns)])
|
|
|
|
|
|
|
|
return df
|
|
|
|
|
2024-05-12 15:16:55 +00:00
|
|
|
if Path(config["lookahead_analysis_exportfilename"]).exists():
|
2023-05-20 09:35:17 +00:00
|
|
|
# Read CSV file into a pandas dataframe
|
2024-05-12 15:16:55 +00:00
|
|
|
csv_df = pd.read_csv(config["lookahead_analysis_exportfilename"])
|
2023-05-20 09:35:17 +00:00
|
|
|
else:
|
|
|
|
# Create a new empty DataFrame with the desired column names and set the index
|
2024-05-12 15:16:55 +00:00
|
|
|
csv_df = pd.DataFrame(
|
|
|
|
columns=[
|
|
|
|
"filename",
|
|
|
|
"strategy",
|
|
|
|
"has_bias",
|
|
|
|
"total_signals",
|
|
|
|
"biased_entry_signals",
|
|
|
|
"biased_exit_signals",
|
|
|
|
"biased_indicators",
|
|
|
|
],
|
|
|
|
index=None,
|
|
|
|
)
|
2023-05-20 09:35:17 +00:00
|
|
|
|
|
|
|
for inst in lookahead_analysis:
|
2023-05-28 18:52:58 +00:00
|
|
|
# only update if
|
2024-05-12 15:16:55 +00:00
|
|
|
if (
|
|
|
|
inst.current_analysis.total_signals > config["minimum_trade_amount"]
|
|
|
|
and inst.failed_bias_check is not True
|
|
|
|
):
|
|
|
|
new_row_data = {
|
|
|
|
"filename": inst.strategy_obj["location"].parts[-1],
|
|
|
|
"strategy": inst.strategy_obj["name"],
|
|
|
|
"has_bias": inst.current_analysis.has_bias,
|
|
|
|
"total_signals": int(inst.current_analysis.total_signals),
|
|
|
|
"biased_entry_signals": int(inst.current_analysis.false_entry_signals),
|
|
|
|
"biased_exit_signals": int(inst.current_analysis.false_exit_signals),
|
|
|
|
"biased_indicators": ",".join(inst.current_analysis.false_indicators),
|
|
|
|
}
|
2023-05-28 18:52:58 +00:00
|
|
|
csv_df = add_or_update_row(csv_df, new_row_data)
|
2023-05-20 09:35:17 +00:00
|
|
|
|
2023-05-28 20:13:29 +00:00
|
|
|
# Fill NaN values with a default value (e.g., 0)
|
2024-05-12 15:16:55 +00:00
|
|
|
csv_df["total_signals"] = csv_df["total_signals"].astype(int).fillna(0)
|
|
|
|
csv_df["biased_entry_signals"] = csv_df["biased_entry_signals"].astype(int).fillna(0)
|
|
|
|
csv_df["biased_exit_signals"] = csv_df["biased_exit_signals"].astype(int).fillna(0)
|
2023-05-28 20:13:29 +00:00
|
|
|
|
|
|
|
# Convert columns to integers
|
2024-05-12 15:16:55 +00:00
|
|
|
csv_df["total_signals"] = csv_df["total_signals"].astype(int)
|
|
|
|
csv_df["biased_entry_signals"] = csv_df["biased_entry_signals"].astype(int)
|
|
|
|
csv_df["biased_exit_signals"] = csv_df["biased_exit_signals"].astype(int)
|
2023-05-28 20:13:29 +00:00
|
|
|
|
2023-05-20 09:35:17 +00:00
|
|
|
logger.info(f"saving {config['lookahead_analysis_exportfilename']}")
|
2024-05-12 15:16:55 +00:00
|
|
|
csv_df.to_csv(config["lookahead_analysis_exportfilename"], index=False)
|
2023-05-20 09:35:17 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2023-06-09 20:11:30 +00:00
|
|
|
def calculate_config_overrides(config: Config):
|
2024-05-12 15:16:55 +00:00
|
|
|
if config.get("enable_protections", False):
|
2024-03-17 08:53:45 +00:00
|
|
|
# if protections are used globally, they can produce false positives.
|
2024-05-12 15:16:55 +00:00
|
|
|
config["enable_protections"] = False
|
|
|
|
logger.info(
|
|
|
|
"Protections were enabled. "
|
|
|
|
"Disabling protections now "
|
|
|
|
"since they could otherwise produce false positives."
|
|
|
|
)
|
|
|
|
if config["targeted_trade_amount"] < config["minimum_trade_amount"]:
|
2023-05-20 09:45:06 +00:00
|
|
|
# this combo doesn't make any sense.
|
|
|
|
raise OperationalException(
|
2023-06-09 20:11:30 +00:00
|
|
|
"Targeted trade amount can't be smaller than minimum trade amount."
|
2023-05-20 09:45:06 +00:00
|
|
|
)
|
2024-05-12 15:16:55 +00:00
|
|
|
if len(config["pairs"]) > config.get("max_open_trades", 0):
|
|
|
|
logger.info(
|
|
|
|
"Max_open_trades were less than amount of pairs "
|
|
|
|
"or defined in the strategy. "
|
|
|
|
"Set max_open_trades to amount of pairs "
|
|
|
|
"just to avoid false positives."
|
|
|
|
)
|
|
|
|
config["max_open_trades"] = len(config["pairs"])
|
2023-06-09 20:11:30 +00:00
|
|
|
|
|
|
|
min_dry_run_wallet = 1000000000
|
2024-05-12 15:16:55 +00:00
|
|
|
if config["dry_run_wallet"] < min_dry_run_wallet:
|
|
|
|
logger.info(
|
|
|
|
"Dry run wallet was not set to 1 billion, pushing it up there "
|
|
|
|
"just to avoid false positives"
|
|
|
|
)
|
|
|
|
config["dry_run_wallet"] = min_dry_run_wallet
|
2023-07-23 18:05:29 +00:00
|
|
|
|
2024-05-12 15:16:55 +00:00
|
|
|
if "timerange" not in config:
|
2023-08-05 06:24:47 +00:00
|
|
|
# setting a timerange is enforced here
|
|
|
|
raise OperationalException(
|
|
|
|
"Please set a timerange. "
|
|
|
|
"Usually a few months are enough depending on your needs and strategy."
|
|
|
|
)
|
2023-07-23 17:50:12 +00:00
|
|
|
# fix stake_amount to 10k.
|
|
|
|
# in a combination with a wallet size of 1 billion it should always be able to trade
|
|
|
|
# no matter if they use custom_stake_amount as a small percentage of wallet size
|
|
|
|
# or fixate custom_stake_amount to a certain value.
|
2024-05-12 15:16:55 +00:00
|
|
|
logger.info("fixing stake_amount to 10k")
|
|
|
|
config["stake_amount"] = 10000
|
2023-05-20 09:45:06 +00:00
|
|
|
|
2023-05-27 20:31:47 +00:00
|
|
|
# enforce cache to be 'none', shift it to 'none' if not already
|
|
|
|
# (since the default value is 'day')
|
2024-05-12 15:16:55 +00:00
|
|
|
if config.get("backtest_cache") is None:
|
|
|
|
config["backtest_cache"] = "none"
|
|
|
|
elif config["backtest_cache"] != "none":
|
|
|
|
logger.info(
|
|
|
|
f"backtest_cache = "
|
|
|
|
f"{config['backtest_cache']} detected. "
|
|
|
|
f"Inside lookahead-analysis it is enforced to be 'none'. "
|
|
|
|
f"Changed it to 'none'"
|
|
|
|
)
|
|
|
|
config["backtest_cache"] = "none"
|
2023-06-09 20:11:30 +00:00
|
|
|
return config
|
|
|
|
|
|
|
|
@staticmethod
|
2023-06-15 18:42:26 +00:00
|
|
|
def initialize_single_lookahead_analysis(config: Config, strategy_obj: Dict[str, Any]):
|
2023-06-09 20:11:30 +00:00
|
|
|
logger.info(f"Bias test of {Path(strategy_obj['location']).name} started.")
|
|
|
|
start = time.perf_counter()
|
|
|
|
current_instance = LookaheadAnalysis(config, strategy_obj)
|
|
|
|
current_instance.start()
|
|
|
|
elapsed = time.perf_counter() - start
|
2024-05-12 15:16:55 +00:00
|
|
|
logger.info(
|
|
|
|
f"Checking look ahead bias via backtests "
|
|
|
|
f"of {Path(strategy_obj['location']).name} "
|
|
|
|
f"took {elapsed:.0f} seconds."
|
|
|
|
)
|
2023-06-09 20:11:30 +00:00
|
|
|
return current_instance
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def start(config: Config):
|
|
|
|
config = LookaheadAnalysisSubFunctions.calculate_config_overrides(config)
|
2023-05-27 20:31:47 +00:00
|
|
|
|
2023-05-20 09:45:06 +00:00
|
|
|
strategy_objs = StrategyResolver.search_all_objects(
|
2024-05-12 15:16:55 +00:00
|
|
|
config, enum_failed=False, recursive=config.get("recursive_strategy_search", False)
|
|
|
|
)
|
2023-05-20 09:45:06 +00:00
|
|
|
|
|
|
|
lookaheadAnalysis_instances = []
|
|
|
|
|
2023-09-28 19:01:37 +00:00
|
|
|
# unify --strategy and --strategy-list to one list
|
2024-05-12 15:16:55 +00:00
|
|
|
if not (strategy_list := config.get("strategy_list", [])):
|
|
|
|
if config.get("strategy") is None:
|
2023-05-20 09:51:46 +00:00
|
|
|
raise OperationalException(
|
|
|
|
"No Strategy specified. Please specify a strategy via --strategy or "
|
2023-09-28 19:01:37 +00:00
|
|
|
"--strategy-list"
|
2023-05-20 09:51:46 +00:00
|
|
|
)
|
2024-05-12 15:16:55 +00:00
|
|
|
strategy_list = [config["strategy"]]
|
2023-05-20 09:45:06 +00:00
|
|
|
|
|
|
|
# check if strategies can be properly loaded, only check them if they can be.
|
|
|
|
for strat in strategy_list:
|
|
|
|
for strategy_obj in strategy_objs:
|
2024-05-12 15:16:55 +00:00
|
|
|
if strategy_obj["name"] == strat and strategy_obj not in strategy_list:
|
2023-05-20 09:45:06 +00:00
|
|
|
lookaheadAnalysis_instances.append(
|
|
|
|
LookaheadAnalysisSubFunctions.initialize_single_lookahead_analysis(
|
2024-05-12 15:16:55 +00:00
|
|
|
config, strategy_obj
|
|
|
|
)
|
|
|
|
)
|
2023-05-20 09:45:06 +00:00
|
|
|
break
|
|
|
|
|
|
|
|
# report the results
|
|
|
|
if lookaheadAnalysis_instances:
|
2024-09-07 02:03:17 +00:00
|
|
|
caption: str | None = None
|
|
|
|
if any([
|
|
|
|
any([
|
|
|
|
indicator.startswith("&")
|
|
|
|
for indicator in inst.current_analysis.false_indicators
|
|
|
|
]) for inst in lookaheadAnalysis_instances
|
|
|
|
]):
|
|
|
|
caption = (
|
|
|
|
"Any indicators in 'biased_indicators' which are used within "
|
|
|
|
"set_freqai_targets() can be ignored."
|
|
|
|
)
|
2023-05-20 09:45:06 +00:00
|
|
|
LookaheadAnalysisSubFunctions.text_table_lookahead_analysis_instances(
|
2024-09-07 02:03:17 +00:00
|
|
|
config, lookaheadAnalysis_instances, caption=caption
|
2024-05-12 15:16:55 +00:00
|
|
|
)
|
|
|
|
if config.get("lookahead_analysis_exportfilename") is not None:
|
2023-05-20 09:45:06 +00:00
|
|
|
LookaheadAnalysisSubFunctions.export_to_csv(config, lookaheadAnalysis_instances)
|
|
|
|
else:
|
2024-05-12 15:16:55 +00:00
|
|
|
logger.error(
|
|
|
|
"There were no strategies specified neither through "
|
|
|
|
"--strategy nor through "
|
|
|
|
"--strategy-list "
|
|
|
|
"or timeframe was not specified."
|
|
|
|
)
|