ruff format: Update more test files

This commit is contained in:
Matthias
2024-05-12 15:59:04 +02:00
parent ca1fe06035
commit d8a8b5c125
8 changed files with 340 additions and 313 deletions

View File

@@ -15,17 +15,18 @@ from tests.conftest import EXMS, get_args, log_has_re, patch_exchange
@pytest.fixture
def lookahead_conf(default_conf_usdt, tmp_path):
default_conf_usdt['user_data_dir'] = tmp_path
default_conf_usdt['minimum_trade_amount'] = 10
default_conf_usdt['targeted_trade_amount'] = 20
default_conf_usdt['timerange'] = '20220101-20220501'
default_conf_usdt["user_data_dir"] = tmp_path
default_conf_usdt["minimum_trade_amount"] = 10
default_conf_usdt["targeted_trade_amount"] = 20
default_conf_usdt["timerange"] = "20220101-20220501"
default_conf_usdt['strategy_path'] = str(
Path(__file__).parent.parent / "strategy/strats/lookahead_bias")
default_conf_usdt['strategy'] = 'strategy_test_v3_with_lookahead_bias'
default_conf_usdt['max_open_trades'] = 1
default_conf_usdt['dry_run_wallet'] = 1000000000
default_conf_usdt['pairs'] = ['UNITTEST/USDT']
default_conf_usdt["strategy_path"] = str(
Path(__file__).parent.parent / "strategy/strats/lookahead_bias"
)
default_conf_usdt["strategy"] = "strategy_test_v3_with_lookahead_bias"
default_conf_usdt["max_open_trades"] = 1
default_conf_usdt["dry_run_wallet"] = 1000000000
default_conf_usdt["pairs"] = ["UNITTEST/USDT"]
return default_conf_usdt
@@ -33,7 +34,7 @@ def test_start_lookahead_analysis(mocker):
single_mock = MagicMock()
text_table_mock = MagicMock()
mocker.patch.multiple(
'freqtrade.optimize.analysis.lookahead_helpers.LookaheadAnalysisSubFunctions',
"freqtrade.optimize.analysis.lookahead_helpers.LookaheadAnalysisSubFunctions",
initialize_single_lookahead_analysis=single_mock,
text_table_lookahead_analysis_instances=text_table_mock,
)
@@ -48,10 +49,10 @@ def test_start_lookahead_analysis(mocker):
"--max-open-trades",
"1",
"--timerange",
"20220101-20220201"
"20220101-20220201",
]
pargs = get_args(args)
pargs['config'] = None
pargs["config"] = None
start_lookahead_analysis(pargs)
assert single_mock.call_count == 1
@@ -72,9 +73,11 @@ def test_start_lookahead_analysis(mocker):
"20",
]
pargs = get_args(args)
pargs['config'] = None
with pytest.raises(OperationalException,
match=r"Targeted trade amount can't be smaller than minimum trade amount.*"):
pargs["config"] = None
with pytest.raises(
OperationalException,
match=r"Targeted trade amount can't be smaller than minimum trade amount.*",
):
start_lookahead_analysis(pargs)
# Missing timerange
@@ -90,27 +93,27 @@ def test_start_lookahead_analysis(mocker):
"1",
]
pargs = get_args(args)
pargs['config'] = None
with pytest.raises(OperationalException,
match=r"Please set a timerange\..*"):
pargs["config"] = None
with pytest.raises(OperationalException, match=r"Please set a timerange\..*"):
start_lookahead_analysis(pargs)
def test_lookahead_helper_invalid_config(lookahead_conf) -> None:
conf = deepcopy(lookahead_conf)
conf['targeted_trade_amount'] = 10
conf['minimum_trade_amount'] = 40
with pytest.raises(OperationalException,
match=r"Targeted trade amount can't be smaller than minimum trade amount.*"):
conf["targeted_trade_amount"] = 10
conf["minimum_trade_amount"] = 40
with pytest.raises(
OperationalException,
match=r"Targeted trade amount can't be smaller than minimum trade amount.*",
):
LookaheadAnalysisSubFunctions.start(conf)
def test_lookahead_helper_no_strategy_defined(lookahead_conf):
conf = deepcopy(lookahead_conf)
conf['pairs'] = ['UNITTEST/USDT']
del conf['strategy']
with pytest.raises(OperationalException,
match=r"No Strategy specified"):
conf["pairs"] = ["UNITTEST/USDT"]
del conf["strategy"]
with pytest.raises(OperationalException, match=r"No Strategy specified"):
LookaheadAnalysisSubFunctions.start(conf)
@@ -118,7 +121,7 @@ def test_lookahead_helper_start(lookahead_conf, mocker) -> None:
single_mock = MagicMock()
text_table_mock = MagicMock()
mocker.patch.multiple(
'freqtrade.optimize.analysis.lookahead_helpers.LookaheadAnalysisSubFunctions',
"freqtrade.optimize.analysis.lookahead_helpers.LookaheadAnalysisSubFunctions",
initialize_single_lookahead_analysis=single_mock,
text_table_lookahead_analysis_instances=text_table_mock,
)
@@ -138,19 +141,20 @@ def test_lookahead_helper_text_table_lookahead_analysis_instances(lookahead_conf
analysis.false_exit_signals = 3
strategy_obj = {
'name': "strategy_test_v3_with_lookahead_bias",
'location': Path(lookahead_conf['strategy_path'], f"{lookahead_conf['strategy']}.py")
"name": "strategy_test_v3_with_lookahead_bias",
"location": Path(lookahead_conf["strategy_path"], f"{lookahead_conf['strategy']}.py"),
}
instance = LookaheadAnalysis(lookahead_conf, strategy_obj)
instance.current_analysis = analysis
_table, _headers, data = (LookaheadAnalysisSubFunctions.
text_table_lookahead_analysis_instances(lookahead_conf, [instance]))
_table, _headers, data = LookaheadAnalysisSubFunctions.text_table_lookahead_analysis_instances(
lookahead_conf, [instance]
)
# check row contents for a try that has too few signals
assert data[0][0] == 'strategy_test_v3_with_lookahead_bias.py'
assert data[0][1] == 'strategy_test_v3_with_lookahead_bias'
assert data[0][2].__contains__('too few trades')
assert data[0][0] == "strategy_test_v3_with_lookahead_bias.py"
assert data[0][1] == "strategy_test_v3_with_lookahead_bias"
assert data[0][2].__contains__("too few trades")
assert len(data[0]) == 3
# now check for an error which occurred after enough trades
@@ -159,46 +163,51 @@ def test_lookahead_helper_text_table_lookahead_analysis_instances(lookahead_conf
analysis.false_exit_signals = 10
instance = LookaheadAnalysis(lookahead_conf, strategy_obj)
instance.current_analysis = analysis
_table, _headers, data = (LookaheadAnalysisSubFunctions.
text_table_lookahead_analysis_instances(lookahead_conf, [instance]))
_table, _headers, data = LookaheadAnalysisSubFunctions.text_table_lookahead_analysis_instances(
lookahead_conf, [instance]
)
assert data[0][2].__contains__("error")
# edit it into not showing an error
instance.failed_bias_check = False
_table, _headers, data = (LookaheadAnalysisSubFunctions.
text_table_lookahead_analysis_instances(lookahead_conf, [instance]))
assert data[0][0] == 'strategy_test_v3_with_lookahead_bias.py'
assert data[0][1] == 'strategy_test_v3_with_lookahead_bias'
_table, _headers, data = LookaheadAnalysisSubFunctions.text_table_lookahead_analysis_instances(
lookahead_conf, [instance]
)
assert data[0][0] == "strategy_test_v3_with_lookahead_bias.py"
assert data[0][1] == "strategy_test_v3_with_lookahead_bias"
assert data[0][2] # True
assert data[0][3] == 12
assert data[0][4] == 11
assert data[0][5] == 10
assert data[0][6] == ''
assert data[0][6] == ""
analysis.false_indicators.append('falseIndicator1')
analysis.false_indicators.append('falseIndicator2')
_table, _headers, data = (LookaheadAnalysisSubFunctions.
text_table_lookahead_analysis_instances(lookahead_conf, [instance]))
analysis.false_indicators.append("falseIndicator1")
analysis.false_indicators.append("falseIndicator2")
_table, _headers, data = LookaheadAnalysisSubFunctions.text_table_lookahead_analysis_instances(
lookahead_conf, [instance]
)
assert data[0][6] == 'falseIndicator1, falseIndicator2'
assert data[0][6] == "falseIndicator1, falseIndicator2"
# check amount of returning rows
assert len(data) == 1
# check amount of multiple rows
_table, _headers, data = (LookaheadAnalysisSubFunctions.text_table_lookahead_analysis_instances(
lookahead_conf, [instance, instance, instance]))
_table, _headers, data = LookaheadAnalysisSubFunctions.text_table_lookahead_analysis_instances(
lookahead_conf, [instance, instance, instance]
)
assert len(data) == 3
def test_lookahead_helper_export_to_csv(lookahead_conf):
import pandas as pd
lookahead_conf['lookahead_analysis_exportfilename'] = "temp_csv_lookahead_analysis.csv"
lookahead_conf["lookahead_analysis_exportfilename"] = "temp_csv_lookahead_analysis.csv"
# just to be sure the test won't fail: remove file if exists for some reason
# (repeat this at the end once again to clean up)
if Path(lookahead_conf['lookahead_analysis_exportfilename']).exists():
Path(lookahead_conf['lookahead_analysis_exportfilename']).unlink()
if Path(lookahead_conf["lookahead_analysis_exportfilename"]).exists():
Path(lookahead_conf["lookahead_analysis_exportfilename"]).unlink()
# before we can start we have to delete the
@@ -208,13 +217,13 @@ def test_lookahead_helper_export_to_csv(lookahead_conf):
analysis1.total_signals = 12
analysis1.false_entry_signals = 11
analysis1.false_exit_signals = 10
analysis1.false_indicators.append('falseIndicator1')
analysis1.false_indicators.append('falseIndicator2')
lookahead_conf['lookahead_analysis_exportfilename'] = "temp_csv_lookahead_analysis.csv"
analysis1.false_indicators.append("falseIndicator1")
analysis1.false_indicators.append("falseIndicator2")
lookahead_conf["lookahead_analysis_exportfilename"] = "temp_csv_lookahead_analysis.csv"
strategy_obj1 = {
'name': "strat1",
'location': Path("file1.py"),
"name": "strat1",
"location": Path("file1.py"),
}
instance1 = LookaheadAnalysis(lookahead_conf, strategy_obj1)
@@ -222,30 +231,28 @@ def test_lookahead_helper_export_to_csv(lookahead_conf):
instance1.current_analysis = analysis1
LookaheadAnalysisSubFunctions.export_to_csv(lookahead_conf, [instance1])
saved_data1 = pd.read_csv(lookahead_conf['lookahead_analysis_exportfilename'])
saved_data1 = pd.read_csv(lookahead_conf["lookahead_analysis_exportfilename"])
expected_values1 = [
[
'file1.py', 'strat1', True,
12, 11, 10,
"falseIndicator1,falseIndicator2"
],
["file1.py", "strat1", True, 12, 11, 10, "falseIndicator1,falseIndicator2"],
]
expected_columns = [
"filename",
"strategy",
"has_bias",
"total_signals",
"biased_entry_signals",
"biased_exit_signals",
"biased_indicators",
]
expected_columns = ['filename', 'strategy', 'has_bias',
'total_signals', 'biased_entry_signals', 'biased_exit_signals',
'biased_indicators']
expected_data1 = pd.DataFrame(expected_values1, columns=expected_columns)
assert Path(lookahead_conf['lookahead_analysis_exportfilename']).exists()
assert Path(lookahead_conf["lookahead_analysis_exportfilename"]).exists()
assert expected_data1.equals(saved_data1)
# 2nd check: update the same strategy (which internally changed or is being retested)
expected_values2 = [
[
'file1.py', 'strat1', False,
22, 21, 20,
"falseIndicator3,falseIndicator4"
],
["file1.py", "strat1", False, 22, 21, 20, "falseIndicator3,falseIndicator4"],
]
expected_data2 = pd.DataFrame(expected_values2, columns=expected_columns)
@@ -254,12 +261,12 @@ def test_lookahead_helper_export_to_csv(lookahead_conf):
analysis2.total_signals = 22
analysis2.false_entry_signals = 21
analysis2.false_exit_signals = 20
analysis2.false_indicators.append('falseIndicator3')
analysis2.false_indicators.append('falseIndicator4')
analysis2.false_indicators.append("falseIndicator3")
analysis2.false_indicators.append("falseIndicator4")
strategy_obj2 = {
'name': "strat1",
'location': Path("file1.py"),
"name": "strat1",
"location": Path("file1.py"),
}
instance2 = LookaheadAnalysis(lookahead_conf, strategy_obj2)
@@ -267,21 +274,14 @@ def test_lookahead_helper_export_to_csv(lookahead_conf):
instance2.current_analysis = analysis2
LookaheadAnalysisSubFunctions.export_to_csv(lookahead_conf, [instance2])
saved_data2 = pd.read_csv(lookahead_conf['lookahead_analysis_exportfilename'])
saved_data2 = pd.read_csv(lookahead_conf["lookahead_analysis_exportfilename"])
assert expected_data2.equals(saved_data2)
# 3rd check: now we add a new row to an already existing file
expected_values3 = [
[
'file1.py', 'strat1', False,
22, 21, 20,
"falseIndicator3,falseIndicator4"
],
[
'file3.py', 'strat3', True,
32, 31, 30, "falseIndicator5,falseIndicator6"
],
["file1.py", "strat1", False, 22, 21, 20, "falseIndicator3,falseIndicator4"],
["file3.py", "strat3", True, 32, 31, 30, "falseIndicator5,falseIndicator6"],
]
expected_data3 = pd.DataFrame(expected_values3, columns=expected_columns)
@@ -291,13 +291,13 @@ def test_lookahead_helper_export_to_csv(lookahead_conf):
analysis3.total_signals = 32
analysis3.false_entry_signals = 31
analysis3.false_exit_signals = 30
analysis3.false_indicators.append('falseIndicator5')
analysis3.false_indicators.append('falseIndicator6')
lookahead_conf['lookahead_analysis_exportfilename'] = "temp_csv_lookahead_analysis.csv"
analysis3.false_indicators.append("falseIndicator5")
analysis3.false_indicators.append("falseIndicator6")
lookahead_conf["lookahead_analysis_exportfilename"] = "temp_csv_lookahead_analysis.csv"
strategy_obj3 = {
'name': "strat3",
'location': Path("file3.py"),
"name": "strat3",
"location": Path("file3.py"),
}
instance3 = LookaheadAnalysis(lookahead_conf, strategy_obj3)
@@ -305,67 +305,66 @@ def test_lookahead_helper_export_to_csv(lookahead_conf):
instance3.current_analysis = analysis3
LookaheadAnalysisSubFunctions.export_to_csv(lookahead_conf, [instance3])
saved_data3 = pd.read_csv(lookahead_conf['lookahead_analysis_exportfilename'])
saved_data3 = pd.read_csv(lookahead_conf["lookahead_analysis_exportfilename"])
assert expected_data3.equals(saved_data3)
# remove csv file after the test is done
if Path(lookahead_conf['lookahead_analysis_exportfilename']).exists():
Path(lookahead_conf['lookahead_analysis_exportfilename']).unlink()
if Path(lookahead_conf["lookahead_analysis_exportfilename"]).exists():
Path(lookahead_conf["lookahead_analysis_exportfilename"]).unlink()
def test_initialize_single_lookahead_analysis(lookahead_conf, mocker, caplog):
mocker.patch('freqtrade.data.history.get_timerange', get_timerange)
mocker.patch(f'{EXMS}.get_fee', return_value=0.0)
mocker.patch(f'{EXMS}.get_min_pair_stake_amount', return_value=0.00001)
mocker.patch(f'{EXMS}.get_max_pair_stake_amount', return_value=float('inf'))
mocker.patch("freqtrade.data.history.get_timerange", get_timerange)
mocker.patch(f"{EXMS}.get_fee", return_value=0.0)
mocker.patch(f"{EXMS}.get_min_pair_stake_amount", return_value=0.00001)
mocker.patch(f"{EXMS}.get_max_pair_stake_amount", return_value=float("inf"))
patch_exchange(mocker)
mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist',
PropertyMock(return_value=['UNITTEST/BTC']))
lookahead_conf['pairs'] = ['UNITTEST/USDT']
mocker.patch(
"freqtrade.plugins.pairlistmanager.PairListManager.whitelist",
PropertyMock(return_value=["UNITTEST/BTC"]),
)
lookahead_conf["pairs"] = ["UNITTEST/USDT"]
lookahead_conf['timeframe'] = '5m'
lookahead_conf['timerange'] = '20180119-20180122'
start_mock = mocker.patch('freqtrade.optimize.analysis.lookahead.LookaheadAnalysis.start')
lookahead_conf["timeframe"] = "5m"
lookahead_conf["timerange"] = "20180119-20180122"
start_mock = mocker.patch("freqtrade.optimize.analysis.lookahead.LookaheadAnalysis.start")
strategy_obj = {
'name': "strategy_test_v3_with_lookahead_bias",
'location': Path(lookahead_conf['strategy_path'], f"{lookahead_conf['strategy']}.py")
"name": "strategy_test_v3_with_lookahead_bias",
"location": Path(lookahead_conf["strategy_path"], f"{lookahead_conf['strategy']}.py"),
}
instance = LookaheadAnalysisSubFunctions.initialize_single_lookahead_analysis(
lookahead_conf, strategy_obj)
lookahead_conf, strategy_obj
)
assert log_has_re(r"Bias test of .* started\.", caplog)
assert start_mock.call_count == 1
assert instance.strategy_obj['name'] == "strategy_test_v3_with_lookahead_bias"
assert instance.strategy_obj["name"] == "strategy_test_v3_with_lookahead_bias"
@pytest.mark.parametrize('scenario', [
'no_bias', 'bias1'
])
@pytest.mark.parametrize("scenario", ["no_bias", "bias1"])
def test_biased_strategy(lookahead_conf, mocker, caplog, scenario) -> None:
patch_exchange(mocker)
mocker.patch('freqtrade.data.history.get_timerange', get_timerange)
mocker.patch(f'{EXMS}.get_fee', return_value=0.0)
mocker.patch(f'{EXMS}.get_min_pair_stake_amount', return_value=0.00001)
mocker.patch(f'{EXMS}.get_max_pair_stake_amount', return_value=float('inf'))
mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist',
PropertyMock(return_value=['UNITTEST/BTC']))
lookahead_conf['pairs'] = ['UNITTEST/USDT']
mocker.patch("freqtrade.data.history.get_timerange", get_timerange)
mocker.patch(f"{EXMS}.get_fee", return_value=0.0)
mocker.patch(f"{EXMS}.get_min_pair_stake_amount", return_value=0.00001)
mocker.patch(f"{EXMS}.get_max_pair_stake_amount", return_value=float("inf"))
mocker.patch(
"freqtrade.plugins.pairlistmanager.PairListManager.whitelist",
PropertyMock(return_value=["UNITTEST/BTC"]),
)
lookahead_conf["pairs"] = ["UNITTEST/USDT"]
lookahead_conf['timeframe'] = '5m'
lookahead_conf['timerange'] = '20180119-20180122'
lookahead_conf["timeframe"] = "5m"
lookahead_conf["timerange"] = "20180119-20180122"
# Patch scenario Parameter to allow for easy selection
mocker.patch('freqtrade.strategy.hyper.HyperStrategyMixin.load_params_from_file',
return_value={
'params': {
"buy": {
"scenario": scenario
}
}
})
mocker.patch(
"freqtrade.strategy.hyper.HyperStrategyMixin.load_params_from_file",
return_value={"params": {"buy": {"scenario": scenario}}},
)
strategy_obj = {'name': "strategy_test_v3_with_lookahead_bias"}
strategy_obj = {"name": "strategy_test_v3_with_lookahead_bias"}
instance = LookaheadAnalysis(lookahead_conf, strategy_obj)
instance.start()
# Assert init correct
@@ -380,10 +379,10 @@ def test_biased_strategy(lookahead_conf, mocker, caplog, scenario) -> None:
def test_config_overrides(lookahead_conf):
lookahead_conf['max_open_trades'] = 0
lookahead_conf['dry_run_wallet'] = 1
lookahead_conf['pairs'] = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT']
lookahead_conf["max_open_trades"] = 0
lookahead_conf["dry_run_wallet"] = 1
lookahead_conf["pairs"] = ["BTC/USDT", "ETH/USDT", "SOL/USDT"]
lookahead_conf = LookaheadAnalysisSubFunctions.calculate_config_overrides(lookahead_conf)
assert lookahead_conf['dry_run_wallet'] == 1000000000
assert lookahead_conf['max_open_trades'] == 3
assert lookahead_conf["dry_run_wallet"] == 1000000000
assert lookahead_conf["max_open_trades"] == 3