Elffuss BraidHub

kikocis/freqtrade public

develop · 33.4 KiBRawPermalink
1# pragma pylint: disable=missing-docstring, protected-access, C0103
2
3import json
4import uuid
5from pathlib import Path
6from shutil import copyfile
7from unittest.mock import MagicMock, PropertyMock
8
9import arrow
10import pytest
11from pandas import DataFrame
12from pandas.testing import assert_frame_equal
13
14from freqtrade.configuration import TimeRange
15from freqtrade.constants import AVAILABLE_DATAHANDLERS
16from freqtrade.data.converter import ohlcv_to_dataframe
17from freqtrade.data.history.hdf5datahandler import HDF5DataHandler
18from freqtrade.data.history.history_utils import (_download_pair_history, _download_trades_history,
19 _load_cached_data_for_updating,
20 convert_trades_to_ohlcv, get_timerange, load_data,
21 load_pair_history, refresh_backtest_ohlcv_data,
22 refresh_backtest_trades_data, refresh_data,
23 validate_backtest_data)
24from freqtrade.data.history.idatahandler import IDataHandler, get_datahandler, get_datahandlerclass
25from freqtrade.data.history.jsondatahandler import JsonDataHandler, JsonGzDataHandler
26from freqtrade.exchange import timeframe_to_minutes
27from freqtrade.misc import file_dump_json
28from freqtrade.resolvers import StrategyResolver
29from tests.conftest import get_patched_exchange, log_has, log_has_re, patch_exchange
30
31
32# Change this if modifying UNITTEST/BTC testdatafile
33_BTC_UNITTEST_LENGTH = 13681
34
35
36def _backup_file(file: Path, copy_file: bool = False) -> None:
37 """
38 Backup existing file to avoid deleting the user file
39 :param file: complete path to the file
40 :param copy_file: keep file in place too.
41 :return: None
42 """
43 file_swp = str(file) + '.swp'
44 if file.is_file():
45 file.rename(file_swp)
46
47 if copy_file:
48 copyfile(file_swp, file)
49
50
51def _clean_test_file(file: Path) -> None:
52 """
53 Backup existing file to avoid deleting the user file
54 :param file: complete path to the file
55 :return: None
56 """
57 file_swp = Path(str(file) + '.swp')
58 # 1. Delete file from the test
59 if file.is_file():
60 file.unlink()
61
62 # 2. Rollback to the initial file
63 if file_swp.is_file():
64 file_swp.rename(file)
65
66
67def test_load_data_30min_timeframe(mocker, caplog, default_conf, testdatadir) -> None:
68 ld = load_pair_history(pair='UNITTEST/BTC', timeframe='30m', datadir=testdatadir)
69 assert isinstance(ld, DataFrame)
70 assert not log_has(
71 'Download history data for pair: "UNITTEST/BTC", timeframe: 30m '
72 'and store in None.', caplog
73 )
74
75
76def test_load_data_7min_timeframe(mocker, caplog, default_conf, testdatadir) -> None:
77 ld = load_pair_history(pair='UNITTEST/BTC', timeframe='7m', datadir=testdatadir)
78 assert isinstance(ld, DataFrame)
79 assert ld.empty
80 assert log_has(
81 'No history data for pair: "UNITTEST/BTC", timeframe: 7m. '
82 'Use `freqtrade download-data` to download the data', caplog
83 )
84
85
86def test_load_data_1min_timeframe(ohlcv_history, mocker, caplog, testdatadir) -> None:
87 mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ohlcv_history)
88 file = testdatadir / 'UNITTEST_BTC-1m.json'
89 _backup_file(file, copy_file=True)
90 load_data(datadir=testdatadir, timeframe='1m', pairs=['UNITTEST/BTC'])
91 assert file.is_file()
92 assert not log_has(
93 'Download history data for pair: "UNITTEST/BTC", interval: 1m '
94 'and store in None.', caplog
95 )
96 _clean_test_file(file)
97
98
99def test_load_data_startup_candles(mocker, caplog, default_conf, testdatadir) -> None:
100 ltfmock = mocker.patch(
101 'freqtrade.data.history.jsondatahandler.JsonDataHandler._ohlcv_load',
102 MagicMock(return_value=DataFrame()))
103 timerange = TimeRange('date', None, 1510639620, 0)
104 load_pair_history(pair='UNITTEST/BTC', timeframe='1m',
105 datadir=testdatadir, timerange=timerange,
106 startup_candles=20,)
107
108 assert ltfmock.call_count == 1
109 assert ltfmock.call_args_list[0][1]['timerange'] != timerange
110 # startts is 20 minutes earlier
111 assert ltfmock.call_args_list[0][1]['timerange'].startts == timerange.startts - 20 * 60
112
113
114def test_load_data_with_new_pair_1min(ohlcv_history_list, mocker, caplog,
115 default_conf, testdatadir) -> None:
116 """
117 Test load_pair_history() with 1 min timeframe
118 """
119 mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ohlcv_history_list)
120 exchange = get_patched_exchange(mocker, default_conf)
121 file = testdatadir / 'MEME_BTC-1m.json'
122
123 _backup_file(file)
124 # do not download a new pair if refresh_pairs isn't set
125 load_pair_history(datadir=testdatadir, timeframe='1m', pair='MEME/BTC')
126 assert not file.is_file()
127 assert log_has(
128 'No history data for pair: "MEME/BTC", timeframe: 1m. '
129 'Use `freqtrade download-data` to download the data', caplog
130 )
131
132 # download a new pair if refresh_pairs is set
133 refresh_data(datadir=testdatadir, timeframe='1m', pairs=['MEME/BTC'],
134 exchange=exchange)
135 load_pair_history(datadir=testdatadir, timeframe='1m', pair='MEME/BTC')
136 assert file.is_file()
137 assert log_has_re(
138 'Download history data for pair: "MEME/BTC", timeframe: 1m '
139 'and store in .*', caplog
140 )
141 _clean_test_file(file)
142
143
144def test_testdata_path(testdatadir) -> None:
145 assert str(Path('tests') / 'testdata') in str(testdatadir)
146
147
148@pytest.mark.parametrize("pair,expected_result", [
149 ("ETH/BTC", 'freqtrade/hello/world/ETH_BTC-5m.json'),
150 ("Fabric Token/ETH", 'freqtrade/hello/world/Fabric_Token_ETH-5m.json'),
151 ("ETHH20", 'freqtrade/hello/world/ETHH20-5m.json'),
152 (".XBTBON2H", 'freqtrade/hello/world/_XBTBON2H-5m.json'),
153 ("ETHUSD.d", 'freqtrade/hello/world/ETHUSD_d-5m.json'),
154 ("ACC_OLD/BTC", 'freqtrade/hello/world/ACC_OLD_BTC-5m.json'),
155])
156def test_json_pair_data_filename(pair, expected_result):
157 fn = JsonDataHandler._pair_data_filename(Path('freqtrade/hello/world'), pair, '5m')
158 assert isinstance(fn, Path)
159 assert fn == Path(expected_result)
160 fn = JsonGzDataHandler._pair_data_filename(Path('freqtrade/hello/world'), pair, '5m')
161 assert isinstance(fn, Path)
162 assert fn == Path(expected_result + '.gz')
163
164
165@pytest.mark.parametrize("pair,expected_result", [
166 ("ETH/BTC", 'freqtrade/hello/world/ETH_BTC-trades.json'),
167 ("Fabric Token/ETH", 'freqtrade/hello/world/Fabric_Token_ETH-trades.json'),
168 ("ETHH20", 'freqtrade/hello/world/ETHH20-trades.json'),
169 (".XBTBON2H", 'freqtrade/hello/world/_XBTBON2H-trades.json'),
170 ("ETHUSD.d", 'freqtrade/hello/world/ETHUSD_d-trades.json'),
171 ("ACC_OLD_BTC", 'freqtrade/hello/world/ACC_OLD_BTC-trades.json'),
172])
173def test_json_pair_trades_filename(pair, expected_result):
174 fn = JsonDataHandler._pair_trades_filename(Path('freqtrade/hello/world'), pair)
175 assert isinstance(fn, Path)
176 assert fn == Path(expected_result)
177
178 fn = JsonGzDataHandler._pair_trades_filename(Path('freqtrade/hello/world'), pair)
179 assert isinstance(fn, Path)
180 assert fn == Path(expected_result + '.gz')
181
182
183def test_load_cached_data_for_updating(mocker, testdatadir) -> None:
184
185 data_handler = get_datahandler(testdatadir, 'json')
186
187 test_data = None
188 test_filename = testdatadir.joinpath('UNITTEST_BTC-1m.json')
189 with open(test_filename, "rt") as file:
190 test_data = json.load(file)
191
192 test_data_df = ohlcv_to_dataframe(test_data, '1m', 'UNITTEST/BTC',
193 fill_missing=False, drop_incomplete=False)
194 # now = last cached item + 1 hour
195 now_ts = test_data[-1][0] / 1000 + 60 * 60
196 mocker.patch('arrow.utcnow', return_value=arrow.get(now_ts))
197
198 # timeframe starts earlier than the cached data
199 # should fully update data
200 timerange = TimeRange('date', None, test_data[0][0] / 1000 - 1, 0)
201 data, start_ts = _load_cached_data_for_updating('UNITTEST/BTC', '1m', timerange, data_handler)
202 assert data.empty
203 assert start_ts == test_data[0][0] - 1000
204
205 # timeframe starts in the center of the cached data
206 # should return the chached data w/o the last item
207 timerange = TimeRange('date', None, test_data[0][0] / 1000 + 1, 0)
208 data, start_ts = _load_cached_data_for_updating('UNITTEST/BTC', '1m', timerange, data_handler)
209
210 assert_frame_equal(data, test_data_df.iloc[:-1])
211 assert test_data[-2][0] <= start_ts < test_data[-1][0]
212
213 # timeframe starts after the chached data
214 # should return the chached data w/o the last item
215 timerange = TimeRange('date', None, test_data[-1][0] / 1000 + 100, 0)
216 data, start_ts = _load_cached_data_for_updating('UNITTEST/BTC', '1m', timerange, data_handler)
217 assert_frame_equal(data, test_data_df.iloc[:-1])
218 assert test_data[-2][0] <= start_ts < test_data[-1][0]
219
220 # no datafile exist
221 # should return timestamp start time
222 timerange = TimeRange('date', None, now_ts - 10000, 0)
223 data, start_ts = _load_cached_data_for_updating('NONEXIST/BTC', '1m', timerange, data_handler)
224 assert data.empty
225 assert start_ts == (now_ts - 10000) * 1000
226
227 # no datafile exist, no timeframe is set
228 # should return an empty array and None
229 data, start_ts = _load_cached_data_for_updating('NONEXIST/BTC', '1m', None, data_handler)
230 assert data.empty
231 assert start_ts is None
232
233
234def test_download_pair_history(ohlcv_history_list, mocker, default_conf, testdatadir) -> None:
235 mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=ohlcv_history_list)
236 exchange = get_patched_exchange(mocker, default_conf)
237 file1_1 = testdatadir / 'MEME_BTC-1m.json'
238 file1_5 = testdatadir / 'MEME_BTC-5m.json'
239 file2_1 = testdatadir / 'CFI_BTC-1m.json'
240 file2_5 = testdatadir / 'CFI_BTC-5m.json'
241
242 _backup_file(file1_1)
243 _backup_file(file1_5)
244 _backup_file(file2_1)
245 _backup_file(file2_5)
246
247 assert not file1_1.is_file()
248 assert not file2_1.is_file()
249
250 assert _download_pair_history(datadir=testdatadir, exchange=exchange,
251 pair='MEME/BTC',
252 timeframe='1m')
253 assert _download_pair_history(datadir=testdatadir, exchange=exchange,
254 pair='CFI/BTC',
255 timeframe='1m')
256 assert not exchange._pairs_last_refresh_time
257 assert file1_1.is_file()
258 assert file2_1.is_file()
259
260 # clean files freshly downloaded
261 _clean_test_file(file1_1)
262 _clean_test_file(file2_1)
263
264 assert not file1_5.is_file()
265 assert not file2_5.is_file()
266
267 assert _download_pair_history(datadir=testdatadir, exchange=exchange,
268 pair='MEME/BTC',
269 timeframe='5m')
270 assert _download_pair_history(datadir=testdatadir, exchange=exchange,
271 pair='CFI/BTC',
272 timeframe='5m')
273 assert not exchange._pairs_last_refresh_time
274 assert file1_5.is_file()
275 assert file2_5.is_file()
276
277 # clean files freshly downloaded
278 _clean_test_file(file1_5)
279 _clean_test_file(file2_5)
280
281
282def test_download_pair_history2(mocker, default_conf, testdatadir) -> None:
283 tick = [
284 [1509836520000, 0.00162008, 0.00162008, 0.00162008, 0.00162008, 108.14853839],
285 [1509836580000, 0.00161, 0.00161, 0.00161, 0.00161, 82.390199]
286 ]
287 json_dump_mock = mocker.patch(
288 'freqtrade.data.history.jsondatahandler.JsonDataHandler.ohlcv_store',
289 return_value=None)
290 mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv', return_value=tick)
291 exchange = get_patched_exchange(mocker, default_conf)
292 _download_pair_history(testdatadir, exchange, pair="UNITTEST/BTC", timeframe='1m')
293 _download_pair_history(testdatadir, exchange, pair="UNITTEST/BTC", timeframe='3m')
294 assert json_dump_mock.call_count == 2
295
296
297def test_download_backtesting_data_exception(ohlcv_history, mocker, caplog,
298 default_conf, testdatadir) -> None:
299 mocker.patch('freqtrade.exchange.Exchange.get_historic_ohlcv',
300 side_effect=Exception('File Error'))
301
302 exchange = get_patched_exchange(mocker, default_conf)
303
304 file1_1 = testdatadir / 'MEME_BTC-1m.json'
305 file1_5 = testdatadir / 'MEME_BTC-5m.json'
306 _backup_file(file1_1)
307 _backup_file(file1_5)
308
309 assert not _download_pair_history(datadir=testdatadir, exchange=exchange,
310 pair='MEME/BTC',
311 timeframe='1m')
312 # clean files freshly downloaded
313 _clean_test_file(file1_1)
314 _clean_test_file(file1_5)
315 assert log_has('Failed to download history data for pair: "MEME/BTC", timeframe: 1m.', caplog)
316
317
318def test_load_partial_missing(testdatadir, caplog) -> None:
319 # Make sure we start fresh - test missing data at start
320 start = arrow.get('2018-01-01T00:00:00')
321 end = arrow.get('2018-01-11T00:00:00')
322 data = load_data(testdatadir, '5m', ['UNITTEST/BTC'], startup_candles=20,
323 timerange=TimeRange('date', 'date', start.int_timestamp, end.int_timestamp))
324 assert log_has(
325 'Using indicator startup period: 20 ...', caplog
326 )
327 # timedifference in 5 minutes
328 td = ((end - start).total_seconds() // 60 // 5) + 1
329 assert td != len(data['UNITTEST/BTC'])
330 start_real = data['UNITTEST/BTC'].iloc[0, 0]
331 assert log_has(f'Missing data at start for pair '
332 f'UNITTEST/BTC, data starts at {start_real.strftime("%Y-%m-%d %H:%M:%S")}',
333 caplog)
334 # Make sure we start fresh - test missing data at end
335 caplog.clear()
336 start = arrow.get('2018-01-10T00:00:00')
337 end = arrow.get('2018-02-20T00:00:00')
338 data = load_data(datadir=testdatadir, timeframe='5m', pairs=['UNITTEST/BTC'],
339 timerange=TimeRange('date', 'date', start.int_timestamp, end.int_timestamp))
340 # timedifference in 5 minutes
341 td = ((end - start).total_seconds() // 60 // 5) + 1
342 assert td != len(data['UNITTEST/BTC'])
343
344 # Shift endtime with +5 - as last candle is dropped (partial candle)
345 end_real = arrow.get(data['UNITTEST/BTC'].iloc[-1, 0]).shift(minutes=5)
346 assert log_has(f'Missing data at end for pair '
347 f'UNITTEST/BTC, data ends at {end_real.strftime("%Y-%m-%d %H:%M:%S")}',
348 caplog)
349
350
351def test_init(default_conf, mocker) -> None:
352 assert {} == load_data(
353 datadir=Path(''),
354 pairs=[],
355 timeframe=default_conf['timeframe']
356 )
357
358
359def test_init_with_refresh(default_conf, mocker) -> None:
360 exchange = get_patched_exchange(mocker, default_conf)
361 refresh_data(
362 datadir=Path(''),
363 pairs=[],
364 timeframe=default_conf['timeframe'],
365 exchange=exchange
366 )
367 assert {} == load_data(
368 datadir=Path(''),
369 pairs=[],
370 timeframe=default_conf['timeframe']
371 )
372
373
374def test_file_dump_json_tofile(testdatadir) -> None:
375 file = testdatadir / 'test_{id}.json'.format(id=str(uuid.uuid4()))
376 data = {'bar': 'foo'}
377
378 # check the file we will create does not exist
379 assert not file.is_file()
380
381 # Create the Json file
382 file_dump_json(file, data)
383
384 # Check the file was create
385 assert file.is_file()
386
387 # Open the Json file created and test the data is in it
388 with file.open() as data_file:
389 json_from_file = json.load(data_file)
390
391 assert 'bar' in json_from_file
392 assert json_from_file['bar'] == 'foo'
393
394 # Remove the file
395 _clean_test_file(file)
396
397
398def test_get_timerange(default_conf, mocker, testdatadir) -> None:
399 patch_exchange(mocker)
400
401 default_conf.update({'strategy': 'DefaultStrategy'})
402 strategy = StrategyResolver.load_strategy(default_conf)
403
404 data = strategy.ohlcvdata_to_dataframe(
405 load_data(
406 datadir=testdatadir,
407 timeframe='1m',
408 pairs=['UNITTEST/BTC']
409 )
410 )
411 min_date, max_date = get_timerange(data)
412 assert min_date.isoformat() == '2017-11-04T23:02:00+00:00'
413 assert max_date.isoformat() == '2017-11-14T22:58:00+00:00'
414
415
416def test_validate_backtest_data_warn(default_conf, mocker, caplog, testdatadir) -> None:
417 patch_exchange(mocker)
418
419 default_conf.update({'strategy': 'DefaultStrategy'})
420 strategy = StrategyResolver.load_strategy(default_conf)
421
422 data = strategy.ohlcvdata_to_dataframe(
423 load_data(
424 datadir=testdatadir,
425 timeframe='1m',
426 pairs=['UNITTEST/BTC'],
427 fill_up_missing=False
428 )
429 )
430 min_date, max_date = get_timerange(data)
431 caplog.clear()
432 assert validate_backtest_data(data['UNITTEST/BTC'], 'UNITTEST/BTC',
433 min_date, max_date, timeframe_to_minutes('1m'))
434 assert len(caplog.record_tuples) == 1
435 assert log_has(
436 "UNITTEST/BTC has missing frames: expected 14396, got 13680, that's 716 missing values",
437 caplog)
438
439
440def test_validate_backtest_data(default_conf, mocker, caplog, testdatadir) -> None:
441 patch_exchange(mocker)
442
443 default_conf.update({'strategy': 'DefaultStrategy'})
444 strategy = StrategyResolver.load_strategy(default_conf)
445
446 timerange = TimeRange('index', 'index', 200, 250)
447 data = strategy.ohlcvdata_to_dataframe(
448 load_data(
449 datadir=testdatadir,
450 timeframe='5m',
451 pairs=['UNITTEST/BTC'],
452 timerange=timerange
453 )
454 )
455
456 min_date, max_date = get_timerange(data)
457 caplog.clear()
458 assert not validate_backtest_data(data['UNITTEST/BTC'], 'UNITTEST/BTC',
459 min_date, max_date, timeframe_to_minutes('5m'))
460 assert len(caplog.record_tuples) == 0
461
462
463def test_refresh_backtest_ohlcv_data(mocker, default_conf, markets, caplog, testdatadir):
464 dl_mock = mocker.patch('freqtrade.data.history.history_utils._download_pair_history',
465 MagicMock())
466 mocker.patch(
467 'freqtrade.exchange.Exchange.markets', PropertyMock(return_value=markets)
468 )
469 mocker.patch.object(Path, "exists", MagicMock(return_value=True))
470 mocker.patch.object(Path, "unlink", MagicMock())
471
472 ex = get_patched_exchange(mocker, default_conf)
473 timerange = TimeRange.parse_timerange("20190101-20190102")
474 refresh_backtest_ohlcv_data(exchange=ex, pairs=["ETH/BTC", "XRP/BTC"],
475 timeframes=["1m", "5m"], datadir=testdatadir,
476 timerange=timerange, erase=True
477 )
478
479 assert dl_mock.call_count == 4
480 assert dl_mock.call_args[1]['timerange'].starttype == 'date'
481
482 assert log_has("Downloading pair ETH/BTC, interval 1m.", caplog)
483
484
485def test_download_data_no_markets(mocker, default_conf, caplog, testdatadir):
486 dl_mock = mocker.patch('freqtrade.data.history.history_utils._download_pair_history',
487 MagicMock())
488
489 ex = get_patched_exchange(mocker, default_conf)
490 mocker.patch(
491 'freqtrade.exchange.Exchange.markets', PropertyMock(return_value={})
492 )
493 timerange = TimeRange.parse_timerange("20190101-20190102")
494 unav_pairs = refresh_backtest_ohlcv_data(exchange=ex, pairs=["BTT/BTC", "LTC/USDT"],
495 timeframes=["1m", "5m"],
496 datadir=testdatadir,
497 timerange=timerange, erase=False
498 )
499
500 assert dl_mock.call_count == 0
501 assert "BTT/BTC" in unav_pairs
502 assert "LTC/USDT" in unav_pairs
503 assert log_has("Skipping pair BTT/BTC...", caplog)
504
505
506def test_refresh_backtest_trades_data(mocker, default_conf, markets, caplog, testdatadir):
507 dl_mock = mocker.patch('freqtrade.data.history.history_utils._download_trades_history',
508 MagicMock())
509 mocker.patch(
510 'freqtrade.exchange.Exchange.markets', PropertyMock(return_value=markets)
511 )
512 mocker.patch.object(Path, "exists", MagicMock(return_value=True))
513 mocker.patch.object(Path, "unlink", MagicMock())
514
515 ex = get_patched_exchange(mocker, default_conf)
516 timerange = TimeRange.parse_timerange("20190101-20190102")
517 unavailable_pairs = refresh_backtest_trades_data(exchange=ex,
518 pairs=["ETH/BTC", "XRP/BTC", "XRP/ETH"],
519 datadir=testdatadir,
520 timerange=timerange, erase=True
521 )
522
523 assert dl_mock.call_count == 2
524 assert dl_mock.call_args[1]['timerange'].starttype == 'date'
525
526 assert log_has("Downloading trades for pair ETH/BTC.", caplog)
527 assert unavailable_pairs == ["XRP/ETH"]
528 assert log_has("Skipping pair XRP/ETH...", caplog)
529
530
531def test_download_trades_history(trades_history, mocker, default_conf, testdatadir, caplog) -> None:
532
533 ght_mock = MagicMock(side_effect=lambda pair, *args, **kwargs: (pair, trades_history))
534 mocker.patch('freqtrade.exchange.Exchange.get_historic_trades',
535 ght_mock)
536 exchange = get_patched_exchange(mocker, default_conf)
537 file1 = testdatadir / 'ETH_BTC-trades.json.gz'
538 data_handler = get_datahandler(testdatadir, data_format='jsongz')
539 _backup_file(file1)
540
541 assert not file1.is_file()
542
543 assert _download_trades_history(data_handler=data_handler, exchange=exchange,
544 pair='ETH/BTC')
545 assert log_has("New Amount of trades: 5", caplog)
546 assert file1.is_file()
547
548 ght_mock.reset_mock()
549 since_time = int(trades_history[-3][0] // 1000)
550 since_time2 = int(trades_history[-1][0] // 1000)
551 timerange = TimeRange('date', None, since_time, 0)
552 assert _download_trades_history(data_handler=data_handler, exchange=exchange,
553 pair='ETH/BTC', timerange=timerange)
554
555 assert ght_mock.call_count == 1
556 # Check this in seconds - since we had to convert to seconds above too.
557 assert int(ght_mock.call_args_list[0][1]['since'] // 1000) == since_time2 - 5
558 assert ght_mock.call_args_list[0][1]['from_id'] is not None
559
560 # clean files freshly downloaded
561 _clean_test_file(file1)
562
563 mocker.patch('freqtrade.exchange.Exchange.get_historic_trades',
564 MagicMock(side_effect=ValueError))
565
566 assert not _download_trades_history(data_handler=data_handler, exchange=exchange,
567 pair='ETH/BTC')
568 assert log_has_re('Failed to download historic trades for pair: "ETH/BTC".*', caplog)
569
570 file2 = testdatadir / 'XRP_ETH-trades.json.gz'
571
572 _backup_file(file2, True)
573
574 ght_mock.reset_mock()
575 mocker.patch('freqtrade.exchange.Exchange.get_historic_trades',
576 ght_mock)
577 # Since before first start date
578 since_time = int(trades_history[0][0] // 1000) - 500
579 timerange = TimeRange('date', None, since_time, 0)
580
581 assert _download_trades_history(data_handler=data_handler, exchange=exchange,
582 pair='XRP/ETH', timerange=timerange)
583
584 assert ght_mock.call_count == 1
585
586 assert int(ght_mock.call_args_list[0][1]['since'] // 1000) == since_time
587 assert ght_mock.call_args_list[0][1]['from_id'] is None
588 assert log_has_re(r'Start earlier than available data. Redownloading trades for.*', caplog)
589 _clean_test_file(file2)
590
591
592def test_convert_trades_to_ohlcv(mocker, default_conf, testdatadir, caplog):
593
594 pair = 'XRP/ETH'
595 file1 = testdatadir / 'XRP_ETH-1m.json'
596 file5 = testdatadir / 'XRP_ETH-5m.json'
597 # Compare downloaded dataset with converted dataset
598 dfbak_1m = load_pair_history(datadir=testdatadir, timeframe="1m", pair=pair)
599 dfbak_5m = load_pair_history(datadir=testdatadir, timeframe="5m", pair=pair)
600
601 _backup_file(file1, copy_file=True)
602 _backup_file(file5)
603
604 tr = TimeRange.parse_timerange('20191011-20191012')
605
606 convert_trades_to_ohlcv([pair], timeframes=['1m', '5m'],
607 datadir=testdatadir, timerange=tr, erase=True)
608
609 assert log_has("Deleting existing data for pair XRP/ETH, interval 1m.", caplog)
610 # Load new data
611 df_1m = load_pair_history(datadir=testdatadir, timeframe="1m", pair=pair)
612 df_5m = load_pair_history(datadir=testdatadir, timeframe="5m", pair=pair)
613
614 assert df_1m.equals(dfbak_1m)
615 assert df_5m.equals(dfbak_5m)
616
617 _clean_test_file(file1)
618 _clean_test_file(file5)
619
620 assert not log_has('Could not convert NoDatapair to OHLCV.', caplog)
621
622 convert_trades_to_ohlcv(['NoDatapair'], timeframes=['1m', '5m'],
623 datadir=testdatadir, timerange=tr, erase=True)
624 assert log_has('Could not convert NoDatapair to OHLCV.', caplog)
625
626
627def test_datahandler_ohlcv_get_pairs(testdatadir):
628 pairs = JsonDataHandler.ohlcv_get_pairs(testdatadir, '5m')
629 # Convert to set to avoid failures due to sorting
630 assert set(pairs) == {'UNITTEST/BTC', 'XLM/BTC', 'ETH/BTC', 'TRX/BTC', 'LTC/BTC',
631 'XMR/BTC', 'ZEC/BTC', 'ADA/BTC', 'ETC/BTC', 'NXT/BTC',
632 'DASH/BTC', 'XRP/ETH'}
633
634 pairs = JsonGzDataHandler.ohlcv_get_pairs(testdatadir, '8m')
635 assert set(pairs) == {'UNITTEST/BTC'}
636
637 pairs = HDF5DataHandler.ohlcv_get_pairs(testdatadir, '5m')
638 assert set(pairs) == {'UNITTEST/BTC'}
639
640
641def test_datahandler_ohlcv_get_available_data(testdatadir):
642 paircombs = JsonDataHandler.ohlcv_get_available_data(testdatadir)
643 # Convert to set to avoid failures due to sorting
644 assert set(paircombs) == {('UNITTEST/BTC', '5m'), ('ETH/BTC', '5m'), ('XLM/BTC', '5m'),
645 ('TRX/BTC', '5m'), ('LTC/BTC', '5m'), ('XMR/BTC', '5m'),
646 ('ZEC/BTC', '5m'), ('UNITTEST/BTC', '1m'), ('ADA/BTC', '5m'),
647 ('ETC/BTC', '5m'), ('NXT/BTC', '5m'), ('DASH/BTC', '5m'),
648 ('XRP/ETH', '1m'), ('XRP/ETH', '5m'), ('UNITTEST/BTC', '30m'),
649 ('UNITTEST/BTC', '8m'), ('NOPAIR/XXX', '4m')}
650
651 paircombs = JsonGzDataHandler.ohlcv_get_available_data(testdatadir)
652 assert set(paircombs) == {('UNITTEST/BTC', '8m')}
653 paircombs = HDF5DataHandler.ohlcv_get_available_data(testdatadir)
654 assert set(paircombs) == {('UNITTEST/BTC', '5m')}
655
656
657def test_jsondatahandler_trades_get_pairs(testdatadir):
658 pairs = JsonGzDataHandler.trades_get_pairs(testdatadir)
659 # Convert to set to avoid failures due to sorting
660 assert set(pairs) == {'XRP/ETH', 'XRP/OLD'}
661
662
663def test_jsondatahandler_ohlcv_purge(mocker, testdatadir):
664 mocker.patch.object(Path, "exists", MagicMock(return_value=False))
665 unlinkmock = mocker.patch.object(Path, "unlink", MagicMock())
666 dh = JsonGzDataHandler(testdatadir)
667 assert not dh.ohlcv_purge('UNITTEST/NONEXIST', '5m')
668 assert unlinkmock.call_count == 0
669
670 mocker.patch.object(Path, "exists", MagicMock(return_value=True))
671 assert dh.ohlcv_purge('UNITTEST/NONEXIST', '5m')
672 assert unlinkmock.call_count == 1
673
674
675def test_jsondatahandler_ohlcv_load(testdatadir, caplog):
676 dh = JsonDataHandler(testdatadir)
677 df = dh.ohlcv_load('XRP/ETH', '5m')
678 assert len(df) == 711
679
680 # Failure case (empty array)
681 df1 = dh.ohlcv_load('NOPAIR/XXX', '4m')
682 assert len(df1) == 0
683 assert log_has("Could not load data for NOPAIR/XXX.", caplog)
684 assert df.columns.equals(df1.columns)
685
686
687def test_jsondatahandler_trades_load(testdatadir, caplog):
688 dh = JsonGzDataHandler(testdatadir)
689 logmsg = "Old trades format detected - converting"
690 dh.trades_load('XRP/ETH')
691 assert not log_has(logmsg, caplog)
692
693 # Test conversation is happening
694 dh.trades_load('XRP/OLD')
695 assert log_has(logmsg, caplog)
696
697
698def test_jsondatahandler_trades_purge(mocker, testdatadir):
699 mocker.patch.object(Path, "exists", MagicMock(return_value=False))
700 unlinkmock = mocker.patch.object(Path, "unlink", MagicMock())
701 dh = JsonGzDataHandler(testdatadir)
702 assert not dh.trades_purge('UNITTEST/NONEXIST')
703 assert unlinkmock.call_count == 0
704
705 mocker.patch.object(Path, "exists", MagicMock(return_value=True))
706 assert dh.trades_purge('UNITTEST/NONEXIST')
707 assert unlinkmock.call_count == 1
708
709
710@pytest.mark.parametrize('datahandler', AVAILABLE_DATAHANDLERS)
711def test_datahandler_ohlcv_append(datahandler, testdatadir, ):
712 dh = get_datahandler(testdatadir, datahandler)
713 with pytest.raises(NotImplementedError):
714 dh.ohlcv_append('UNITTEST/ETH', '5m', DataFrame())
715
716
717@pytest.mark.parametrize('datahandler', AVAILABLE_DATAHANDLERS)
718def test_datahandler_trades_append(datahandler, testdatadir):
719 dh = get_datahandler(testdatadir, datahandler)
720 with pytest.raises(NotImplementedError):
721 dh.trades_append('UNITTEST/ETH', [])
722
723
724def test_hdf5datahandler_trades_get_pairs(testdatadir):
725 pairs = HDF5DataHandler.trades_get_pairs(testdatadir)
726 # Convert to set to avoid failures due to sorting
727 assert set(pairs) == {'XRP/ETH'}
728
729
730def test_hdf5datahandler_trades_load(testdatadir):
731 dh = HDF5DataHandler(testdatadir)
732 trades = dh.trades_load('XRP/ETH')
733 assert isinstance(trades, list)
734
735 trades1 = dh.trades_load('UNITTEST/NONEXIST')
736 assert trades1 == []
737 # data goes from 2019-10-11 - 2019-10-13
738 timerange = TimeRange.parse_timerange('20191011-20191012')
739
740 trades2 = dh._trades_load('XRP/ETH', timerange)
741 assert len(trades) > len(trades2)
742 # Check that ID is None (If it's nan, it's wrong)
743 assert trades2[0][2] is None
744
745 # unfiltered load has trades before starttime
746 assert len([t for t in trades if t[0] < timerange.startts * 1000]) >= 0
747 # filtered list does not have trades before starttime
748 assert len([t for t in trades2 if t[0] < timerange.startts * 1000]) == 0
749 # unfiltered load has trades after endtime
750 assert len([t for t in trades if t[0] > timerange.stopts * 1000]) > 0
751 # filtered list does not have trades after endtime
752 assert len([t for t in trades2 if t[0] > timerange.stopts * 1000]) == 0
753
754
755def test_hdf5datahandler_trades_store(testdatadir):
756 dh = HDF5DataHandler(testdatadir)
757 trades = dh.trades_load('XRP/ETH')
758
759 dh.trades_store('XRP/NEW', trades)
760 file = testdatadir / 'XRP_NEW-trades.h5'
761 assert file.is_file()
762 # Load trades back
763 trades_new = dh.trades_load('XRP/NEW')
764
765 assert len(trades_new) == len(trades)
766 assert trades[0][0] == trades_new[0][0]
767 assert trades[0][1] == trades_new[0][1]
768 # assert trades[0][2] == trades_new[0][2] # This is nan - so comparison does not make sense
769 assert trades[0][3] == trades_new[0][3]
770 assert trades[0][4] == trades_new[0][4]
771 assert trades[0][5] == trades_new[0][5]
772 assert trades[0][6] == trades_new[0][6]
773 assert trades[-1][0] == trades_new[-1][0]
774 assert trades[-1][1] == trades_new[-1][1]
775 # assert trades[-1][2] == trades_new[-1][2] # This is nan - so comparison does not make sense
776 assert trades[-1][3] == trades_new[-1][3]
777 assert trades[-1][4] == trades_new[-1][4]
778 assert trades[-1][5] == trades_new[-1][5]
779 assert trades[-1][6] == trades_new[-1][6]
780
781 _clean_test_file(file)
782
783
784def test_hdf5datahandler_trades_purge(mocker, testdatadir):
785 mocker.patch.object(Path, "exists", MagicMock(return_value=False))
786 unlinkmock = mocker.patch.object(Path, "unlink", MagicMock())
787 dh = HDF5DataHandler(testdatadir)
788 assert not dh.trades_purge('UNITTEST/NONEXIST')
789 assert unlinkmock.call_count == 0
790
791 mocker.patch.object(Path, "exists", MagicMock(return_value=True))
792 assert dh.trades_purge('UNITTEST/NONEXIST')
793 assert unlinkmock.call_count == 1
794
795
796def test_hdf5datahandler_ohlcv_load_and_resave(testdatadir):
797 dh = HDF5DataHandler(testdatadir)
798 ohlcv = dh.ohlcv_load('UNITTEST/BTC', '5m')
799 assert isinstance(ohlcv, DataFrame)
800 assert len(ohlcv) > 0
801
802 file = testdatadir / 'UNITTEST_NEW-5m.h5'
803 assert not file.is_file()
804
805 dh.ohlcv_store('UNITTEST/NEW', '5m', ohlcv)
806 assert file.is_file()
807
808 assert not ohlcv[ohlcv['date'] < '2018-01-15'].empty
809
810 # Data gores from 2018-01-10 - 2018-01-30
811 timerange = TimeRange.parse_timerange('20180115-20180119')
812
813 # Call private function to ensure timerange is filtered in hdf5
814 ohlcv = dh._ohlcv_load('UNITTEST/BTC', '5m', timerange)
815 ohlcv1 = dh._ohlcv_load('UNITTEST/NEW', '5m', timerange)
816 assert len(ohlcv) == len(ohlcv1)
817 assert ohlcv.equals(ohlcv1)
818 assert ohlcv[ohlcv['date'] < '2018-01-15'].empty
819 assert ohlcv[ohlcv['date'] > '2018-01-19'].empty
820
821 _clean_test_file(file)
822
823 # Try loading inexisting file
824 ohlcv = dh.ohlcv_load('UNITTEST/NONEXIST', '5m')
825 assert ohlcv.empty
826
827
828def test_hdf5datahandler_ohlcv_purge(mocker, testdatadir):
829 mocker.patch.object(Path, "exists", MagicMock(return_value=False))
830 unlinkmock = mocker.patch.object(Path, "unlink", MagicMock())
831 dh = HDF5DataHandler(testdatadir)
832 assert not dh.ohlcv_purge('UNITTEST/NONEXIST', '5m')
833 assert unlinkmock.call_count == 0
834
835 mocker.patch.object(Path, "exists", MagicMock(return_value=True))
836 assert dh.ohlcv_purge('UNITTEST/NONEXIST', '5m')
837 assert unlinkmock.call_count == 1
838
839
840def test_gethandlerclass():
841 cl = get_datahandlerclass('json')
842 assert cl == JsonDataHandler
843 assert issubclass(cl, IDataHandler)
844 cl = get_datahandlerclass('jsongz')
845 assert cl == JsonGzDataHandler
846 assert issubclass(cl, IDataHandler)
847 assert issubclass(cl, JsonDataHandler)
848 cl = get_datahandlerclass('hdf5')
849 assert cl == HDF5DataHandler
850 assert issubclass(cl, IDataHandler)
851 with pytest.raises(ValueError, match=r"No datahandler for .*"):
852 get_datahandlerclass('DeadBeef')
853
854
855def test_get_datahandler(testdatadir):
856 dh = get_datahandler(testdatadir, 'json')
857 assert type(dh) == JsonDataHandler
858 dh = get_datahandler(testdatadir, 'jsongz')
859 assert type(dh) == JsonGzDataHandler
860 dh1 = get_datahandler(testdatadir, 'jsongz', dh)
861 assert id(dh1) == id(dh)
862
863 dh = get_datahandler(testdatadir, 'hdf5')
864 assert type(dh) == HDF5DataHandler