Elffuss BraidHub

kikocis/freqtrade public

develop · 17.5 KiBRenderedRawPermalink
1# Advanced Hyperopt
2
3This page explains some advanced Hyperopt topics that may require higher
4coding skills and Python knowledge than creation of an ordinal hyperoptimization
5class.
6
7## Creating and using a custom loss function
8
9To use a custom loss function class, make sure that the function `hyperopt_loss_function` is defined in your custom hyperopt loss class.
10For the sample below, you then need to add the command line parameter `--hyperopt-loss SuperDuperHyperOptLoss` to your hyperopt call so this function is being used.
11
12A sample of this can be found below, which is identical to the Default Hyperopt loss implementation. A full sample can be found in [userdata/hyperopts](https://github.com/freqtrade/freqtrade/blob/develop/freqtrade/templates/sample_hyperopt_loss.py).
13
14``` python
15from datetime import datetime
16from typing import Dict
17
18from pandas import DataFrame
19
20from freqtrade.optimize.hyperopt import IHyperOptLoss
21
22TARGET_TRADES = 600
23EXPECTED_MAX_PROFIT = 3.0
24MAX_ACCEPTED_TRADE_DURATION = 300
25
26class SuperDuperHyperOptLoss(IHyperOptLoss):
27 """
28 Defines the default loss function for hyperopt
29 """
30
31 @staticmethod
32 def hyperopt_loss_function(results: DataFrame, trade_count: int,
33 min_date: datetime, max_date: datetime,
34 config: Dict, processed: Dict[str, DataFrame],
35 *args, **kwargs) -> float:
36 """
37 Objective function, returns smaller number for better results
38 This is the legacy algorithm (used until now in freqtrade).
39 Weights are distributed as follows:
40 * 0.4 to trade duration
41 * 0.25: Avoiding trade loss
42 * 1.0 to total profit, compared to the expected value (`EXPECTED_MAX_PROFIT`) defined above
43 """
44 total_profit = results['profit_ratio'].sum()
45 trade_duration = results['trade_duration'].mean()
46
47 trade_loss = 1 - 0.25 * exp(-(trade_count - TARGET_TRADES) ** 2 / 10 ** 5.8)
48 profit_loss = max(0, 1 - total_profit / EXPECTED_MAX_PROFIT)
49 duration_loss = 0.4 * min(trade_duration / MAX_ACCEPTED_TRADE_DURATION, 1)
50 result = trade_loss + profit_loss + duration_loss
51 return result
52```
53
54Currently, the arguments are:
55
56* `results`: DataFrame containing the result
57 The following columns are available in results (corresponds to the output-file of backtesting when used with `--export trades`):
58 `pair, profit_ratio, profit_abs, open_date, open_rate, fee_open, close_date, close_rate, fee_close, amount, trade_duration, is_open, sell_reason, stake_amount, min_rate, max_rate, stop_loss_ratio, stop_loss_abs`
59* `trade_count`: Amount of trades (identical to `len(results)`)
60* `min_date`: Start date of the timerange used
61* `min_date`: End date of the timerange used
62* `config`: Config object used (Note: Not all strategy-related parameters will be updated here if they are part of a hyperopt space).
63* `processed`: Dict of Dataframes with the pair as keys containing the data used for backtesting.
64
65This function needs to return a floating point number (`float`). Smaller numbers will be interpreted as better results. The parameters and balancing for this is up to you.
66
67!!! Note
68 This function is called once per iteration - so please make sure to have this as optimized as possible to not slow hyperopt down unnecessarily.
69
70!!! Note
71 Please keep the arguments `*args` and `**kwargs` in the interface to allow us to extend this interface later.
72
73## Overriding pre-defined spaces
74
75To override a pre-defined space (`roi_space`, `generate_roi_table`, `stoploss_space`, `trailing_space`), define a nested class called Hyperopt and define the required spaces as follows:
76
77```python
78class MyAwesomeStrategy(IStrategy):
79 class HyperOpt:
80 # Define a custom stoploss space.
81 def stoploss_space(self):
82 return [SKDecimal(-0.05, -0.01, decimals=3, name='stoploss')]
83```
84
85## Space options
86
87For the additional spaces, scikit-optimize (in combination with Freqtrade) provides the following space types:
88
89* `Categorical` - Pick from a list of categories (e.g. `Categorical(['a', 'b', 'c'], name="cat")`)
90* `Integer` - Pick from a range of whole numbers (e.g. `Integer(1, 10, name='rsi')`)
91* `SKDecimal` - Pick from a range of decimal numbers with limited precision (e.g. `SKDecimal(0.1, 0.5, decimals=3, name='adx')`). *Available only with freqtrade*.
92* `Real` - Pick from a range of decimal numbers with full precision (e.g. `Real(0.1, 0.5, name='adx')`
93
94You can import all of these from `freqtrade.optimize.space`, although `Categorical`, `Integer` and `Real` are only aliases for their corresponding scikit-optimize Spaces. `SKDecimal` is provided by freqtrade for faster optimizations.
95
96``` python
97from freqtrade.optimize.space import Categorical, Dimension, Integer, SKDecimal, Real # noqa
98```
99
100!!! Hint "SKDecimal vs. Real"
101 We recommend to use `SKDecimal` instead of the `Real` space in almost all cases. While the Real space provides full accuracy (up to ~16 decimal places) - this precision is rarely needed, and leads to unnecessary long hyperopt times.
102
103 Assuming the definition of a rather small space (`SKDecimal(0.10, 0.15, decimals=2, name='xxx')`) - SKDecimal will have 5 possibilities (`[0.10, 0.11, 0.12, 0.13, 0.14, 0.15]`).
104
105 A corresponding real space `Real(0.10, 0.15 name='xxx')` on the other hand has an almost unlimited number of possibilities (`[0.10, 0.010000000001, 0.010000000002, ... 0.014999999999, 0.01500000000]`).
106
107---
108
109## Legacy Hyperopt
110
111This Section explains the configuration of an explicit Hyperopt file (separate to the strategy).
112
113!!! Warning "Deprecated / legacy mode"
114 Since the 2021.4 release you no longer have to write a separate hyperopt class, but all strategies can be hyperopted.
115 Please read the [main hyperopt page](hyperopt.md) for more details.
116
117### Prepare hyperopt file
118
119Configuring an explicit hyperopt file is similar to writing your own strategy, and many tasks will be similar.
120
121!!! Tip "About this page"
122 For this page, we will be using a fictional strategy called `AwesomeStrategy` - which will be optimized using the `AwesomeHyperopt` class.
123
124#### Create a Custom Hyperopt File
125
126The simplest way to get started is to use the following command, which will create a new hyperopt file from a template, which will be located under `user_data/hyperopts/AwesomeHyperopt.py`.
127
128Let assume you want a hyperopt file `AwesomeHyperopt.py`:
129
130``` bash
131freqtrade new-hyperopt --hyperopt AwesomeHyperopt
132```
133
134#### Legacy Hyperopt checklist
135
136Checklist on all tasks / possibilities in hyperopt
137
138Depending on the space you want to optimize, only some of the below are required:
139
140* fill `buy_strategy_generator` - for buy signal optimization
141* fill `indicator_space` - for buy signal optimization
142* fill `sell_strategy_generator` - for sell signal optimization
143* fill `sell_indicator_space` - for sell signal optimization
144
145!!! Note
146 `populate_indicators` needs to create all indicators any of thee spaces may use, otherwise hyperopt will not work.
147
148Optional in hyperopt - can also be loaded from a strategy (recommended):
149
150* `populate_indicators` - fallback to create indicators
151* `populate_buy_trend` - fallback if not optimizing for buy space. should come from strategy
152* `populate_sell_trend` - fallback if not optimizing for sell space. should come from strategy
153
154!!! Note
155 You always have to provide a strategy to Hyperopt, even if your custom Hyperopt class contains all methods.
156 Assuming the optional methods are not in your hyperopt file, please use `--strategy AweSomeStrategy` which contains these methods so hyperopt can use these methods instead.
157
158Rarely you may also need to override:
159
160* `roi_space` - for custom ROI optimization (if you need the ranges for the ROI parameters in the optimization hyperspace that differ from default)
161* `generate_roi_table` - for custom ROI optimization (if you need the ranges for the values in the ROI table that differ from default or the number of entries (steps) in the ROI table which differs from the default 4 steps)
162* `stoploss_space` - for custom stoploss optimization (if you need the range for the stoploss parameter in the optimization hyperspace that differs from default)
163* `trailing_space` - for custom trailing stop optimization (if you need the ranges for the trailing stop parameters in the optimization hyperspace that differ from default)
164
165#### Defining a buy signal optimization
166
167Let's say you are curious: should you use MACD crossings or lower Bollinger
168Bands to trigger your buys. And you also wonder should you use RSI or ADX to
169help with those buy decisions. If you decide to use RSI or ADX, which values
170should I use for them? So let's use hyperparameter optimization to solve this
171mystery.
172
173We will start by defining a search space:
174
175```python
176 def indicator_space() -> List[Dimension]:
177 """
178 Define your Hyperopt space for searching strategy parameters
179 """
180 return [
181 Integer(20, 40, name='adx-value'),
182 Integer(20, 40, name='rsi-value'),
183 Categorical([True, False], name='adx-enabled'),
184 Categorical([True, False], name='rsi-enabled'),
185 Categorical(['bb_lower', 'macd_cross_signal'], name='trigger')
186 ]
187```
188
189Above definition says: I have five parameters I want you to randomly combine
190to find the best combination. Two of them are integer values (`adx-value` and `rsi-value`) and I want you test in the range of values 20 to 40.
191Then we have three category variables. First two are either `True` or `False`.
192We use these to either enable or disable the ADX and RSI guards.
193The last one we call `trigger` and use it to decide which buy trigger we want to use.
194
195So let's write the buy strategy generator using these values:
196
197```python
198 @staticmethod
199 def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
200 """
201 Define the buy strategy parameters to be used by Hyperopt.
202 """
203 def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
204 conditions = []
205 # GUARDS AND TRENDS
206 if 'adx-enabled' in params and params['adx-enabled']:
207 conditions.append(dataframe['adx'] > params['adx-value'])
208 if 'rsi-enabled' in params and params['rsi-enabled']:
209 conditions.append(dataframe['rsi'] < params['rsi-value'])
210
211 # TRIGGERS
212 if 'trigger' in params:
213 if params['trigger'] == 'bb_lower':
214 conditions.append(dataframe['close'] < dataframe['bb_lowerband'])
215 if params['trigger'] == 'macd_cross_signal':
216 conditions.append(qtpylib.crossed_above(
217 dataframe['macd'], dataframe['macdsignal']
218 ))
219
220 # Check that volume is not 0
221 conditions.append(dataframe['volume'] > 0)
222
223 if conditions:
224 dataframe.loc[
225 reduce(lambda x, y: x & y, conditions),
226 'buy'] = 1
227
228 return dataframe
229
230 return populate_buy_trend
231```
232
233Hyperopt will now call `populate_buy_trend()` many times (`epochs`) with different value combinations.
234It will use the given historical data and make buys based on the buy signals generated with the above function.
235Based on the results, hyperopt will tell you which parameter combination produced the best results (based on the configured [loss function](#loss-functions)).
236
237!!! Note
238 The above setup expects to find ADX, RSI and Bollinger Bands in the populated indicators.
239 When you want to test an indicator that isn't used by the bot currently, remember to
240 add it to the `populate_indicators()` method in your strategy or hyperopt file.
241
242#### Sell optimization
243
244Similar to the buy-signal above, sell-signals can also be optimized.
245Place the corresponding settings into the following methods
246
247* Inside `sell_indicator_space()` - the parameters hyperopt shall be optimizing.
248* Within `sell_strategy_generator()` - populate the nested method `populate_sell_trend()` to apply the parameters.
249
250The configuration and rules are the same than for buy signals.
251To avoid naming collisions in the search-space, please prefix all sell-spaces with `sell-`.
252
253### Execute Hyperopt
254
255Once you have updated your hyperopt configuration you can run it.
256Because hyperopt tries a lot of combinations to find the best parameters it will take time to get a good result. More time usually results in better results.
257
258We strongly recommend to use `screen` or `tmux` to prevent any connection loss.
259
260```bash
261freqtrade hyperopt --config config.json --hyperopt <hyperoptname> --hyperopt-loss <hyperoptlossname> --strategy <strategyname> -e 500 --spaces all
262```
263
264Use `<hyperoptname>` as the name of the custom hyperopt used.
265
266The `-e` option will set how many evaluations hyperopt will do. Since hyperopt uses Bayesian search, running too many epochs at once may not produce greater results. Experience has shown that best results are usually not improving much after 500-1000 epochs.
267Doing multiple runs (executions) with a few 1000 epochs and different random state will most likely produce different results.
268
269The `--spaces all` option determines that all possible parameters should be optimized. Possibilities are listed below.
270
271!!! Note
272 Hyperopt will store hyperopt results with the timestamp of the hyperopt start time.
273 Reading commands (`hyperopt-list`, `hyperopt-show`) can use `--hyperopt-filename <filename>` to read and display older hyperopt results.
274 You can find a list of filenames with `ls -l user_data/hyperopt_results/`.
275
276#### Running Hyperopt using methods from a strategy
277
278Hyperopt can reuse `populate_indicators`, `populate_buy_trend`, `populate_sell_trend` from your strategy, assuming these methods are **not** in your custom hyperopt file, and a strategy is provided.
279
280```bash
281freqtrade hyperopt --hyperopt AwesomeHyperopt --hyperopt-loss SharpeHyperOptLossDaily --strategy AwesomeStrategy
282```
283
284### Understand the Hyperopt Result
285
286Once Hyperopt is completed you can use the result to create a new strategy.
287Given the following result from hyperopt:
288
289```
290Best result:
291
292 44/100: 135 trades. Avg profit 0.57%. Total profit 0.03871918 BTC (0.7722Σ%). Avg duration 180.4 mins. Objective: 1.94367
293
294Buy hyperspace params:
295{ 'adx-value': 44,
296 'rsi-value': 29,
297 'adx-enabled': False,
298 'rsi-enabled': True,
299 'trigger': 'bb_lower'}
300```
301
302You should understand this result like:
303
304* The buy trigger that worked best was `bb_lower`.
305* You should not use ADX because `adx-enabled: False`)
306* You should **consider** using the RSI indicator (`rsi-enabled: True` and the best value is `29.0` (`rsi-value: 29.0`)
307
308You have to look inside your strategy file into `buy_strategy_generator()`
309method, what those values match to.
310
311So for example you had `rsi-value: 29.0` so we would look at `rsi`-block, that translates to the following code block:
312
313```python
314(dataframe['rsi'] < 29.0)
315```
316
317Translating your whole hyperopt result as the new buy-signal would then look like:
318
319```python
320def populate_buy_trend(self, dataframe: DataFrame) -> DataFrame:
321 dataframe.loc[
322 (
323 (dataframe['rsi'] < 29.0) & # rsi-value
324 dataframe['close'] < dataframe['bb_lowerband'] # trigger
325 ),
326 'buy'] = 1
327 return dataframe
328```
329
330### Validate backtesting results
331
332Once the optimized parameters and conditions have been implemented into your strategy, you should backtest the strategy to make sure everything is working as expected.
333
334To achieve same results (number of trades, their durations, profit, etc.) than during Hyperopt, please use same configuration and parameters (timerange, timeframe, ...) used for hyperopt `--dmmp`/`--disable-max-market-positions` and `--eps`/`--enable-position-stacking` for Backtesting.
335
336Should results don't match, please double-check to make sure you transferred all conditions correctly.
337Pay special care to the stoploss (and trailing stoploss) parameters, as these are often set in configuration files, which override changes to the strategy.
338You should also carefully review the log of your backtest to ensure that there were no parameters inadvertently set by the configuration (like `stoploss` or `trailing_stop`).
339
340### Sharing methods with your strategy
341
342Hyperopt classes provide access to the Strategy via the `strategy` class attribute.
343This can be a great way to reduce code duplication if used correctly, but will also complicate usage for inexperienced users.
344
345``` python
346from pandas import DataFrame
347from freqtrade.strategy.interface import IStrategy
348import freqtrade.vendor.qtpylib.indicators as qtpylib
349
350class MyAwesomeStrategy(IStrategy):
351
352 buy_params = {
353 'rsi-value': 30,
354 'adx-value': 35,
355 }
356
357 def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
358 return self.buy_strategy_generator(self.buy_params, dataframe, metadata)
359
360 @staticmethod
361 def buy_strategy_generator(params, dataframe: DataFrame, metadata: dict) -> DataFrame:
362 dataframe.loc[
363 (
364 qtpylib.crossed_above(dataframe['rsi'], params['rsi-value']) &
365 dataframe['adx'] > params['adx-value']) &
366 dataframe['volume'] > 0
367 )
368 , 'buy'] = 1
369 return dataframe
370
371class MyAwesomeHyperOpt(IHyperOpt):
372 ...
373 @staticmethod
374 def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
375 """
376 Define the buy strategy parameters to be used by Hyperopt.
377 """
378 def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame:
379 # Call strategy's buy strategy generator
380 return self.StrategyClass.buy_strategy_generator(params, dataframe, metadata)
381
382 return populate_buy_trend
383```