[SQUASH] Address PR comments.

* Split Parameter into IntParameter/FloatParameter/CategoricalParameter.
* Rename IHyperStrategy to HyperStrategyMixin and use it as mixin.
* --hyperopt parameter is now optional if strategy uses HyperStrategyMixin.
* Use OperationalException() instead of asserts.
This commit is contained in:
Rokas Kupstys
2021-03-24 10:32:34 +02:00
parent 0a205f52b0
commit bb89e44e19
6 changed files with 138 additions and 51 deletions

View File

@@ -23,6 +23,7 @@ from pandas import DataFrame
from freqtrade.constants import DATETIME_PRINT_FORMAT, LAST_BT_RESULT_FN
from freqtrade.data.converter import trim_dataframe
from freqtrade.data.history import get_timerange
from freqtrade.exceptions import OperationalException
from freqtrade.misc import file_dump_json, plural
from freqtrade.optimize.backtesting import Backtesting
# Import IHyperOpt and IHyperOptLoss to allow unpickling classes from these modules
@@ -68,7 +69,11 @@ class Hyperopt:
self.backtesting = Backtesting(self.config)
if self.config['hyperopt'] == 'HyperOptAuto':
if not self.config.get('hyperopt'):
if not getattr(self.backtesting.strategy, 'HYPER_STRATEGY', False):
raise OperationalException('Strategy is not auto-hyperoptable. Specify --hyperopt '
'parameter or add HyperStrategyMixin mixin to your '
'strategy class.')
self.custom_hyperopt = HyperOptAuto(self.config)
else:
self.custom_hyperopt = HyperOptResolver.load_hyperopt(self.config)

View File

@@ -1,7 +1,7 @@
"""
HyperOptAuto class.
This module implements a convenience auto-hyperopt class, which can be used together with strategies that implement
IHyperStrategy interface.
This module implements a convenience auto-hyperopt class, which can be used together with strategies
that implement IHyperStrategy interface.
"""
from typing import Any, Callable, Dict, List
from pandas import DataFrame
@@ -13,26 +13,31 @@ from freqtrade.optimize.hyperopt_interface import IHyperOpt
# noinspection PyUnresolvedReferences
class HyperOptAuto(IHyperOpt):
"""
This class delegates functionality to Strategy(IHyperStrategy) and Strategy.HyperOpt classes. Most of the time
Strategy.HyperOpt class would only implement indicator_space and sell_indicator_space methods, but other hyperopt
methods can be overridden as well.
This class delegates functionality to Strategy(IHyperStrategy) and Strategy.HyperOpt classes.
Most of the time Strategy.HyperOpt class would only implement indicator_space and
sell_indicator_space methods, but other hyperopt methods can be overridden as well.
"""
def buy_strategy_generator(self, params: Dict[str, Any]) -> Callable:
assert hasattr(self.strategy, 'enumerate_parameters'), 'Strategy must inherit from IHyperStrategy.'
if not getattr(self.strategy, 'HYPER_STRATEGY', False):
raise OperationalException('Strategy must inherit from IHyperStrategy.')
def populate_buy_trend(dataframe: DataFrame, metadata: dict):
for attr_name, attr in self.strategy.enumerate_parameters('buy'):
attr.value = params[attr_name]
return self.strategy.populate_buy_trend(dataframe, metadata)
return populate_buy_trend
def sell_strategy_generator(self, params: Dict[str, Any]) -> Callable:
assert hasattr(self.strategy, 'enumerate_parameters'), 'Strategy must inherit from IHyperStrategy.'
if not getattr(self.strategy, 'HYPER_STRATEGY', False):
raise OperationalException('Strategy must inherit from IHyperStrategy.')
def populate_buy_trend(dataframe: DataFrame, metadata: dict):
for attr_name, attr in self.strategy.enumerate_parameters('sell'):
attr.value = params[attr_name]
return self.strategy.populate_sell_trend(dataframe, metadata)
return populate_buy_trend
def _get_func(self, name) -> Callable:
@@ -49,7 +54,8 @@ class HyperOptAuto(IHyperOpt):
return default_func
def _generate_indicator_space(self, category):
assert hasattr(self.strategy, 'enumerate_parameters'), 'Strategy must inherit from IHyperStrategy.'
if not getattr(self.strategy, 'HYPER_STRATEGY', False):
raise OperationalException('Strategy must inherit from IHyperStrategy.')
for attr_name, attr in self.strategy.enumerate_parameters(category):
yield attr.get_space(attr_name)

View File

@@ -5,15 +5,14 @@ This module defines the interface to apply for hyperopt
import logging
import math
from abc import ABC
from typing import Any, Callable, Dict, List
from typing import Any, Callable, Dict, List, Union
from skopt.space import Categorical, Dimension, Integer, Real
from freqtrade.exceptions import OperationalException
from freqtrade.exchange import timeframe_to_minutes
from freqtrade.misc import round_dict
from freqtrade.strategy import IStrategy
from freqtrade.strategy import IStrategy, HyperStrategyMixin
logger = logging.getLogger(__name__)
@@ -35,7 +34,7 @@ class IHyperOpt(ABC):
"""
ticker_interval: str # DEPRECATED
timeframe: str
strategy: IStrategy
strategy: Union[IStrategy, HyperStrategyMixin]
def __init__(self, config: dict) -> None:
self.config = config