Elffuss BraidHub

kikocis/freqtrade public

Merge pull request #4703 from freqtrade/decimal_space

Add SKDecimal Space
Changeset3efe3ca15543a09fab8cab977bb05f4e32ab427068772456cad6f122d41a53ef
AuthorMatthias <xmatthias@outlook.com> · 2021-04-12 19:18 +02:00
CommitterGitHub <noreply@github.com> · 2021-04-12 19:18 +02:00
Parents462f899044b1, 25373500f6ee

Browse the files at this changeset

5 files changed

added freqtrade/optimize/decimalspace.py +32 −0
@@ -0,0 +1,32 @@
1+import numpy as np
2+from skopt.space import Integer
3+
4+
5+class SKDecimal(Integer):
6+
7+ def __init__(self, low, high, decimals=3, prior="uniform", base=10, transform=None,
8+ name=None, dtype=np.int64):
9+ self.decimals = decimals
10+ _low = int(low * pow(10, self.decimals))
11+ _high = int(high * pow(10, self.decimals))
12+ self.low_orig = low
13+ self.high_orig = high
14+
15+ super().__init__(_low, _high, prior, base, transform, name, dtype)
16+
17+ def __repr__(self):
18+ return "Decimal(low={}, high={}, decimals={}, prior='{}', transform='{}')".format(
19+ self.low_orig, self.high_orig, self.decimals, self.prior, self.transform_)
20+
21+ def __contains__(self, point):
22+ if isinstance(point, list):
23+ point = np.array(point)
24+ return self.low_orig <= point <= self.high_orig
25+
26+ def transform(self, Xt):
27+ aa = [int(x * pow(10, self.decimals)) for x in Xt]
28+ return super().transform(aa)
29+
30+ def inverse_transform(self, Xt):
31+ res = super().inverse_transform(Xt)
32+ return [round(x * pow(0.1, self.decimals), self.decimals) for x in res]
modified freqtrade/optimize/hyperopt_auto.py +2 −2
@@ -27,7 +27,7 @@
2727 for attr_name, attr in self.strategy.enumerate_parameters('buy'):
2828 if attr.optimize:
2929 # noinspection PyProtectedMember
30- attr._set_value(params[attr_name])
30+ attr.value = params[attr_name]
3131 return self.strategy.populate_buy_trend(dataframe, metadata)
3232
3333 return populate_buy_trend
@@ -37,7 +37,7 @@
3737 for attr_name, attr in self.strategy.enumerate_parameters('sell'):
3838 if attr.optimize:
3939 # noinspection PyProtectedMember
40- attr._set_value(params[attr_name])
40+ attr.value = params[attr_name]
4141 return self.strategy.populate_sell_trend(dataframe, metadata)
4242
4343 return populate_sell_trend
modified freqtrade/strategy/hyper.py +51 −49
@@ -10,6 +10,7 @@
1010
1111 with suppress(ImportError):
1212 from skopt.space import Integer, Real, Categorical
13+ from freqtrade.optimize.decimalspace import SKDecimal
1314
1415 from freqtrade.exceptions import OperationalException
1516
@@ -24,9 +25,8 @@
2425 category: Optional[str]
2526 default: Any
2627 value: Any
27- opt_range: Sequence[Any]
2828
29- def __init__(self, *, opt_range: Sequence[Any], default: Any, space: Optional[str] = None,
29+ def __init__(self, *, default: Any, space: Optional[str] = None,
3030 optimize: bool = True, load: bool = True, **kwargs):
3131 """
3232 Initialize hyperopt-optimizable parameter.
@@ -43,7 +43,6 @@
4343 self.category = space
4444 self._space_params = kwargs
4545 self.value = default
46- self.opt_range = opt_range
4746 self.optimize = optimize
4847 self.load = load
4948
@@ -51,24 +50,51 @@
5150 return f'{self.__class__.__name__}({self.value})'
5251
5352 @abstractmethod
54- def get_space(self, name: str) -> Union['Integer', 'Real', 'Categorical']:
53+ def get_space(self, name: str) -> Union['Integer', 'Real', 'SKDecimal', 'Categorical']:
5554 """
5655 Get-space - will be used by Hyperopt to get the hyperopt Space
5756 """
5857
59- def _set_value(self, value: Any):
58+
59+class NumericParameter(BaseParameter):
60+ """ Internal parameter used for Numeric purposes """
61+ float_or_int = Union[int, float]
62+ default: float_or_int
63+ value: float_or_int
64+
65+ def __init__(self, low: Union[float_or_int, Sequence[float_or_int]],
66+ high: Optional[float_or_int] = None, *, default: float_or_int,
67+ space: Optional[str] = None, optimize: bool = True, load: bool = True, **kwargs):
6068 """
61- Update current value. Used by hyperopt functions for the purpose where optimization and
62- value spaces differ.
63- :param value: A numerical value.
69+ Initialize hyperopt-optimizable numeric parameter.
70+ Cannot be instantiated, but provides the validation for other numeric parameters
71+ :param low: Lower end (inclusive) of optimization space or [low, high].
72+ :param high: Upper end (inclusive) of optimization space.
73+ Must be none of entire range is passed first parameter.
74+ :param default: A default value.
75+ :param space: A parameter category. Can be 'buy' or 'sell'. This parameter is optional if
76+ parameter fieldname is prefixed with 'buy_' or 'sell_'.
77+ :param optimize: Include parameter in hyperopt optimizations.
78+ :param load: Load parameter value from {space}_params.
79+ :param kwargs: Extra parameters to skopt.space.*.
6480 """
65- self.value = value
81+ if high is not None and isinstance(low, Sequence):
82+ raise OperationalException(f'{self.__class__.__name__} space invalid.')
83+ if high is None or isinstance(low, Sequence):
84+ if not isinstance(low, Sequence) or len(low) != 2:
85+ raise OperationalException(f'{self.__class__.__name__} space must be [low, high]')
86+ self.low, self.high = low
87+ else:
88+ self.low = low
89+ self.high = high
90+
91+ super().__init__(default=default, space=space, optimize=optimize,
92+ load=load, **kwargs)
6693
6794
68-class IntParameter(BaseParameter):
95+class IntParameter(NumericParameter):
6996 default: int
7097 value: int
71- opt_range: Sequence[int]
7298
7399 def __init__(self, low: Union[int, Sequence[int]], high: Optional[int] = None, *, default: int,
74100 space: Optional[str] = None, optimize: bool = True, load: bool = True, **kwargs):
@@ -84,15 +110,8 @@
84110 :param load: Load parameter value from {space}_params.
85111 :param kwargs: Extra parameters to skopt.space.Integer.
86112 """
87- if high is not None and isinstance(low, Sequence):
88- raise OperationalException('IntParameter space invalid.')
89- if high is None or isinstance(low, Sequence):
90- if not isinstance(low, Sequence) or len(low) != 2:
91- raise OperationalException('IntParameter space must be [low, high]')
92- opt_range = low
93- else:
94- opt_range = [low, high]
95- super().__init__(opt_range=opt_range, default=default, space=space, optimize=optimize,
113+
114+ super().__init__(low=low, high=high, default=default, space=space, optimize=optimize,
96115 load=load, **kwargs)
97116
98117 def get_space(self, name: str) -> 'Integer':
@@ -100,13 +119,12 @@
100119 Create skopt optimization space.
101120 :param name: A name of parameter field.
102121 """
103- return Integer(*self.opt_range, name=name, **self._space_params)
122+ return Integer(low=self.low, high=self.high, name=name, **self._space_params)
104123
105124
106-class RealParameter(BaseParameter):
125+class RealParameter(NumericParameter):
107126 default: float
108127 value: float
109- opt_range: Sequence[float]
110128
111129 def __init__(self, low: Union[float, Sequence[float]], high: Optional[float] = None, *,
112130 default: float, space: Optional[str] = None, optimize: bool = True,
@@ -123,15 +141,7 @@
123141 :param load: Load parameter value from {space}_params.
124142 :param kwargs: Extra parameters to skopt.space.Real.
125143 """
126- if high is not None and isinstance(low, Sequence):
127- raise OperationalException(f'{self.__class__.__name__} space invalid.')
128- if high is None or isinstance(low, Sequence):
129- if not isinstance(low, Sequence) or len(low) != 2:
130- raise OperationalException(f'{self.__class__.__name__} space must be [low, high]')
131- opt_range = low
132- else:
133- opt_range = [low, high]
134- super().__init__(opt_range=opt_range, default=default, space=space, optimize=optimize,
144+ super().__init__(low=low, high=high, default=default, space=space, optimize=optimize,
135145 load=load, **kwargs)
136146
137147 def get_space(self, name: str) -> 'Real':
@@ -139,13 +149,12 @@
139149 Create skopt optimization space.
140150 :param name: A name of parameter field.
141151 """
142- return Real(*self.opt_range, name=name, **self._space_params)
152+ return Real(low=self.low, high=self.high, name=name, **self._space_params)
143153
144154
145-class DecimalParameter(RealParameter):
155+class DecimalParameter(NumericParameter):
146156 default: float
147157 value: float
148- opt_range: Sequence[float]
149158
150159 def __init__(self, low: Union[float, Sequence[float]], high: Optional[float] = None, *,
151160 default: float, decimals: int = 3, space: Optional[str] = None,
@@ -161,29 +170,21 @@
161170 parameter fieldname is prefixed with 'buy_' or 'sell_'.
162171 :param optimize: Include parameter in hyperopt optimizations.
163172 :param load: Load parameter value from {space}_params.
164- :param kwargs: Extra parameters to skopt.space.Real.
173+ :param kwargs: Extra parameters to skopt.space.Integer.
165174 """
166175 self._decimals = decimals
167176 default = round(default, self._decimals)
177+
168178 super().__init__(low=low, high=high, default=default, space=space, optimize=optimize,
169179 load=load, **kwargs)
170180
171- def get_space(self, name: str) -> 'Integer':
181+ def get_space(self, name: str) -> 'SKDecimal':
172182 """
173183 Create skopt optimization space.
174184 :param name: A name of parameter field.
175185 """
176- low = int(self.opt_range[0] * pow(10, self._decimals))
177- high = int(self.opt_range[1] * pow(10, self._decimals))
178- return Integer(low, high, name=name, **self._space_params)
179-
180- def _set_value(self, value: int):
181- """
182- Update current value. Used by hyperopt functions for the purpose where optimization and
183- value spaces differ.
184- :param value: An integer value.
185- """
186- self.value = round(value * pow(0.1, self._decimals), self._decimals)
186+ return SKDecimal(low=self.low, high=self.high, decimals=self._decimals, name=name,
187+ **self._space_params)
187188
188189
189190 class CategoricalParameter(BaseParameter):
@@ -208,7 +209,8 @@
208209 if len(categories) < 2:
209210 raise OperationalException(
210211 'CategoricalParameter space must be [a, b, ...] (at least two parameters)')
211- super().__init__(opt_range=categories, default=default, space=space, optimize=optimize,
212+ self.opt_range = categories
213+ super().__init__(default=default, space=space, optimize=optimize,
212214 load=load, **kwargs)
213215
214216 def get_space(self, name: str) -> 'Categorical':
modified tests/optimize/test_hyperopt.py +18 −0
@@ -15,6 +15,7 @@
1515 from freqtrade.commands.optimize_commands import setup_optimize_configuration, start_hyperopt
1616 from freqtrade.data.history import load_data
1717 from freqtrade.exceptions import OperationalException
18+from freqtrade.optimize.decimalspace import SKDecimal
1819 from freqtrade.optimize.hyperopt import Hyperopt
1920 from freqtrade.optimize.hyperopt_auto import HyperOptAuto
2021 from freqtrade.optimize.hyperopt_tools import HyperoptTools
@@ -1104,3 +1105,20 @@
11041105 assert isinstance(hyperopt.custom_hyperopt, HyperOptAuto)
11051106
11061107 hyperopt.start()
1108+
1109+
1110+def test_SKDecimal():
1111+ space = SKDecimal(1, 2, decimals=2)
1112+ assert 1.5 in space
1113+ assert 2.5 not in space
1114+ assert space.low == 100
1115+ assert space.high == 200
1116+
1117+ assert space.inverse_transform([200]) == [2.0]
1118+ assert space.inverse_transform([100]) == [1.0]
1119+ assert space.inverse_transform([150, 160]) == [1.5, 1.6]
1120+
1121+ assert space.transform([1.5]) == [150]
1122+ assert space.transform([2.0]) == [200]
1123+ assert space.transform([1.0]) == [100]
1124+ assert space.transform([1.5, 1.6]) == [150, 160]
modified tests/strategy/test_interface.py +0 −2
@@ -596,8 +596,6 @@
596596 fltpar = DecimalParameter(low=0.0, high=5.5, default=1.0004, decimals=3, space='buy')
597597 assert isinstance(fltpar.get_space(''), Integer)
598598 assert fltpar.value == 1
599- fltpar._set_value(2222)
600- assert fltpar.value == 2.222
601599
602600 catpar = CategoricalParameter(['buy_rsi', 'buy_macd', 'buy_none'],
603601 default='buy_macd', space='buy')