Elffuss BraidHub

kikocis/freqtrade public

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