Ensure hyper param file can be loaded

closes #8452
This commit is contained in:
Matthias 2023-04-04 20:04:28 +02:00
parent fe02f611fb
commit f03a99918a
3 changed files with 21 additions and 8 deletions

View File

@ -23,6 +23,8 @@ logger = logging.getLogger(__name__)
NON_OPT_PARAM_APPENDIX = " # value loaded from strategy" NON_OPT_PARAM_APPENDIX = " # value loaded from strategy"
HYPER_PARAMS_FILE_FORMAT = rapidjson.NM_NATIVE | rapidjson.NM_NAN
def hyperopt_serializer(x): def hyperopt_serializer(x):
if isinstance(x, np.integer): if isinstance(x, np.integer):
@ -76,9 +78,18 @@ class HyperoptTools():
with filename.open('w') as f: with filename.open('w') as f:
rapidjson.dump(final_params, f, indent=2, rapidjson.dump(final_params, f, indent=2,
default=hyperopt_serializer, default=hyperopt_serializer,
number_mode=rapidjson.NM_NATIVE | rapidjson.NM_NAN number_mode=HYPER_PARAMS_FILE_FORMAT
) )
@staticmethod
def load_params(filename: Path) -> Dict:
"""
Load parameters from file
"""
with filename.open('r') as f:
params = rapidjson.load(f, number_mode=HYPER_PARAMS_FILE_FORMAT)
return params
@staticmethod @staticmethod
def try_export_params(config: Config, strategy_name: str, params: Dict): def try_export_params(config: Config, strategy_name: str, params: Dict):
if params.get(FTHYPT_FILEVERSION, 1) >= 2 and not config.get('disableparamexport', False): if params.get(FTHYPT_FILEVERSION, 1) >= 2 and not config.get('disableparamexport', False):
@ -189,7 +200,7 @@ class HyperoptTools():
for s in ['buy', 'sell', 'protection', for s in ['buy', 'sell', 'protection',
'roi', 'stoploss', 'trailing', 'max_open_trades']: 'roi', 'stoploss', 'trailing', 'max_open_trades']:
HyperoptTools._params_update_for_json(result_dict, params, non_optimized, s) HyperoptTools._params_update_for_json(result_dict, params, non_optimized, s)
print(rapidjson.dumps(result_dict, default=str, number_mode=rapidjson.NM_NATIVE)) print(rapidjson.dumps(result_dict, default=str, number_mode=HYPER_PARAMS_FILE_FORMAT))
else: else:
HyperoptTools._params_pretty_print(params, 'buy', "Buy hyperspace params:", HyperoptTools._params_pretty_print(params, 'buy', "Buy hyperspace params:",

View File

@ -8,7 +8,7 @@ from typing import Any, Dict, Iterator, List, Optional, Tuple, Type, Union
from freqtrade.constants import Config from freqtrade.constants import Config
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
from freqtrade.misc import deep_merge_dicts, json_load from freqtrade.misc import deep_merge_dicts
from freqtrade.optimize.hyperopt_tools import HyperoptTools from freqtrade.optimize.hyperopt_tools import HyperoptTools
from freqtrade.strategy.parameters import BaseParameter from freqtrade.strategy.parameters import BaseParameter
@ -124,8 +124,7 @@ class HyperStrategyMixin:
if filename.is_file(): if filename.is_file():
logger.info(f"Loading parameters from file {filename}") logger.info(f"Loading parameters from file {filename}")
try: try:
with filename.open('r') as f: params = HyperoptTools.load_params(filename)
params = json_load(f)
if params.get('strategy_name') != self.__class__.__name__: if params.get('strategy_name') != self.__class__.__name__:
raise OperationalException('Invalid parameter file provided.') raise OperationalException('Invalid parameter file provided.')
return params return params

View File

@ -986,7 +986,8 @@ def test_auto_hyperopt_interface_loadparams(default_conf, mocker, caplog):
} }
} }
} }
mocker.patch('freqtrade.strategy.hyper.json_load', return_value=expected_result) mocker.patch('freqtrade.strategy.hyper.HyperoptTools.load_params',
return_value=expected_result)
PairLocks.timeframe = default_conf['timeframe'] PairLocks.timeframe = default_conf['timeframe']
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
assert strategy.stoploss == -0.05 assert strategy.stoploss == -0.05
@ -1005,11 +1006,13 @@ def test_auto_hyperopt_interface_loadparams(default_conf, mocker, caplog):
} }
} }
mocker.patch('freqtrade.strategy.hyper.json_load', return_value=expected_result) mocker.patch('freqtrade.strategy.hyper.HyperoptTools.load_params',
return_value=expected_result)
with pytest.raises(OperationalException, match="Invalid parameter file provided."): with pytest.raises(OperationalException, match="Invalid parameter file provided."):
StrategyResolver.load_strategy(default_conf) StrategyResolver.load_strategy(default_conf)
mocker.patch('freqtrade.strategy.hyper.json_load', MagicMock(side_effect=ValueError())) mocker.patch('freqtrade.strategy.hyper.HyperoptTools.load_params',
MagicMock(side_effect=ValueError()))
StrategyResolver.load_strategy(default_conf) StrategyResolver.load_strategy(default_conf)
assert log_has("Invalid parameter file format.", caplog) assert log_has("Invalid parameter file format.", caplog)