Elffuss BraidHub

kikocis/freqtrade public

develop · 42.2 KiBRawPermalink
1# pragma pylint: disable=missing-docstring,W0212,C0103
2import locale
3import logging
4import re
5from datetime import datetime
6from pathlib import Path
7from typing import Dict, List
8from unittest.mock import MagicMock
9
10import pandas as pd
11import pytest
12from arrow import Arrow
13from filelock import Timeout
14
15from freqtrade.commands.optimize_commands import setup_optimize_configuration, start_hyperopt
16from freqtrade.data.history import load_data
17from freqtrade.exceptions import OperationalException
18from freqtrade.optimize.hyperopt import Hyperopt
19from freqtrade.optimize.hyperopt_auto import HyperOptAuto
20from freqtrade.optimize.hyperopt_tools import HyperoptTools
21from freqtrade.optimize.space import SKDecimal
22from freqtrade.resolvers.hyperopt_resolver import HyperOptResolver
23from freqtrade.state import RunMode
24from tests.conftest import (get_args, log_has, log_has_re, patch_exchange,
25 patched_configuration_load_config_file)
26
27from .hyperopts.default_hyperopt import DefaultHyperOpt
28
29
30# Functions for recurrent object patching
31def create_results(mocker, hyperopt, testdatadir) -> List[Dict]:
32 """
33 When creating results, mock the hyperopt so that *by default*
34 - we don't create any pickle'd files in the filesystem
35 - we might have a pickle'd file so make sure that we return
36 false when looking for it
37 """
38 hyperopt.results_file = testdatadir / 'optimize/ut_results.pickle'
39
40 mocker.patch.object(Path, "is_file", MagicMock(return_value=False))
41 stat_mock = MagicMock()
42 stat_mock.st_size = 1
43 mocker.patch.object(Path, "stat", MagicMock(return_value=stat_mock))
44
45 mocker.patch.object(Path, "unlink", MagicMock(return_value=True))
46 mocker.patch('freqtrade.optimize.hyperopt.dump', return_value=None)
47 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
48
49 return [{'loss': 1, 'result': 'foo', 'params': {}, 'is_best': True}]
50
51
52def test_setup_hyperopt_configuration_without_arguments(mocker, default_conf, caplog) -> None:
53 patched_configuration_load_config_file(mocker, default_conf)
54
55 args = [
56 'hyperopt',
57 '--config', 'config.json',
58 '--hyperopt', 'DefaultHyperOpt',
59 ]
60
61 config = setup_optimize_configuration(get_args(args), RunMode.HYPEROPT)
62 assert 'max_open_trades' in config
63 assert 'stake_currency' in config
64 assert 'stake_amount' in config
65 assert 'exchange' in config
66 assert 'pair_whitelist' in config['exchange']
67 assert 'datadir' in config
68 assert log_has('Using data directory: {} ...'.format(config['datadir']), caplog)
69 assert 'timeframe' in config
70 assert not log_has_re('Parameter -i/--ticker-interval detected .*', caplog)
71
72 assert 'position_stacking' not in config
73 assert not log_has('Parameter --enable-position-stacking detected ...', caplog)
74
75 assert 'timerange' not in config
76 assert 'runmode' in config
77 assert config['runmode'] == RunMode.HYPEROPT
78
79
80def test_setup_hyperopt_configuration_with_arguments(mocker, default_conf, caplog) -> None:
81 patched_configuration_load_config_file(mocker, default_conf)
82 mocker.patch(
83 'freqtrade.configuration.configuration.create_datadir',
84 lambda c, x: x
85 )
86
87 args = [
88 'hyperopt',
89 '--config', 'config.json',
90 '--hyperopt', 'DefaultHyperOpt',
91 '--datadir', '/foo/bar',
92 '--timeframe', '1m',
93 '--timerange', ':100',
94 '--enable-position-stacking',
95 '--disable-max-market-positions',
96 '--epochs', '1000',
97 '--spaces', 'default',
98 '--print-all'
99 ]
100
101 config = setup_optimize_configuration(get_args(args), RunMode.HYPEROPT)
102 assert 'max_open_trades' in config
103 assert 'stake_currency' in config
104 assert 'stake_amount' in config
105 assert 'exchange' in config
106 assert 'pair_whitelist' in config['exchange']
107 assert 'datadir' in config
108 assert config['runmode'] == RunMode.HYPEROPT
109
110 assert log_has('Using data directory: {} ...'.format(config['datadir']), caplog)
111 assert 'timeframe' in config
112 assert log_has('Parameter -i/--timeframe detected ... Using timeframe: 1m ...',
113 caplog)
114
115 assert 'position_stacking' in config
116 assert log_has('Parameter --enable-position-stacking detected ...', caplog)
117
118 assert 'use_max_market_positions' in config
119 assert log_has('Parameter --disable-max-market-positions detected ...', caplog)
120 assert log_has('max_open_trades set to unlimited ...', caplog)
121
122 assert 'timerange' in config
123 assert log_has('Parameter --timerange detected: {} ...'.format(config['timerange']), caplog)
124
125 assert 'epochs' in config
126 assert log_has('Parameter --epochs detected ... Will run Hyperopt with for 1000 epochs ...',
127 caplog)
128
129 assert 'spaces' in config
130 assert log_has('Parameter -s/--spaces detected: {}'.format(config['spaces']), caplog)
131 assert 'print_all' in config
132 assert log_has('Parameter --print-all detected ...', caplog)
133
134
135def test_setup_hyperopt_configuration_stake_amount(mocker, default_conf) -> None:
136
137 patched_configuration_load_config_file(mocker, default_conf)
138
139 args = [
140 'hyperopt',
141 '--config', 'config.json',
142 '--hyperopt', 'DefaultHyperOpt',
143 '--stake-amount', '1',
144 '--starting-balance', '2'
145 ]
146 conf = setup_optimize_configuration(get_args(args), RunMode.HYPEROPT)
147 assert isinstance(conf, dict)
148
149 args = [
150 'hyperopt',
151 '--config', 'config.json',
152 '--strategy', 'DefaultStrategy',
153 '--stake-amount', '1',
154 '--starting-balance', '0.5'
155 ]
156 with pytest.raises(OperationalException, match=r"Starting balance .* smaller .*"):
157 setup_optimize_configuration(get_args(args), RunMode.HYPEROPT)
158
159
160def test_hyperoptresolver(mocker, default_conf, caplog) -> None:
161 patched_configuration_load_config_file(mocker, default_conf)
162
163 hyperopt = DefaultHyperOpt
164 delattr(hyperopt, 'populate_indicators')
165 delattr(hyperopt, 'populate_buy_trend')
166 delattr(hyperopt, 'populate_sell_trend')
167 mocker.patch(
168 'freqtrade.resolvers.hyperopt_resolver.HyperOptResolver.load_object',
169 MagicMock(return_value=hyperopt(default_conf))
170 )
171 default_conf.update({'hyperopt': 'DefaultHyperOpt'})
172 x = HyperOptResolver.load_hyperopt(default_conf)
173 assert not hasattr(x, 'populate_indicators')
174 assert not hasattr(x, 'populate_buy_trend')
175 assert not hasattr(x, 'populate_sell_trend')
176 assert log_has("Hyperopt class does not provide populate_indicators() method. "
177 "Using populate_indicators from the strategy.", caplog)
178 assert log_has("Hyperopt class does not provide populate_sell_trend() method. "
179 "Using populate_sell_trend from the strategy.", caplog)
180 assert log_has("Hyperopt class does not provide populate_buy_trend() method. "
181 "Using populate_buy_trend from the strategy.", caplog)
182 assert hasattr(x, "ticker_interval") # DEPRECATED
183 assert hasattr(x, "timeframe")
184
185
186def test_hyperoptresolver_wrongname(default_conf) -> None:
187 default_conf.update({'hyperopt': "NonExistingHyperoptClass"})
188
189 with pytest.raises(OperationalException, match=r'Impossible to load Hyperopt.*'):
190 HyperOptResolver.load_hyperopt(default_conf)
191
192
193def test_hyperoptresolver_noname(default_conf):
194 default_conf['hyperopt'] = ''
195 with pytest.raises(OperationalException,
196 match="No Hyperopt set. Please use `--hyperopt` to specify "
197 "the Hyperopt class to use."):
198 HyperOptResolver.load_hyperopt(default_conf)
199
200
201def test_start_not_installed(mocker, default_conf, import_fails) -> None:
202 start_mock = MagicMock()
203 patched_configuration_load_config_file(mocker, default_conf)
204
205 mocker.patch('freqtrade.optimize.hyperopt.Hyperopt.start', start_mock)
206 patch_exchange(mocker)
207
208 args = [
209 'hyperopt',
210 '--config', 'config.json',
211 '--hyperopt', 'DefaultHyperOpt',
212 '--hyperopt-path',
213 str(Path(__file__).parent / "hyperopts"),
214 '--epochs', '5',
215 '--hyperopt-loss', 'SharpeHyperOptLossDaily',
216 ]
217 pargs = get_args(args)
218
219 with pytest.raises(OperationalException, match=r"Please ensure that the hyperopt dependencies"):
220 start_hyperopt(pargs)
221
222
223def test_start(mocker, hyperopt_conf, caplog) -> None:
224 start_mock = MagicMock()
225 patched_configuration_load_config_file(mocker, hyperopt_conf)
226 mocker.patch('freqtrade.optimize.hyperopt.Hyperopt.start', start_mock)
227 patch_exchange(mocker)
228
229 args = [
230 'hyperopt',
231 '--config', 'config.json',
232 '--hyperopt', 'DefaultHyperOpt',
233 '--hyperopt-loss', 'SharpeHyperOptLossDaily',
234 '--epochs', '5'
235 ]
236 pargs = get_args(args)
237 start_hyperopt(pargs)
238
239 assert log_has('Starting freqtrade in Hyperopt mode', caplog)
240 assert start_mock.call_count == 1
241
242
243def test_start_no_data(mocker, hyperopt_conf) -> None:
244 patched_configuration_load_config_file(mocker, hyperopt_conf)
245 mocker.patch('freqtrade.data.history.load_pair_history', MagicMock(return_value=pd.DataFrame))
246 mocker.patch(
247 'freqtrade.optimize.hyperopt.get_timerange',
248 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
249 )
250
251 patch_exchange(mocker)
252
253 args = [
254 'hyperopt',
255 '--config', 'config.json',
256 '--hyperopt', 'DefaultHyperOpt',
257 '--hyperopt-loss', 'SharpeHyperOptLossDaily',
258 '--epochs', '5'
259 ]
260 pargs = get_args(args)
261 with pytest.raises(OperationalException, match='No data found. Terminating.'):
262 start_hyperopt(pargs)
263
264
265def test_start_filelock(mocker, hyperopt_conf, caplog) -> None:
266 hyperopt_mock = MagicMock(side_effect=Timeout(Hyperopt.get_lock_filename(hyperopt_conf)))
267 patched_configuration_load_config_file(mocker, hyperopt_conf)
268 mocker.patch('freqtrade.optimize.hyperopt.Hyperopt.__init__', hyperopt_mock)
269 patch_exchange(mocker)
270
271 args = [
272 'hyperopt',
273 '--config', 'config.json',
274 '--hyperopt', 'DefaultHyperOpt',
275 '--hyperopt-loss', 'SharpeHyperOptLossDaily',
276 '--epochs', '5'
277 ]
278 pargs = get_args(args)
279 start_hyperopt(pargs)
280 assert log_has("Another running instance of freqtrade Hyperopt detected.", caplog)
281
282
283def test_log_results_if_loss_improves(hyperopt, capsys) -> None:
284 hyperopt.current_best_loss = 2
285 hyperopt.total_epochs = 2
286
287 hyperopt.print_results(
288 {
289 'loss': 1,
290 'results_metrics':
291 {
292 'trade_count': 1,
293 'avg_profit': 0.1,
294 'total_profit': 0.001,
295 'profit': 1.0,
296 'duration': 20.0
297 },
298 'total_profit': 0,
299 'current_epoch': 2, # This starts from 1 (in a human-friendly manner)
300 'is_initial_point': False,
301 'is_best': True
302 }
303 )
304 out, err = capsys.readouterr()
305 assert all(x in out
306 for x in ["Best", "2/2", " 1", "0.10%", "0.00100000 BTC (1.00%)", "20.0 m"])
307
308
309def test_no_log_if_loss_does_not_improve(hyperopt, caplog) -> None:
310 hyperopt.current_best_loss = 2
311 hyperopt.print_results(
312 {
313 'is_best': False,
314 'loss': 3,
315 'current_epoch': 1,
316 }
317 )
318 assert caplog.record_tuples == []
319
320
321def test_save_results_saves_epochs(mocker, hyperopt, testdatadir, caplog) -> None:
322 epochs = create_results(mocker, hyperopt, testdatadir)
323 mock_dump = mocker.patch('freqtrade.optimize.hyperopt.dump', return_value=None)
324 mock_dump_json = mocker.patch('freqtrade.optimize.hyperopt.file_dump_json', return_value=None)
325 results_file = testdatadir / 'optimize' / 'ut_results.pickle'
326
327 caplog.set_level(logging.DEBUG)
328
329 hyperopt.epochs = epochs
330 hyperopt._save_results()
331 assert log_has(f"1 epoch saved to '{results_file}'.", caplog)
332 mock_dump.assert_called_once()
333 mock_dump_json.assert_called_once()
334
335 hyperopt.epochs = epochs + epochs
336 hyperopt._save_results()
337 assert log_has(f"2 epochs saved to '{results_file}'.", caplog)
338
339
340def test_read_results_returns_epochs(mocker, hyperopt, testdatadir, caplog) -> None:
341 epochs = create_results(mocker, hyperopt, testdatadir)
342 mock_load = mocker.patch('freqtrade.optimize.hyperopt_tools.load', return_value=epochs)
343 results_file = testdatadir / 'optimize' / 'ut_results.pickle'
344 hyperopt_epochs = HyperoptTools._read_results(results_file)
345 assert log_has(f"Reading epochs from '{results_file}'", caplog)
346 assert hyperopt_epochs == epochs
347 mock_load.assert_called_once()
348
349
350def test_load_previous_results(mocker, hyperopt, testdatadir, caplog) -> None:
351 epochs = create_results(mocker, hyperopt, testdatadir)
352 mock_load = mocker.patch('freqtrade.optimize.hyperopt_tools.load', return_value=epochs)
353 mocker.patch.object(Path, 'is_file', MagicMock(return_value=True))
354 statmock = MagicMock()
355 statmock.st_size = 5
356 # mocker.patch.object(Path, 'stat', MagicMock(return_value=statmock))
357
358 results_file = testdatadir / 'optimize' / 'ut_results.pickle'
359
360 hyperopt_epochs = HyperoptTools.load_previous_results(results_file)
361
362 assert hyperopt_epochs == epochs
363 mock_load.assert_called_once()
364
365 del epochs[0]['is_best']
366 mock_load = mocker.patch('freqtrade.optimize.hyperopt_tools.load', return_value=epochs)
367
368 with pytest.raises(OperationalException):
369 HyperoptTools.load_previous_results(results_file)
370
371
372def test_roi_table_generation(hyperopt) -> None:
373 params = {
374 'roi_t1': 5,
375 'roi_t2': 10,
376 'roi_t3': 15,
377 'roi_p1': 1,
378 'roi_p2': 2,
379 'roi_p3': 3,
380 }
381
382 assert hyperopt.custom_hyperopt.generate_roi_table(params) == {0: 6, 15: 3, 25: 1, 30: 0}
383
384
385def test_start_calls_optimizer(mocker, hyperopt_conf, capsys) -> None:
386 dumper = mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
387 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
388
389 mocker.patch('freqtrade.optimize.backtesting.Backtesting.load_bt_data',
390 MagicMock(return_value=(MagicMock(), None)))
391 mocker.patch(
392 'freqtrade.optimize.hyperopt.get_timerange',
393 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
394 )
395
396 parallel = mocker.patch(
397 'freqtrade.optimize.hyperopt.Hyperopt.run_optimizer_parallel',
398 MagicMock(return_value=[{
399 'loss': 1, 'results_explanation': 'foo result',
400 'params': {'buy': {}, 'sell': {}, 'roi': {}, 'stoploss': 0.0},
401 'results_metrics':
402 {
403 'trade_count': 1,
404 'avg_profit': 0.1,
405 'total_profit': 0.001,
406 'profit': 1.0,
407 'duration': 20.0
408 },
409 }])
410 )
411 patch_exchange(mocker)
412 # Co-test loading timeframe from strategy
413 del hyperopt_conf['timeframe']
414
415 hyperopt = Hyperopt(hyperopt_conf)
416 hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock()
417 hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={})
418
419 hyperopt.start()
420
421 parallel.assert_called_once()
422
423 out, err = capsys.readouterr()
424 assert 'Best result:\n\n* 1/1: foo result Objective: 1.00000\n' in out
425 assert dumper.called
426 # Should be called twice, once for historical candle data, once to save evaluations
427 assert dumper.call_count == 2
428 assert hasattr(hyperopt.backtesting.strategy, "advise_sell")
429 assert hasattr(hyperopt.backtesting.strategy, "advise_buy")
430 assert hasattr(hyperopt, "max_open_trades")
431 assert hyperopt.max_open_trades == hyperopt_conf['max_open_trades']
432 assert hasattr(hyperopt, "position_stacking")
433
434
435def test_format_results(hyperopt):
436 # Test with BTC as stake_currency
437 trades = [
438 ('ETH/BTC', 2, 2, 123),
439 ('LTC/BTC', 1, 1, 123),
440 ('XPR/BTC', -1, -2, -246)
441 ]
442 labels = ['currency', 'profit_ratio', 'profit_abs', 'trade_duration']
443 df = pd.DataFrame.from_records(trades, columns=labels)
444 results_metrics = hyperopt._calculate_results_metrics(df)
445 results_explanation = hyperopt._format_results_explanation_string(results_metrics)
446 total_profit = results_metrics['total_profit']
447
448 results = {
449 'loss': 0.0,
450 'params_dict': None,
451 'params_details': None,
452 'results_metrics': results_metrics,
453 'results_explanation': results_explanation,
454 'total_profit': total_profit,
455 'current_epoch': 1,
456 'is_initial_point': True,
457 }
458
459 result = HyperoptTools._format_explanation_string(results, 1)
460 assert result.find(' 66.67%')
461 assert result.find('Total profit 1.00000000 BTC')
462 assert result.find('2.0000Σ %')
463
464 # Test with EUR as stake_currency
465 trades = [
466 ('ETH/EUR', 2, 2, 123),
467 ('LTC/EUR', 1, 1, 123),
468 ('XPR/EUR', -1, -2, -246)
469 ]
470 df = pd.DataFrame.from_records(trades, columns=labels)
471 results_metrics = hyperopt._calculate_results_metrics(df)
472 results['total_profit'] = results_metrics['total_profit']
473 result = HyperoptTools._format_explanation_string(results, 1)
474 assert result.find('Total profit 1.00000000 EUR')
475
476
477@pytest.mark.parametrize("spaces, expected_results", [
478 (['buy'],
479 {'buy': True, 'sell': False, 'roi': False, 'stoploss': False, 'trailing': False}),
480 (['sell'],
481 {'buy': False, 'sell': True, 'roi': False, 'stoploss': False, 'trailing': False}),
482 (['roi'],
483 {'buy': False, 'sell': False, 'roi': True, 'stoploss': False, 'trailing': False}),
484 (['stoploss'],
485 {'buy': False, 'sell': False, 'roi': False, 'stoploss': True, 'trailing': False}),
486 (['trailing'],
487 {'buy': False, 'sell': False, 'roi': False, 'stoploss': False, 'trailing': True}),
488 (['buy', 'sell', 'roi', 'stoploss'],
489 {'buy': True, 'sell': True, 'roi': True, 'stoploss': True, 'trailing': False}),
490 (['buy', 'sell', 'roi', 'stoploss', 'trailing'],
491 {'buy': True, 'sell': True, 'roi': True, 'stoploss': True, 'trailing': True}),
492 (['buy', 'roi'],
493 {'buy': True, 'sell': False, 'roi': True, 'stoploss': False, 'trailing': False}),
494 (['all'],
495 {'buy': True, 'sell': True, 'roi': True, 'stoploss': True, 'trailing': True}),
496 (['default'],
497 {'buy': True, 'sell': True, 'roi': True, 'stoploss': True, 'trailing': False}),
498 (['default', 'trailing'],
499 {'buy': True, 'sell': True, 'roi': True, 'stoploss': True, 'trailing': True}),
500 (['all', 'buy'],
501 {'buy': True, 'sell': True, 'roi': True, 'stoploss': True, 'trailing': True}),
502 (['default', 'buy'],
503 {'buy': True, 'sell': True, 'roi': True, 'stoploss': True, 'trailing': False}),
504])
505def test_has_space(hyperopt, spaces, expected_results):
506 for s in ['buy', 'sell', 'roi', 'stoploss', 'trailing']:
507 hyperopt.config.update({'spaces': spaces})
508 assert hyperopt.has_space(s) == expected_results[s]
509
510
511def test_populate_indicators(hyperopt, testdatadir) -> None:
512 data = load_data(testdatadir, '1m', ['UNITTEST/BTC'], fill_up_missing=True)
513 dataframes = hyperopt.backtesting.strategy.ohlcvdata_to_dataframe(data)
514 dataframe = hyperopt.custom_hyperopt.populate_indicators(dataframes['UNITTEST/BTC'],
515 {'pair': 'UNITTEST/BTC'})
516
517 # Check if some indicators are generated. We will not test all of them
518 assert 'adx' in dataframe
519 assert 'mfi' in dataframe
520 assert 'rsi' in dataframe
521
522
523def test_buy_strategy_generator(hyperopt, testdatadir) -> None:
524 data = load_data(testdatadir, '1m', ['UNITTEST/BTC'], fill_up_missing=True)
525 dataframes = hyperopt.backtesting.strategy.ohlcvdata_to_dataframe(data)
526 dataframe = hyperopt.custom_hyperopt.populate_indicators(dataframes['UNITTEST/BTC'],
527 {'pair': 'UNITTEST/BTC'})
528
529 populate_buy_trend = hyperopt.custom_hyperopt.buy_strategy_generator(
530 {
531 'adx-value': 20,
532 'fastd-value': 20,
533 'mfi-value': 20,
534 'rsi-value': 20,
535 'adx-enabled': True,
536 'fastd-enabled': True,
537 'mfi-enabled': True,
538 'rsi-enabled': True,
539 'trigger': 'bb_lower'
540 }
541 )
542 result = populate_buy_trend(dataframe, {'pair': 'UNITTEST/BTC'})
543 # Check if some indicators are generated. We will not test all of them
544 assert 'buy' in result
545 assert 1 in result['buy']
546
547
548def test_sell_strategy_generator(hyperopt, testdatadir) -> None:
549 data = load_data(testdatadir, '1m', ['UNITTEST/BTC'], fill_up_missing=True)
550 dataframes = hyperopt.backtesting.strategy.ohlcvdata_to_dataframe(data)
551 dataframe = hyperopt.custom_hyperopt.populate_indicators(dataframes['UNITTEST/BTC'],
552 {'pair': 'UNITTEST/BTC'})
553
554 populate_sell_trend = hyperopt.custom_hyperopt.sell_strategy_generator(
555 {
556 'sell-adx-value': 20,
557 'sell-fastd-value': 75,
558 'sell-mfi-value': 80,
559 'sell-rsi-value': 20,
560 'sell-adx-enabled': True,
561 'sell-fastd-enabled': True,
562 'sell-mfi-enabled': True,
563 'sell-rsi-enabled': True,
564 'sell-trigger': 'sell-bb_upper'
565 }
566 )
567 result = populate_sell_trend(dataframe, {'pair': 'UNITTEST/BTC'})
568 # Check if some indicators are generated. We will not test all of them
569 print(result)
570 assert 'sell' in result
571 assert 1 in result['sell']
572
573
574def test_generate_optimizer(mocker, hyperopt_conf) -> None:
575 hyperopt_conf.update({'spaces': 'all',
576 'hyperopt_min_trades': 1,
577 })
578
579 trades = [
580 ('TRX/BTC', 0.023117, 0.000233, 100)
581 ]
582 labels = ['currency', 'profit_ratio', 'profit_abs', 'trade_duration']
583 backtest_result = pd.DataFrame.from_records(trades, columns=labels)
584
585 mocker.patch(
586 'freqtrade.optimize.hyperopt.Backtesting.backtest',
587 MagicMock(return_value=backtest_result)
588 )
589 mocker.patch(
590 'freqtrade.optimize.hyperopt.get_timerange',
591 MagicMock(return_value=(Arrow(2017, 12, 10), Arrow(2017, 12, 13)))
592 )
593 patch_exchange(mocker)
594 mocker.patch('freqtrade.optimize.hyperopt.load', MagicMock())
595
596 optimizer_param = {
597 'adx-value': 0,
598 'fastd-value': 35,
599 'mfi-value': 0,
600 'rsi-value': 0,
601 'adx-enabled': False,
602 'fastd-enabled': True,
603 'mfi-enabled': False,
604 'rsi-enabled': False,
605 'trigger': 'macd_cross_signal',
606 'sell-adx-value': 0,
607 'sell-fastd-value': 75,
608 'sell-mfi-value': 0,
609 'sell-rsi-value': 0,
610 'sell-adx-enabled': False,
611 'sell-fastd-enabled': True,
612 'sell-mfi-enabled': False,
613 'sell-rsi-enabled': False,
614 'sell-trigger': 'macd_cross_signal',
615 'roi_t1': 60.0,
616 'roi_t2': 30.0,
617 'roi_t3': 20.0,
618 'roi_p1': 0.01,
619 'roi_p2': 0.01,
620 'roi_p3': 0.1,
621 'stoploss': -0.4,
622 'trailing_stop': True,
623 'trailing_stop_positive': 0.02,
624 'trailing_stop_positive_offset_p1': 0.05,
625 'trailing_only_offset_is_reached': False,
626 }
627 response_expected = {
628 'loss': 1.9840569076926293,
629 'results_explanation': (' 1 trades. 1/0/0 Wins/Draws/Losses. '
630 'Avg profit 2.31%. Median profit 2.31%. Total profit '
631 '0.00023300 BTC ( 2.31\N{GREEK CAPITAL LETTER SIGMA}%). '
632 'Avg duration 100.0 min.'
633 ).encode(locale.getpreferredencoding(), 'replace').decode('utf-8'),
634 'params_details': {'buy': {'adx-enabled': False,
635 'adx-value': 0,
636 'fastd-enabled': True,
637 'fastd-value': 35,
638 'mfi-enabled': False,
639 'mfi-value': 0,
640 'rsi-enabled': False,
641 'rsi-value': 0,
642 'trigger': 'macd_cross_signal'},
643 'roi': {0: 0.12000000000000001,
644 20.0: 0.02,
645 50.0: 0.01,
646 110.0: 0},
647 'sell': {'sell-adx-enabled': False,
648 'sell-adx-value': 0,
649 'sell-fastd-enabled': True,
650 'sell-fastd-value': 75,
651 'sell-mfi-enabled': False,
652 'sell-mfi-value': 0,
653 'sell-rsi-enabled': False,
654 'sell-rsi-value': 0,
655 'sell-trigger': 'macd_cross_signal'},
656 'stoploss': {'stoploss': -0.4},
657 'trailing': {'trailing_only_offset_is_reached': False,
658 'trailing_stop': True,
659 'trailing_stop_positive': 0.02,
660 'trailing_stop_positive_offset': 0.07}},
661 'params_dict': optimizer_param,
662 'results_metrics': {'avg_profit': 2.3117,
663 'draws': 0,
664 'duration': 100.0,
665 'losses': 0,
666 'winsdrawslosses': ' 1 0 0',
667 'median_profit': 2.3117,
668 'profit': 2.3117,
669 'total_profit': 0.000233,
670 'trade_count': 1,
671 'wins': 1},
672 'total_profit': 0.00023300
673 }
674
675 hyperopt = Hyperopt(hyperopt_conf)
676 hyperopt.dimensions = hyperopt.hyperopt_space()
677 generate_optimizer_value = hyperopt.generate_optimizer(list(optimizer_param.values()))
678 assert generate_optimizer_value == response_expected
679
680
681def test_clean_hyperopt(mocker, hyperopt_conf, caplog):
682 patch_exchange(mocker)
683
684 mocker.patch("freqtrade.optimize.hyperopt.Path.is_file", MagicMock(return_value=True))
685 unlinkmock = mocker.patch("freqtrade.optimize.hyperopt.Path.unlink", MagicMock())
686 h = Hyperopt(hyperopt_conf)
687
688 assert unlinkmock.call_count == 2
689 assert log_has(f"Removing `{h.data_pickle_file}`.", caplog)
690
691
692def test_print_json_spaces_all(mocker, hyperopt_conf, capsys) -> None:
693 dumper = mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
694 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
695
696 mocker.patch('freqtrade.optimize.backtesting.Backtesting.load_bt_data',
697 MagicMock(return_value=(MagicMock(), None)))
698 mocker.patch(
699 'freqtrade.optimize.hyperopt.get_timerange',
700 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
701 )
702
703 parallel = mocker.patch(
704 'freqtrade.optimize.hyperopt.Hyperopt.run_optimizer_parallel',
705 MagicMock(return_value=[{
706 'loss': 1, 'results_explanation': 'foo result', 'params': {},
707 'params_details': {
708 'buy': {'mfi-value': None},
709 'sell': {'sell-mfi-value': None},
710 'roi': {}, 'stoploss': {'stoploss': None},
711 'trailing': {'trailing_stop': None}
712 },
713 'results_metrics':
714 {
715 'trade_count': 1,
716 'avg_profit': 0.1,
717 'total_profit': 0.001,
718 'profit': 1.0,
719 'duration': 20.0
720 }
721 }])
722 )
723 patch_exchange(mocker)
724
725 hyperopt_conf.update({'spaces': 'all',
726 'hyperopt_jobs': 1,
727 'print_json': True,
728 })
729
730 hyperopt = Hyperopt(hyperopt_conf)
731 hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock()
732 hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={})
733
734 hyperopt.start()
735
736 parallel.assert_called_once()
737
738 out, err = capsys.readouterr()
739 result_str = (
740 '{"params":{"mfi-value":null,"sell-mfi-value":null},"minimal_roi"'
741 ':{},"stoploss":null,"trailing_stop":null}'
742 )
743 assert result_str in out # noqa: E501
744 assert dumper.called
745 # Should be called twice, once for historical candle data, once to save evaluations
746 assert dumper.call_count == 2
747
748
749def test_print_json_spaces_default(mocker, hyperopt_conf, capsys) -> None:
750 dumper = mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
751 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
752 mocker.patch('freqtrade.optimize.backtesting.Backtesting.load_bt_data',
753 MagicMock(return_value=(MagicMock(), None)))
754 mocker.patch(
755 'freqtrade.optimize.hyperopt.get_timerange',
756 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
757 )
758
759 parallel = mocker.patch(
760 'freqtrade.optimize.hyperopt.Hyperopt.run_optimizer_parallel',
761 MagicMock(return_value=[{
762 'loss': 1, 'results_explanation': 'foo result', 'params': {},
763 'params_details': {
764 'buy': {'mfi-value': None},
765 'sell': {'sell-mfi-value': None},
766 'roi': {}, 'stoploss': {'stoploss': None}
767 },
768 'results_metrics':
769 {
770 'trade_count': 1,
771 'avg_profit': 0.1,
772 'total_profit': 0.001,
773 'profit': 1.0,
774 'duration': 20.0
775 }
776 }])
777 )
778 patch_exchange(mocker)
779
780 hyperopt_conf.update({'print_json': True})
781
782 hyperopt = Hyperopt(hyperopt_conf)
783 hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock()
784 hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={})
785
786 hyperopt.start()
787
788 parallel.assert_called_once()
789
790 out, err = capsys.readouterr()
791 assert '{"params":{"mfi-value":null,"sell-mfi-value":null},"minimal_roi":{},"stoploss":null}' in out # noqa: E501
792 assert dumper.called
793 # Should be called twice, once for historical candle data, once to save evaluations
794 assert dumper.call_count == 2
795
796
797def test_print_json_spaces_roi_stoploss(mocker, hyperopt_conf, capsys) -> None:
798 dumper = mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
799 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
800 mocker.patch('freqtrade.optimize.backtesting.Backtesting.load_bt_data',
801 MagicMock(return_value=(MagicMock(), None)))
802 mocker.patch(
803 'freqtrade.optimize.hyperopt.get_timerange',
804 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
805 )
806
807 parallel = mocker.patch(
808 'freqtrade.optimize.hyperopt.Hyperopt.run_optimizer_parallel',
809 MagicMock(return_value=[{
810 'loss': 1, 'results_explanation': 'foo result', 'params': {},
811 'params_details': {'roi': {}, 'stoploss': {'stoploss': None}},
812 'results_metrics':
813 {
814 'trade_count': 1,
815 'avg_profit': 0.1,
816 'total_profit': 0.001,
817 'profit': 1.0,
818 'duration': 20.0
819 }
820 }])
821 )
822 patch_exchange(mocker)
823
824 hyperopt_conf.update({'spaces': 'roi stoploss',
825 'hyperopt_jobs': 1,
826 'print_json': True,
827 })
828
829 hyperopt = Hyperopt(hyperopt_conf)
830 hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock()
831 hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={})
832
833 hyperopt.start()
834
835 parallel.assert_called_once()
836
837 out, err = capsys.readouterr()
838 assert '{"minimal_roi":{},"stoploss":null}' in out
839 assert dumper.called
840 # Should be called twice, once for historical candle data, once to save evaluations
841 assert dumper.call_count == 2
842
843
844def test_simplified_interface_roi_stoploss(mocker, hyperopt_conf, capsys) -> None:
845 dumper = mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
846 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
847 mocker.patch('freqtrade.optimize.backtesting.Backtesting.load_bt_data',
848 MagicMock(return_value=(MagicMock(), None)))
849 mocker.patch(
850 'freqtrade.optimize.hyperopt.get_timerange',
851 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
852 )
853
854 parallel = mocker.patch(
855 'freqtrade.optimize.hyperopt.Hyperopt.run_optimizer_parallel',
856 MagicMock(return_value=[{
857 'loss': 1, 'results_explanation': 'foo result', 'params': {'stoploss': 0.0},
858 'results_metrics':
859 {
860 'trade_count': 1,
861 'avg_profit': 0.1,
862 'total_profit': 0.001,
863 'profit': 1.0,
864 'duration': 20.0
865 }
866 }])
867 )
868 patch_exchange(mocker)
869
870 hyperopt_conf.update({'spaces': 'roi stoploss'})
871
872 hyperopt = Hyperopt(hyperopt_conf)
873 hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock()
874 hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={})
875
876 del hyperopt.custom_hyperopt.__class__.buy_strategy_generator
877 del hyperopt.custom_hyperopt.__class__.sell_strategy_generator
878 del hyperopt.custom_hyperopt.__class__.indicator_space
879 del hyperopt.custom_hyperopt.__class__.sell_indicator_space
880
881 hyperopt.start()
882
883 parallel.assert_called_once()
884
885 out, err = capsys.readouterr()
886 assert 'Best result:\n\n* 1/1: foo result Objective: 1.00000\n' in out
887 assert dumper.called
888 # Should be called twice, once for historical candle data, once to save evaluations
889 assert dumper.call_count == 2
890 assert hasattr(hyperopt.backtesting.strategy, "advise_sell")
891 assert hasattr(hyperopt.backtesting.strategy, "advise_buy")
892 assert hasattr(hyperopt, "max_open_trades")
893 assert hyperopt.max_open_trades == hyperopt_conf['max_open_trades']
894 assert hasattr(hyperopt, "position_stacking")
895
896
897def test_simplified_interface_all_failed(mocker, hyperopt_conf) -> None:
898 mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
899 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
900 mocker.patch('freqtrade.optimize.backtesting.Backtesting.load_bt_data',
901 MagicMock(return_value=(MagicMock(), None)))
902 mocker.patch(
903 'freqtrade.optimize.hyperopt.get_timerange',
904 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
905 )
906
907 patch_exchange(mocker)
908
909 hyperopt_conf.update({'spaces': 'all', })
910
911 hyperopt = Hyperopt(hyperopt_conf)
912 hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock()
913 hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={})
914
915 del hyperopt.custom_hyperopt.__class__.buy_strategy_generator
916 del hyperopt.custom_hyperopt.__class__.sell_strategy_generator
917 del hyperopt.custom_hyperopt.__class__.indicator_space
918 del hyperopt.custom_hyperopt.__class__.sell_indicator_space
919
920 with pytest.raises(OperationalException, match=r"The 'buy' space is included into *"):
921 hyperopt.start()
922
923
924def test_simplified_interface_buy(mocker, hyperopt_conf, capsys) -> None:
925 dumper = mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
926 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
927 mocker.patch('freqtrade.optimize.backtesting.Backtesting.load_bt_data',
928 MagicMock(return_value=(MagicMock(), None)))
929 mocker.patch(
930 'freqtrade.optimize.hyperopt.get_timerange',
931 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
932 )
933
934 parallel = mocker.patch(
935 'freqtrade.optimize.hyperopt.Hyperopt.run_optimizer_parallel',
936 MagicMock(return_value=[{
937 'loss': 1, 'results_explanation': 'foo result', 'params': {},
938 'results_metrics':
939 {
940 'trade_count': 1,
941 'avg_profit': 0.1,
942 'total_profit': 0.001,
943 'profit': 1.0,
944 'duration': 20.0
945 }
946 }])
947 )
948 patch_exchange(mocker)
949
950 hyperopt_conf.update({'spaces': 'buy'})
951
952 hyperopt = Hyperopt(hyperopt_conf)
953 hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock()
954 hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={})
955
956 # TODO: sell_strategy_generator() is actually not called because
957 # run_optimizer_parallel() is mocked
958 del hyperopt.custom_hyperopt.__class__.sell_strategy_generator
959 del hyperopt.custom_hyperopt.__class__.sell_indicator_space
960
961 hyperopt.start()
962
963 parallel.assert_called_once()
964
965 out, err = capsys.readouterr()
966 assert 'Best result:\n\n* 1/1: foo result Objective: 1.00000\n' in out
967 assert dumper.called
968 # Should be called twice, once for historical candle data, once to save evaluations
969 assert dumper.call_count == 2
970 assert hasattr(hyperopt.backtesting.strategy, "advise_sell")
971 assert hasattr(hyperopt.backtesting.strategy, "advise_buy")
972 assert hasattr(hyperopt, "max_open_trades")
973 assert hyperopt.max_open_trades == hyperopt_conf['max_open_trades']
974 assert hasattr(hyperopt, "position_stacking")
975
976
977def test_simplified_interface_sell(mocker, hyperopt_conf, capsys) -> None:
978 dumper = mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
979 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
980 mocker.patch('freqtrade.optimize.backtesting.Backtesting.load_bt_data',
981 MagicMock(return_value=(MagicMock(), None)))
982 mocker.patch(
983 'freqtrade.optimize.hyperopt.get_timerange',
984 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
985 )
986
987 parallel = mocker.patch(
988 'freqtrade.optimize.hyperopt.Hyperopt.run_optimizer_parallel',
989 MagicMock(return_value=[{
990 'loss': 1, 'results_explanation': 'foo result', 'params': {},
991 'results_metrics':
992 {
993 'trade_count': 1,
994 'avg_profit': 0.1,
995 'total_profit': 0.001,
996 'profit': 1.0,
997 'duration': 20.0
998 }
999 }])
1000 )
1001 patch_exchange(mocker)
1002
1003 hyperopt_conf.update({'spaces': 'sell', })
1004
1005 hyperopt = Hyperopt(hyperopt_conf)
1006 hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock()
1007 hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={})
1008
1009 # TODO: buy_strategy_generator() is actually not called because
1010 # run_optimizer_parallel() is mocked
1011 del hyperopt.custom_hyperopt.__class__.buy_strategy_generator
1012 del hyperopt.custom_hyperopt.__class__.indicator_space
1013
1014 hyperopt.start()
1015
1016 parallel.assert_called_once()
1017
1018 out, err = capsys.readouterr()
1019 assert 'Best result:\n\n* 1/1: foo result Objective: 1.00000\n' in out
1020 assert dumper.called
1021 # Should be called twice, once for historical candle data, once to save evaluations
1022 assert dumper.call_count == 2
1023 assert hasattr(hyperopt.backtesting.strategy, "advise_sell")
1024 assert hasattr(hyperopt.backtesting.strategy, "advise_buy")
1025 assert hasattr(hyperopt, "max_open_trades")
1026 assert hyperopt.max_open_trades == hyperopt_conf['max_open_trades']
1027 assert hasattr(hyperopt, "position_stacking")
1028
1029
1030@pytest.mark.parametrize("method,space", [
1031 ('buy_strategy_generator', 'buy'),
1032 ('indicator_space', 'buy'),
1033 ('sell_strategy_generator', 'sell'),
1034 ('sell_indicator_space', 'sell'),
1035])
1036def test_simplified_interface_failed(mocker, hyperopt_conf, method, space) -> None:
1037 mocker.patch('freqtrade.optimize.hyperopt.dump', MagicMock())
1038 mocker.patch('freqtrade.optimize.hyperopt.file_dump_json')
1039 mocker.patch('freqtrade.optimize.backtesting.Backtesting.load_bt_data',
1040 MagicMock(return_value=(MagicMock(), None)))
1041 mocker.patch(
1042 'freqtrade.optimize.hyperopt.get_timerange',
1043 MagicMock(return_value=(datetime(2017, 12, 10), datetime(2017, 12, 13)))
1044 )
1045
1046 patch_exchange(mocker)
1047
1048 hyperopt_conf.update({'spaces': space})
1049
1050 hyperopt = Hyperopt(hyperopt_conf)
1051 hyperopt.backtesting.strategy.ohlcvdata_to_dataframe = MagicMock()
1052 hyperopt.custom_hyperopt.generate_roi_table = MagicMock(return_value={})
1053
1054 delattr(hyperopt.custom_hyperopt.__class__, method)
1055
1056 with pytest.raises(OperationalException, match=f"The '{space}' space is included into *"):
1057 hyperopt.start()
1058
1059
1060def test_print_epoch_details(capsys):
1061 test_result = {
1062 'params_details': {
1063 'trailing': {
1064 'trailing_stop': True,
1065 'trailing_stop_positive': 0.02,
1066 'trailing_stop_positive_offset': 0.04,
1067 'trailing_only_offset_is_reached': True
1068 },
1069 'roi': {
1070 0: 0.18,
1071 90: 0.14,
1072 225: 0.05,
1073 430: 0},
1074 },
1075 'results_explanation': 'foo result',
1076 'is_initial_point': False,
1077 'total_profit': 0,
1078 'current_epoch': 2, # This starts from 1 (in a human-friendly manner)
1079 'is_best': True
1080 }
1081
1082 HyperoptTools.print_epoch_details(test_result, 5, False, no_header=True)
1083 captured = capsys.readouterr()
1084 assert '# Trailing stop:' in captured.out
1085 # re.match(r"Pairs for .*", captured.out)
1086 assert re.search(r'^\s+trailing_stop = True$', captured.out, re.MULTILINE)
1087 assert re.search(r'^\s+trailing_stop_positive = 0.02$', captured.out, re.MULTILINE)
1088 assert re.search(r'^\s+trailing_stop_positive_offset = 0.04$', captured.out, re.MULTILINE)
1089 assert re.search(r'^\s+trailing_only_offset_is_reached = True$', captured.out, re.MULTILINE)
1090
1091 assert '# ROI table:' in captured.out
1092 assert re.search(r'^\s+minimal_roi = \{$', captured.out, re.MULTILINE)
1093 assert re.search(r'^\s+\"90\"\:\s0.14,\s*$', captured.out, re.MULTILINE)
1094
1095
1096def test_in_strategy_auto_hyperopt(mocker, hyperopt_conf, tmpdir) -> None:
1097 (Path(tmpdir) / 'hyperopt_results').mkdir(parents=True)
1098 # No hyperopt needed
1099 del hyperopt_conf['hyperopt']
1100 hyperopt_conf.update({
1101 'strategy': 'HyperoptableStrategy',
1102 'user_data_dir': Path(tmpdir),
1103 })
1104 hyperopt = Hyperopt(hyperopt_conf)
1105 assert isinstance(hyperopt.custom_hyperopt, HyperOptAuto)
1106
1107 hyperopt.start()
1108
1109
1110def 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]