2018-02-09 07:35:38 +00:00
|
|
|
# pragma pylint: disable=missing-docstring, W0212, line-too-long, C0103, unused-argument
|
2017-11-24 22:58:35 +00:00
|
|
|
|
2018-02-09 07:35:38 +00:00
|
|
|
import json
|
2017-12-28 14:58:02 +00:00
|
|
|
import math
|
2018-03-17 21:44:47 +00:00
|
|
|
import random
|
|
|
|
from typing import List
|
2018-01-05 09:23:12 +00:00
|
|
|
from unittest.mock import MagicMock
|
2018-03-17 21:44:47 +00:00
|
|
|
|
2018-02-08 19:49:43 +00:00
|
|
|
import numpy as np
|
2018-03-17 21:44:47 +00:00
|
|
|
import pandas as pd
|
2018-07-04 07:31:35 +00:00
|
|
|
import pytest
|
2018-03-17 21:44:47 +00:00
|
|
|
from arrow import Arrow
|
|
|
|
|
2018-12-13 05:35:28 +00:00
|
|
|
from freqtrade import DependencyException, constants
|
2018-06-05 21:53:49 +00:00
|
|
|
from freqtrade.arguments import Arguments, TimeRange
|
2018-12-13 05:35:28 +00:00
|
|
|
from freqtrade.data import history
|
2018-12-15 14:34:25 +00:00
|
|
|
from freqtrade.data.converter import parse_ticker_dataframe
|
2019-03-07 20:24:26 +00:00
|
|
|
from freqtrade.data.btanalysis import evaluate_result_multi
|
2018-11-04 12:23:59 +00:00
|
|
|
from freqtrade.optimize import get_timeframe
|
2018-07-04 07:31:35 +00:00
|
|
|
from freqtrade.optimize.backtesting import (Backtesting, setup_configuration,
|
|
|
|
start)
|
2018-12-25 13:35:48 +00:00
|
|
|
from freqtrade.state import RunMode
|
2018-07-09 16:27:36 +00:00
|
|
|
from freqtrade.strategy.default_strategy import DefaultStrategy
|
2018-12-13 05:35:28 +00:00
|
|
|
from freqtrade.strategy.interface import SellType
|
|
|
|
from freqtrade.tests.conftest import log_has, patch_exchange
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
|
|
|
|
def get_args(args) -> List[str]:
|
|
|
|
return Arguments(args, '').get_parsed_arg()
|
2017-11-24 22:58:35 +00:00
|
|
|
|
2017-12-16 02:39:47 +00:00
|
|
|
|
2018-01-28 07:38:41 +00:00
|
|
|
def trim_dictlist(dict_list, num):
|
2018-01-17 17:19:39 +00:00
|
|
|
new = {}
|
2018-01-28 07:38:41 +00:00
|
|
|
for pair, pair_data in dict_list.items():
|
2018-01-17 17:19:39 +00:00
|
|
|
new[pair] = pair_data[num:]
|
|
|
|
return new
|
|
|
|
|
|
|
|
|
2017-12-28 14:58:02 +00:00
|
|
|
def load_data_test(what):
|
2018-06-07 07:21:07 +00:00
|
|
|
timerange = TimeRange(None, 'line', 0, -101)
|
2018-12-15 14:34:25 +00:00
|
|
|
pair = history.load_tickerdata_file(None, ticker_interval='1m',
|
|
|
|
pair='UNITTEST/BTC', timerange=timerange)
|
2017-12-30 10:55:23 +00:00
|
|
|
datalen = len(pair)
|
2018-12-15 14:34:25 +00:00
|
|
|
|
2017-12-30 10:55:23 +00:00
|
|
|
base = 0.001
|
2017-12-28 14:58:02 +00:00
|
|
|
if what == 'raise':
|
2018-12-15 14:34:25 +00:00
|
|
|
data = [
|
2018-04-09 18:21:54 +00:00
|
|
|
[
|
|
|
|
pair[x][0], # Keep old dates
|
|
|
|
x * base, # But replace O,H,L,C
|
|
|
|
x * base + 0.0001,
|
|
|
|
x * base - 0.0001,
|
|
|
|
x * base,
|
|
|
|
pair[x][5], # Keep old volume
|
|
|
|
] for x in range(0, datalen)
|
2018-12-15 14:34:25 +00:00
|
|
|
]
|
2017-12-28 14:58:02 +00:00
|
|
|
if what == 'lower':
|
2018-12-15 14:34:25 +00:00
|
|
|
data = [
|
2018-04-09 18:21:54 +00:00
|
|
|
[
|
|
|
|
pair[x][0], # Keep old dates
|
|
|
|
1 - x * base, # But replace O,H,L,C
|
|
|
|
1 - x * base + 0.0001,
|
|
|
|
1 - x * base - 0.0001,
|
|
|
|
1 - x * base,
|
|
|
|
pair[x][5] # Keep old volume
|
|
|
|
] for x in range(0, datalen)
|
2018-12-15 14:34:25 +00:00
|
|
|
]
|
2017-12-28 14:58:02 +00:00
|
|
|
if what == 'sine':
|
2017-12-30 10:55:23 +00:00
|
|
|
hz = 0.1 # frequency
|
2018-12-15 14:34:25 +00:00
|
|
|
data = [
|
2018-04-09 18:21:54 +00:00
|
|
|
[
|
|
|
|
pair[x][0], # Keep old dates
|
|
|
|
math.sin(x * hz) / 1000 + base, # But replace O,H,L,C
|
|
|
|
math.sin(x * hz) / 1000 + base + 0.0001,
|
|
|
|
math.sin(x * hz) / 1000 + base - 0.0001,
|
|
|
|
math.sin(x * hz) / 1000 + base,
|
|
|
|
pair[x][5] # Keep old volume
|
|
|
|
] for x in range(0, datalen)
|
2018-12-15 14:34:25 +00:00
|
|
|
]
|
2018-12-31 18:15:05 +00:00
|
|
|
return {'UNITTEST/BTC': parse_ticker_dataframe(data, '1m', fill_missing=True)}
|
2017-12-28 14:58:02 +00:00
|
|
|
|
2017-12-28 19:05:33 +00:00
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def simple_backtest(config, contour, num_results, mocker) -> None:
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-10-16 18:34:20 +00:00
|
|
|
config['ticker_interval'] = '1m'
|
2018-04-21 22:19:11 +00:00
|
|
|
backtesting = Backtesting(config)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
2017-12-28 14:58:02 +00:00
|
|
|
data = load_data_test(contour)
|
2018-10-17 17:47:19 +00:00
|
|
|
processed = backtesting.strategy.tickerdata_to_dataframe(data)
|
2018-11-04 12:23:59 +00:00
|
|
|
min_date, max_date = get_timeframe(processed)
|
2017-12-28 14:58:02 +00:00
|
|
|
assert isinstance(processed, dict)
|
2018-02-09 07:35:38 +00:00
|
|
|
results = backtesting.backtest(
|
|
|
|
{
|
|
|
|
'stake_amount': config['stake_amount'],
|
|
|
|
'processed': processed,
|
|
|
|
'max_open_trades': 1,
|
2018-10-16 18:34:20 +00:00
|
|
|
'position_stacking': False,
|
|
|
|
'start_date': min_date,
|
|
|
|
'end_date': max_date,
|
2018-02-09 07:35:38 +00:00
|
|
|
}
|
|
|
|
)
|
2017-12-28 14:58:02 +00:00
|
|
|
# results :: <class 'pandas.core.frame.DataFrame'>
|
|
|
|
assert len(results) == num_results
|
|
|
|
|
2017-12-30 10:55:23 +00:00
|
|
|
|
2018-06-17 20:29:57 +00:00
|
|
|
def mocked_load_data(datadir, pairs=[], ticker_interval='0m', refresh_pairs=False,
|
|
|
|
timerange=None, exchange=None):
|
2018-12-13 05:35:28 +00:00
|
|
|
tickerdata = history.load_tickerdata_file(datadir, 'UNITTEST/BTC', '1m', timerange=timerange)
|
2018-12-31 18:15:05 +00:00
|
|
|
pairdata = {'UNITTEST/BTC': parse_ticker_dataframe(tickerdata, '1m', fill_missing=True)}
|
2018-02-09 07:35:38 +00:00
|
|
|
return pairdata
|
|
|
|
|
|
|
|
|
2018-08-19 17:48:13 +00:00
|
|
|
# use for mock ccxt.fetch_ohlvc'
|
2018-02-08 19:49:43 +00:00
|
|
|
def _load_pair_as_ticks(pair, tickfreq):
|
2018-12-15 14:34:25 +00:00
|
|
|
ticks = history.load_tickerdata_file(None, ticker_interval=tickfreq, pair=pair)
|
|
|
|
ticks = ticks[-201:]
|
|
|
|
return ticks
|
2018-02-08 19:49:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
# FIX: fixturize this?
|
2018-04-21 22:19:11 +00:00
|
|
|
def _make_backtest_conf(mocker, conf=None, pair='UNITTEST/BTC', record=None):
|
2018-12-15 19:14:13 +00:00
|
|
|
data = history.load_data(datadir=None, ticker_interval='1m', pairs=[pair])
|
2018-06-07 07:21:07 +00:00
|
|
|
data = trim_dictlist(data, -201)
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-04-21 22:19:11 +00:00
|
|
|
backtesting = Backtesting(conf)
|
2018-10-16 18:34:20 +00:00
|
|
|
processed = backtesting.strategy.tickerdata_to_dataframe(data)
|
2018-11-04 12:23:59 +00:00
|
|
|
min_date, max_date = get_timeframe(processed)
|
2018-03-04 00:42:37 +00:00
|
|
|
return {
|
|
|
|
'stake_amount': conf['stake_amount'],
|
2018-10-16 18:34:20 +00:00
|
|
|
'processed': processed,
|
2018-03-04 00:42:37 +00:00
|
|
|
'max_open_trades': 10,
|
2018-07-17 18:26:59 +00:00
|
|
|
'position_stacking': False,
|
2018-10-16 18:34:20 +00:00
|
|
|
'record': record,
|
|
|
|
'start_date': min_date,
|
|
|
|
'end_date': max_date,
|
2018-03-04 00:42:37 +00:00
|
|
|
}
|
2018-02-08 19:49:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _trend(signals, buy_value, sell_value):
|
|
|
|
n = len(signals['low'])
|
|
|
|
buy = np.zeros(n)
|
|
|
|
sell = np.zeros(n)
|
|
|
|
for i in range(0, len(signals['buy'])):
|
|
|
|
if random.random() > 0.5: # Both buy and sell signals at same timeframe
|
|
|
|
buy[i] = buy_value
|
|
|
|
sell[i] = sell_value
|
|
|
|
signals['buy'] = buy
|
|
|
|
signals['sell'] = sell
|
|
|
|
return signals
|
|
|
|
|
|
|
|
|
2018-07-29 19:07:21 +00:00
|
|
|
def _trend_alternate(dataframe=None, metadata=None):
|
2018-02-08 19:49:43 +00:00
|
|
|
signals = dataframe
|
|
|
|
low = signals['low']
|
|
|
|
n = len(low)
|
|
|
|
buy = np.zeros(n)
|
|
|
|
sell = np.zeros(n)
|
|
|
|
for i in range(0, len(buy)):
|
|
|
|
if i % 2 == 0:
|
|
|
|
buy[i] = 1
|
|
|
|
else:
|
|
|
|
sell[i] = 1
|
|
|
|
signals['buy'] = buy
|
|
|
|
signals['sell'] = sell
|
|
|
|
return dataframe
|
|
|
|
|
|
|
|
|
2018-02-09 07:35:38 +00:00
|
|
|
# Unit tests
|
|
|
|
def test_setup_configuration_without_arguments(mocker, default_conf, caplog) -> None:
|
|
|
|
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
|
|
|
read_data=json.dumps(default_conf)
|
|
|
|
))
|
|
|
|
|
|
|
|
args = [
|
|
|
|
'--config', 'config.json',
|
2018-03-24 19:44:04 +00:00
|
|
|
'--strategy', 'DefaultStrategy',
|
2018-02-09 07:35:38 +00:00
|
|
|
'backtesting'
|
|
|
|
]
|
|
|
|
|
|
|
|
config = setup_configuration(get_args(args))
|
|
|
|
assert 'max_open_trades' in config
|
|
|
|
assert 'stake_currency' in config
|
|
|
|
assert 'stake_amount' in config
|
|
|
|
assert 'exchange' in config
|
|
|
|
assert 'pair_whitelist' in config['exchange']
|
|
|
|
assert 'datadir' in config
|
2018-03-04 10:06:40 +00:00
|
|
|
assert log_has(
|
2018-06-02 08:32:05 +00:00
|
|
|
'Using data folder: {} ...'.format(config['datadir']),
|
2018-02-09 07:35:38 +00:00
|
|
|
caplog.record_tuples
|
|
|
|
)
|
|
|
|
assert 'ticker_interval' in config
|
2018-03-04 10:06:40 +00:00
|
|
|
assert not log_has('Parameter -i/--ticker-interval detected ...', caplog.record_tuples)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
assert 'live' not in config
|
2018-03-04 10:06:40 +00:00
|
|
|
assert not log_has('Parameter -l/--live detected ...', caplog.record_tuples)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
2018-07-17 18:26:59 +00:00
|
|
|
assert 'position_stacking' not in config
|
|
|
|
assert not log_has('Parameter --enable-position-stacking detected ...', caplog.record_tuples)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
assert 'refresh_pairs' not in config
|
2018-03-04 10:06:40 +00:00
|
|
|
assert not log_has('Parameter -r/--refresh-pairs-cached detected ...', caplog.record_tuples)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
assert 'timerange' not in config
|
|
|
|
assert 'export' not in config
|
2018-12-25 13:35:48 +00:00
|
|
|
assert 'runmode' in config
|
|
|
|
assert config['runmode'] == RunMode.BACKTEST
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
|
2019-01-01 13:07:40 +00:00
|
|
|
def test_setup_bt_configuration_with_arguments(mocker, default_conf, caplog) -> None:
|
2018-02-09 07:35:38 +00:00
|
|
|
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
|
|
|
read_data=json.dumps(default_conf)
|
|
|
|
))
|
2019-01-01 13:07:40 +00:00
|
|
|
mocker.patch('freqtrade.configuration.Configuration._create_datadir', lambda s, c, x: x)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
args = [
|
|
|
|
'--config', 'config.json',
|
2018-03-24 19:44:04 +00:00
|
|
|
'--strategy', 'DefaultStrategy',
|
2018-02-09 07:35:38 +00:00
|
|
|
'--datadir', '/foo/bar',
|
|
|
|
'backtesting',
|
2018-03-25 20:03:26 +00:00
|
|
|
'--ticker-interval', '1m',
|
2018-02-09 07:35:38 +00:00
|
|
|
'--live',
|
2018-07-17 18:26:59 +00:00
|
|
|
'--enable-position-stacking',
|
2018-07-17 19:05:03 +00:00
|
|
|
'--disable-max-market-positions',
|
2018-02-09 07:35:38 +00:00
|
|
|
'--refresh-pairs-cached',
|
|
|
|
'--timerange', ':100',
|
2018-06-03 12:52:03 +00:00
|
|
|
'--export', '/bar/foo',
|
|
|
|
'--export-filename', 'foo_bar.json'
|
2018-02-09 07:35:38 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
config = setup_configuration(get_args(args))
|
|
|
|
assert 'max_open_trades' in config
|
|
|
|
assert 'stake_currency' in config
|
|
|
|
assert 'stake_amount' in config
|
|
|
|
assert 'exchange' in config
|
|
|
|
assert 'pair_whitelist' in config['exchange']
|
|
|
|
assert 'datadir' in config
|
2018-12-25 13:35:48 +00:00
|
|
|
assert config['runmode'] == RunMode.BACKTEST
|
|
|
|
|
2018-03-04 10:06:40 +00:00
|
|
|
assert log_has(
|
2018-06-02 08:32:05 +00:00
|
|
|
'Using data folder: {} ...'.format(config['datadir']),
|
2018-02-09 07:35:38 +00:00
|
|
|
caplog.record_tuples
|
|
|
|
)
|
|
|
|
assert 'ticker_interval' in config
|
2018-03-04 10:06:40 +00:00
|
|
|
assert log_has('Parameter -i/--ticker-interval detected ...', caplog.record_tuples)
|
|
|
|
assert log_has(
|
2018-03-25 20:03:26 +00:00
|
|
|
'Using ticker_interval: 1m ...',
|
2018-02-09 07:35:38 +00:00
|
|
|
caplog.record_tuples
|
|
|
|
)
|
|
|
|
|
|
|
|
assert 'live' in config
|
2018-03-04 10:06:40 +00:00
|
|
|
assert log_has('Parameter -l/--live detected ...', caplog.record_tuples)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
2018-07-17 18:26:59 +00:00
|
|
|
assert 'position_stacking' in config
|
|
|
|
assert log_has('Parameter --enable-position-stacking detected ...', caplog.record_tuples)
|
2018-07-17 19:05:03 +00:00
|
|
|
|
|
|
|
assert 'use_max_market_positions' in config
|
|
|
|
assert log_has('Parameter --disable-max-market-positions detected ...', caplog.record_tuples)
|
|
|
|
assert log_has('max_open_trades set to unlimited ...', caplog.record_tuples)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
2018-04-09 18:21:54 +00:00
|
|
|
assert 'refresh_pairs' in config
|
2018-03-04 10:06:40 +00:00
|
|
|
assert log_has('Parameter -r/--refresh-pairs-cached detected ...', caplog.record_tuples)
|
2018-02-09 07:35:38 +00:00
|
|
|
assert 'timerange' in config
|
2018-03-04 10:06:40 +00:00
|
|
|
assert log_has(
|
2018-02-09 07:35:38 +00:00
|
|
|
'Parameter --timerange detected: {} ...'.format(config['timerange']),
|
|
|
|
caplog.record_tuples
|
|
|
|
)
|
|
|
|
|
|
|
|
assert 'export' in config
|
2018-03-04 10:06:40 +00:00
|
|
|
assert log_has(
|
2018-02-09 07:35:38 +00:00
|
|
|
'Parameter --export detected: {} ...'.format(config['export']),
|
|
|
|
caplog.record_tuples
|
|
|
|
)
|
2018-06-03 12:52:03 +00:00
|
|
|
assert 'exportfilename' in config
|
|
|
|
assert log_has(
|
|
|
|
'Storing backtest results to {} ...'.format(config['exportfilename']),
|
|
|
|
caplog.record_tuples
|
|
|
|
)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
|
2018-06-03 22:48:26 +00:00
|
|
|
def test_setup_configuration_unlimited_stake_amount(mocker, default_conf, caplog) -> None:
|
2018-07-30 12:40:52 +00:00
|
|
|
default_conf['stake_amount'] = constants.UNLIMITED_STAKE_AMOUNT
|
2018-06-03 22:48:26 +00:00
|
|
|
|
|
|
|
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
2018-07-30 12:40:52 +00:00
|
|
|
read_data=json.dumps(default_conf)
|
2018-06-03 22:48:26 +00:00
|
|
|
))
|
|
|
|
|
|
|
|
args = [
|
|
|
|
'--config', 'config.json',
|
|
|
|
'--strategy', 'DefaultStrategy',
|
|
|
|
'backtesting'
|
|
|
|
]
|
|
|
|
|
|
|
|
with pytest.raises(DependencyException, match=r'.*stake amount.*'):
|
|
|
|
setup_configuration(get_args(args))
|
|
|
|
|
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_start(mocker, fee, default_conf, caplog) -> None:
|
2018-02-09 07:35:38 +00:00
|
|
|
start_mock = MagicMock()
|
2018-06-17 20:29:57 +00:00
|
|
|
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-02-09 07:35:38 +00:00
|
|
|
mocker.patch('freqtrade.optimize.backtesting.Backtesting.start', start_mock)
|
|
|
|
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
|
|
|
read_data=json.dumps(default_conf)
|
|
|
|
))
|
|
|
|
args = [
|
|
|
|
'--config', 'config.json',
|
2018-03-24 19:44:04 +00:00
|
|
|
'--strategy', 'DefaultStrategy',
|
2018-02-09 07:35:38 +00:00
|
|
|
'backtesting'
|
|
|
|
]
|
|
|
|
args = get_args(args)
|
|
|
|
start(args)
|
2018-03-04 10:06:40 +00:00
|
|
|
assert log_has(
|
2018-02-09 07:35:38 +00:00
|
|
|
'Starting freqtrade in Backtesting mode',
|
|
|
|
caplog.record_tuples
|
|
|
|
)
|
|
|
|
assert start_mock.call_count == 1
|
|
|
|
|
|
|
|
|
2019-03-06 18:55:34 +00:00
|
|
|
ORDER_TYPES = [
|
|
|
|
{
|
|
|
|
'buy': 'limit',
|
|
|
|
'sell': 'limit',
|
|
|
|
'stoploss': 'limit',
|
|
|
|
'stoploss_on_exchange': False
|
|
|
|
},
|
|
|
|
{
|
|
|
|
'buy': 'limit',
|
|
|
|
'sell': 'limit',
|
|
|
|
'stoploss': 'limit',
|
|
|
|
'stoploss_on_exchange': True
|
|
|
|
}]
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("order_types", ORDER_TYPES)
|
|
|
|
def test_backtesting_init(mocker, default_conf, order_types) -> None:
|
|
|
|
"""
|
|
|
|
Check that stoploss_on_exchange is set to False while backtesting
|
|
|
|
since backtesting assumes a perfect stoploss anyway.
|
|
|
|
"""
|
|
|
|
default_conf["order_types"] = order_types
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-06-22 18:55:09 +00:00
|
|
|
get_fee = mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.5))
|
2018-02-09 07:35:38 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
|
|
|
assert backtesting.config == default_conf
|
2018-03-25 20:03:26 +00:00
|
|
|
assert backtesting.ticker_interval == '5m'
|
2018-10-17 17:47:19 +00:00
|
|
|
assert callable(backtesting.strategy.tickerdata_to_dataframe)
|
2018-07-20 18:59:56 +00:00
|
|
|
assert callable(backtesting.advise_buy)
|
|
|
|
assert callable(backtesting.advise_sell)
|
2018-06-22 18:55:09 +00:00
|
|
|
get_fee.assert_called()
|
2018-06-23 04:58:25 +00:00
|
|
|
assert backtesting.fee == 0.5
|
2019-03-06 18:55:34 +00:00
|
|
|
assert not backtesting.strategy.order_types["stoploss_on_exchange"]
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
|
2018-12-31 18:15:05 +00:00
|
|
|
def test_tickerdata_to_dataframe_bt(default_conf, mocker) -> None:
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-06-05 21:53:49 +00:00
|
|
|
timerange = TimeRange(None, 'line', 0, -100)
|
2018-12-13 05:35:28 +00:00
|
|
|
tick = history.load_tickerdata_file(None, 'UNITTEST/BTC', '1m', timerange=timerange)
|
2018-12-31 18:15:05 +00:00
|
|
|
tickerlist = {'UNITTEST/BTC': parse_ticker_dataframe(tick, '1m', fill_missing=True)}
|
2018-03-02 13:46:32 +00:00
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
2018-10-17 17:47:19 +00:00
|
|
|
data = backtesting.strategy.tickerdata_to_dataframe(tickerlist)
|
2018-12-31 18:15:05 +00:00
|
|
|
assert len(data['UNITTEST/BTC']) == 102
|
2018-03-02 13:46:32 +00:00
|
|
|
|
2018-07-16 05:11:17 +00:00
|
|
|
# Load strategy to compare the result between Backtesting function and strategy are the same
|
|
|
|
strategy = DefaultStrategy(default_conf)
|
|
|
|
data2 = strategy.tickerdata_to_dataframe(tickerlist)
|
2018-02-03 16:15:40 +00:00
|
|
|
assert data['UNITTEST/BTC'].equals(data2['UNITTEST/BTC'])
|
2018-03-02 13:46:32 +00:00
|
|
|
|
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_generate_text_table(default_conf, mocker):
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2019-01-22 21:41:53 +00:00
|
|
|
default_conf['max_open_trades'] = 2
|
2018-04-21 22:19:11 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
results = pd.DataFrame(
|
|
|
|
{
|
2018-06-10 11:22:24 +00:00
|
|
|
'pair': ['ETH/BTC', 'ETH/BTC'],
|
2018-02-09 07:35:38 +00:00
|
|
|
'profit_percent': [0.1, 0.2],
|
2018-06-10 11:22:24 +00:00
|
|
|
'profit_abs': [0.2, 0.4],
|
|
|
|
'trade_duration': [10, 30],
|
2018-02-09 07:35:38 +00:00
|
|
|
'profit': [2, 0],
|
|
|
|
'loss': [0, 0]
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
result_str = (
|
2018-07-08 17:55:16 +00:00
|
|
|
'| pair | buy count | avg profit % | cum profit % | '
|
2019-01-22 21:41:53 +00:00
|
|
|
'tot profit BTC | tot profit % | avg duration | profit | loss |\n'
|
2018-07-08 17:55:16 +00:00
|
|
|
'|:--------|------------:|---------------:|---------------:|'
|
2019-01-22 21:41:53 +00:00
|
|
|
'-----------------:|---------------:|:---------------|---------:|-------:|\n'
|
|
|
|
'| ETH/BTC | 2 | 15.00 | 30.00 | '
|
|
|
|
'0.60000000 | 15.00 | 0:20:00 | 2 | 0 |\n'
|
|
|
|
'| TOTAL | 2 | 15.00 | 30.00 | '
|
|
|
|
'0.60000000 | 15.00 | 0:20:00 | 2 | 0 |'
|
2018-02-09 07:35:38 +00:00
|
|
|
)
|
2018-02-03 16:15:40 +00:00
|
|
|
assert backtesting._generate_text_table(data={'ETH/BTC': {}}, results=results) == result_str
|
2017-12-28 14:58:02 +00:00
|
|
|
|
2017-12-28 19:05:33 +00:00
|
|
|
|
2018-07-12 19:19:43 +00:00
|
|
|
def test_generate_text_table_sell_reason(default_conf, mocker):
|
|
|
|
patch_exchange(mocker)
|
|
|
|
backtesting = Backtesting(default_conf)
|
|
|
|
|
|
|
|
results = pd.DataFrame(
|
|
|
|
{
|
|
|
|
'pair': ['ETH/BTC', 'ETH/BTC', 'ETH/BTC'],
|
|
|
|
'profit_percent': [0.1, 0.2, 0.3],
|
|
|
|
'profit_abs': [0.2, 0.4, 0.5],
|
|
|
|
'trade_duration': [10, 30, 10],
|
|
|
|
'profit': [2, 0, 0],
|
|
|
|
'loss': [0, 0, 1],
|
|
|
|
'sell_reason': [SellType.ROI, SellType.ROI, SellType.STOP_LOSS]
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
result_str = (
|
|
|
|
'| Sell Reason | Count |\n'
|
|
|
|
'|:--------------|--------:|\n'
|
|
|
|
'| roi | 2 |\n'
|
|
|
|
'| stop_loss | 1 |'
|
|
|
|
)
|
|
|
|
assert backtesting._generate_text_table_sell_reason(
|
|
|
|
data={'ETH/BTC': {}}, results=results) == result_str
|
|
|
|
|
|
|
|
|
2018-07-29 11:07:30 +00:00
|
|
|
def test_generate_text_table_strategyn(default_conf, mocker):
|
|
|
|
"""
|
|
|
|
Test Backtesting.generate_text_table_sell_reason() method
|
|
|
|
"""
|
|
|
|
patch_exchange(mocker)
|
2019-01-22 21:41:53 +00:00
|
|
|
default_conf['max_open_trades'] = 2
|
2018-07-29 11:07:30 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
|
|
|
results = {}
|
|
|
|
results['ETH/BTC'] = pd.DataFrame(
|
|
|
|
{
|
|
|
|
'pair': ['ETH/BTC', 'ETH/BTC', 'ETH/BTC'],
|
|
|
|
'profit_percent': [0.1, 0.2, 0.3],
|
|
|
|
'profit_abs': [0.2, 0.4, 0.5],
|
|
|
|
'trade_duration': [10, 30, 10],
|
|
|
|
'profit': [2, 0, 0],
|
|
|
|
'loss': [0, 0, 1],
|
|
|
|
'sell_reason': [SellType.ROI, SellType.ROI, SellType.STOP_LOSS]
|
|
|
|
}
|
|
|
|
)
|
|
|
|
results['LTC/BTC'] = pd.DataFrame(
|
|
|
|
{
|
|
|
|
'pair': ['LTC/BTC', 'LTC/BTC', 'LTC/BTC'],
|
|
|
|
'profit_percent': [0.4, 0.2, 0.3],
|
|
|
|
'profit_abs': [0.4, 0.4, 0.5],
|
|
|
|
'trade_duration': [15, 30, 15],
|
|
|
|
'profit': [4, 1, 0],
|
|
|
|
'loss': [0, 0, 1],
|
|
|
|
'sell_reason': [SellType.ROI, SellType.ROI, SellType.STOP_LOSS]
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
result_str = (
|
|
|
|
'| Strategy | buy count | avg profit % | cum profit % '
|
2019-01-22 21:41:53 +00:00
|
|
|
'| tot profit BTC | tot profit % | avg duration | profit | loss |\n'
|
2018-07-29 11:07:30 +00:00
|
|
|
'|:-----------|------------:|---------------:|---------------:'
|
2019-01-22 21:41:53 +00:00
|
|
|
'|-----------------:|---------------:|:---------------|---------:|-------:|\n'
|
2018-07-29 11:07:30 +00:00
|
|
|
'| ETH/BTC | 3 | 20.00 | 60.00 '
|
2019-01-22 21:41:53 +00:00
|
|
|
'| 1.10000000 | 30.00 | 0:17:00 | 3 | 0 |\n'
|
2018-07-29 11:07:30 +00:00
|
|
|
'| LTC/BTC | 3 | 30.00 | 90.00 '
|
2019-01-22 21:41:53 +00:00
|
|
|
'| 1.30000000 | 45.00 | 0:20:00 | 3 | 0 |'
|
2018-07-29 11:07:30 +00:00
|
|
|
)
|
|
|
|
print(backtesting._generate_text_table_strategy(all_results=results))
|
|
|
|
assert backtesting._generate_text_table_strategy(all_results=results) == result_str
|
|
|
|
|
|
|
|
|
2018-02-09 07:35:38 +00:00
|
|
|
def test_backtesting_start(default_conf, mocker, caplog) -> None:
|
2018-10-17 17:59:33 +00:00
|
|
|
def get_timeframe(input1):
|
2018-03-02 13:46:32 +00:00
|
|
|
return Arrow(2017, 11, 14, 21, 17), Arrow(2017, 11, 14, 22, 59)
|
|
|
|
|
2018-12-13 05:35:28 +00:00
|
|
|
mocker.patch('freqtrade.data.history.load_data', mocked_load_data)
|
2018-10-17 17:59:33 +00:00
|
|
|
mocker.patch('freqtrade.optimize.get_timeframe', get_timeframe)
|
2018-12-29 12:13:07 +00:00
|
|
|
mocker.patch('freqtrade.exchange.Exchange.refresh_latest_ohlcv', MagicMock())
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-03-02 13:46:32 +00:00
|
|
|
mocker.patch.multiple(
|
|
|
|
'freqtrade.optimize.backtesting.Backtesting',
|
|
|
|
backtest=MagicMock(),
|
|
|
|
_generate_text_table=MagicMock(return_value='1'),
|
|
|
|
)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
2018-07-30 12:40:52 +00:00
|
|
|
default_conf['exchange']['pair_whitelist'] = ['UNITTEST/BTC']
|
2018-10-16 18:09:12 +00:00
|
|
|
default_conf['ticker_interval'] = '1m'
|
2018-07-30 12:40:52 +00:00
|
|
|
default_conf['live'] = False
|
|
|
|
default_conf['datadir'] = None
|
|
|
|
default_conf['export'] = None
|
|
|
|
default_conf['timerange'] = '-100'
|
2018-02-09 07:35:38 +00:00
|
|
|
|
2018-07-30 12:40:52 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
2018-02-09 07:35:38 +00:00
|
|
|
backtesting.start()
|
|
|
|
# check the logs, that will contain the backtest result
|
|
|
|
exists = [
|
|
|
|
'Using local backtesting data (using whitelist in given config) ...',
|
|
|
|
'Using stake_currency: BTC ...',
|
|
|
|
'Using stake_amount: 0.001 ...',
|
|
|
|
'Measuring data from 2017-11-14T21:17:00+00:00 '
|
|
|
|
'up to 2017-11-14T22:59:00+00:00 (0 days)..'
|
|
|
|
]
|
|
|
|
for line in exists:
|
2018-03-04 10:06:40 +00:00
|
|
|
assert log_has(line, caplog.record_tuples)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
|
2018-06-11 17:50:43 +00:00
|
|
|
def test_backtesting_start_no_data(default_conf, mocker, caplog) -> None:
|
2018-10-17 17:59:33 +00:00
|
|
|
def get_timeframe(input1):
|
2018-06-11 17:50:43 +00:00
|
|
|
return Arrow(2017, 11, 14, 21, 17), Arrow(2017, 11, 14, 22, 59)
|
|
|
|
|
2018-12-13 05:35:28 +00:00
|
|
|
mocker.patch('freqtrade.data.history.load_data', MagicMock(return_value={}))
|
2018-10-17 17:59:33 +00:00
|
|
|
mocker.patch('freqtrade.optimize.get_timeframe', get_timeframe)
|
2018-12-29 12:13:07 +00:00
|
|
|
mocker.patch('freqtrade.exchange.Exchange.refresh_latest_ohlcv', MagicMock())
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-06-11 17:50:43 +00:00
|
|
|
mocker.patch.multiple(
|
|
|
|
'freqtrade.optimize.backtesting.Backtesting',
|
|
|
|
backtest=MagicMock(),
|
|
|
|
_generate_text_table=MagicMock(return_value='1'),
|
|
|
|
)
|
|
|
|
|
2018-07-30 12:40:52 +00:00
|
|
|
default_conf['exchange']['pair_whitelist'] = ['UNITTEST/BTC']
|
|
|
|
default_conf['ticker_interval'] = "1m"
|
|
|
|
default_conf['live'] = False
|
|
|
|
default_conf['datadir'] = None
|
|
|
|
default_conf['export'] = None
|
|
|
|
default_conf['timerange'] = '20180101-20180102'
|
2018-06-11 17:50:43 +00:00
|
|
|
|
2018-07-30 12:40:52 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
2018-06-11 17:50:43 +00:00
|
|
|
backtesting.start()
|
|
|
|
# check the logs, that will contain the backtest result
|
2018-06-11 19:02:24 +00:00
|
|
|
|
|
|
|
assert log_has('No data found. Terminating.', caplog.record_tuples)
|
2018-06-11 17:50:43 +00:00
|
|
|
|
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_backtest(default_conf, fee, mocker) -> None:
|
2018-06-17 20:29:57 +00:00
|
|
|
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-04-21 22:19:11 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
2018-07-06 17:45:58 +00:00
|
|
|
pair = 'UNITTEST/BTC'
|
2018-12-15 14:34:25 +00:00
|
|
|
timerange = TimeRange(None, 'line', 0, -201)
|
2018-12-15 19:14:13 +00:00
|
|
|
data = history.load_data(datadir=None, ticker_interval='5m', pairs=['UNITTEST/BTC'],
|
2018-12-15 14:34:25 +00:00
|
|
|
timerange=timerange)
|
2018-10-17 17:47:19 +00:00
|
|
|
data_processed = backtesting.strategy.tickerdata_to_dataframe(data)
|
2018-11-04 12:23:59 +00:00
|
|
|
min_date, max_date = get_timeframe(data_processed)
|
2018-02-09 07:35:38 +00:00
|
|
|
results = backtesting.backtest(
|
|
|
|
{
|
|
|
|
'stake_amount': default_conf['stake_amount'],
|
2018-07-06 17:45:58 +00:00
|
|
|
'processed': data_processed,
|
2018-02-09 07:35:38 +00:00
|
|
|
'max_open_trades': 10,
|
2018-10-16 18:34:20 +00:00
|
|
|
'position_stacking': False,
|
|
|
|
'start_date': min_date,
|
|
|
|
'end_date': max_date,
|
2018-02-09 07:35:38 +00:00
|
|
|
}
|
|
|
|
)
|
2017-12-30 10:55:23 +00:00
|
|
|
assert not results.empty
|
2018-06-13 04:42:24 +00:00
|
|
|
assert len(results) == 2
|
2017-12-28 14:58:02 +00:00
|
|
|
|
2018-07-05 21:22:35 +00:00
|
|
|
expected = pd.DataFrame(
|
2018-07-06 17:45:58 +00:00
|
|
|
{'pair': [pair, pair],
|
2018-11-01 12:14:59 +00:00
|
|
|
'profit_percent': [0.0, 0.0],
|
|
|
|
'profit_abs': [0.0, 0.0],
|
2019-01-27 09:40:52 +00:00
|
|
|
'open_time': pd.to_datetime([Arrow(2018, 1, 29, 18, 40, 0).datetime,
|
|
|
|
Arrow(2018, 1, 30, 3, 30, 0).datetime], utc=True
|
|
|
|
),
|
|
|
|
'close_time': pd.to_datetime([Arrow(2018, 1, 29, 22, 35, 0).datetime,
|
|
|
|
Arrow(2018, 1, 30, 4, 10, 0).datetime], utc=True),
|
2018-12-15 14:34:25 +00:00
|
|
|
'open_index': [78, 184],
|
2019-01-12 12:45:43 +00:00
|
|
|
'close_index': [125, 192],
|
|
|
|
'trade_duration': [235, 40],
|
2018-07-05 21:22:35 +00:00
|
|
|
'open_at_end': [False, False],
|
2018-07-08 18:18:34 +00:00
|
|
|
'open_rate': [0.104445, 0.10302485],
|
2018-11-01 12:14:59 +00:00
|
|
|
'close_rate': [0.104969, 0.103541],
|
2018-07-11 18:03:40 +00:00
|
|
|
'sell_reason': [SellType.ROI, SellType.ROI]
|
|
|
|
})
|
2018-07-05 21:22:35 +00:00
|
|
|
pd.testing.assert_frame_equal(results, expected)
|
2018-07-06 17:45:58 +00:00
|
|
|
data_pair = data_processed[pair]
|
|
|
|
for _, t in results.iterrows():
|
|
|
|
ln = data_pair.loc[data_pair["date"] == t["open_time"]]
|
2018-07-08 18:18:34 +00:00
|
|
|
# Check open trade rate alignes to open rate
|
2018-07-06 17:45:58 +00:00
|
|
|
assert ln is not None
|
2018-07-08 18:18:34 +00:00
|
|
|
assert round(ln.iloc[0]["open"], 6) == round(t["open_rate"], 6)
|
2018-11-01 12:14:59 +00:00
|
|
|
# check close trade rate alignes to close rate or is between high and low
|
2018-07-06 17:45:58 +00:00
|
|
|
ln = data_pair.loc[data_pair["date"] == t["close_time"]]
|
2018-11-01 12:14:59 +00:00
|
|
|
assert (round(ln.iloc[0]["open"], 6) == round(t["close_rate"], 6) or
|
|
|
|
round(ln.iloc[0]["low"], 6) < round(
|
|
|
|
t["close_rate"], 6) < round(ln.iloc[0]["high"], 6))
|
2018-07-05 21:22:35 +00:00
|
|
|
|
2017-12-28 19:05:33 +00:00
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_backtest_1min_ticker_interval(default_conf, fee, mocker) -> None:
|
2018-06-17 20:29:57 +00:00
|
|
|
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-04-21 22:19:11 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
2018-12-15 14:34:25 +00:00
|
|
|
# Run a backtesting for an exiting 1min ticker_interval
|
|
|
|
timerange = TimeRange(None, 'line', 0, -200)
|
2018-12-15 19:14:13 +00:00
|
|
|
data = history.load_data(datadir=None, ticker_interval='1m', pairs=['UNITTEST/BTC'],
|
2018-12-15 14:34:25 +00:00
|
|
|
timerange=timerange)
|
2018-10-16 18:34:20 +00:00
|
|
|
processed = backtesting.strategy.tickerdata_to_dataframe(data)
|
2018-11-04 12:23:59 +00:00
|
|
|
min_date, max_date = get_timeframe(processed)
|
2018-02-09 07:35:38 +00:00
|
|
|
results = backtesting.backtest(
|
|
|
|
{
|
|
|
|
'stake_amount': default_conf['stake_amount'],
|
2018-10-16 18:34:20 +00:00
|
|
|
'processed': processed,
|
2018-02-09 07:35:38 +00:00
|
|
|
'max_open_trades': 1,
|
2018-10-16 18:34:20 +00:00
|
|
|
'position_stacking': False,
|
|
|
|
'start_date': min_date,
|
|
|
|
'end_date': max_date,
|
2018-02-09 07:35:38 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
assert not results.empty
|
2018-06-13 04:42:24 +00:00
|
|
|
assert len(results) == 1
|
2018-02-09 07:35:38 +00:00
|
|
|
|
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_processed(default_conf, mocker) -> None:
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-04-21 22:19:11 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
2018-02-09 07:35:38 +00:00
|
|
|
|
2017-12-30 10:55:23 +00:00
|
|
|
dict_of_tickerrows = load_data_test('raise')
|
2018-10-17 17:47:19 +00:00
|
|
|
dataframes = backtesting.strategy.tickerdata_to_dataframe(dict_of_tickerrows)
|
2018-02-03 16:15:40 +00:00
|
|
|
dataframe = dataframes['UNITTEST/BTC']
|
2017-12-30 10:55:23 +00:00
|
|
|
cols = dataframe.columns
|
|
|
|
# assert the dataframe got some of the indicator columns
|
|
|
|
for col in ['close', 'high', 'low', 'open', 'date',
|
|
|
|
'ema50', 'ao', 'macd', 'plus_dm']:
|
|
|
|
assert col in cols
|
2017-12-28 19:05:33 +00:00
|
|
|
|
2017-12-28 14:58:02 +00:00
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_backtest_pricecontours(default_conf, fee, mocker) -> None:
|
2018-06-17 20:29:57 +00:00
|
|
|
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
2018-12-31 18:15:05 +00:00
|
|
|
tests = [['raise', 19], ['lower', 0], ['sine', 18]]
|
2018-10-16 18:34:20 +00:00
|
|
|
# We need to enable sell-signal - otherwise it sells on ROI!!
|
|
|
|
default_conf['experimental'] = {"use_sell_signal": True}
|
|
|
|
|
2017-12-28 14:58:02 +00:00
|
|
|
for [contour, numres] in tests:
|
2018-04-21 22:19:11 +00:00
|
|
|
simple_backtest(default_conf, contour, numres, mocker)
|
2017-12-28 14:58:02 +00:00
|
|
|
|
2017-12-28 19:05:33 +00:00
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_backtest_clash_buy_sell(mocker, default_conf):
|
2018-02-08 19:49:43 +00:00
|
|
|
# Override the default buy trend function in our default_strategy
|
2018-06-26 05:08:09 +00:00
|
|
|
def fun(dataframe=None, pair=None):
|
2018-02-08 19:49:43 +00:00
|
|
|
buy_value = 1
|
|
|
|
sell_value = 1
|
|
|
|
return _trend(dataframe, buy_value, sell_value)
|
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
backtest_conf = _make_backtest_conf(mocker, conf=default_conf)
|
|
|
|
backtesting = Backtesting(default_conf)
|
2018-07-20 18:59:56 +00:00
|
|
|
backtesting.advise_buy = fun # Override
|
|
|
|
backtesting.advise_sell = fun # Override
|
2018-04-21 22:19:11 +00:00
|
|
|
results = backtesting.backtest(backtest_conf)
|
2018-02-08 19:49:43 +00:00
|
|
|
assert results.empty
|
|
|
|
|
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_backtest_only_sell(mocker, default_conf):
|
2018-02-08 19:49:43 +00:00
|
|
|
# Override the default buy trend function in our default_strategy
|
2018-06-26 05:08:09 +00:00
|
|
|
def fun(dataframe=None, pair=None):
|
2018-02-08 19:49:43 +00:00
|
|
|
buy_value = 0
|
|
|
|
sell_value = 1
|
|
|
|
return _trend(dataframe, buy_value, sell_value)
|
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
backtest_conf = _make_backtest_conf(mocker, conf=default_conf)
|
|
|
|
backtesting = Backtesting(default_conf)
|
2018-07-20 18:59:56 +00:00
|
|
|
backtesting.advise_buy = fun # Override
|
|
|
|
backtesting.advise_sell = fun # Override
|
2018-04-21 22:19:11 +00:00
|
|
|
results = backtesting.backtest(backtest_conf)
|
2018-02-08 19:49:43 +00:00
|
|
|
assert results.empty
|
|
|
|
|
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_backtest_alternate_buy_sell(default_conf, fee, mocker):
|
2018-06-17 20:29:57 +00:00
|
|
|
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
2018-11-15 19:02:48 +00:00
|
|
|
mocker.patch('freqtrade.optimize.backtesting.file_dump_json', MagicMock())
|
2018-04-21 22:19:11 +00:00
|
|
|
backtest_conf = _make_backtest_conf(mocker, conf=default_conf, pair='UNITTEST/BTC')
|
2018-10-16 18:35:08 +00:00
|
|
|
# We need to enable sell-signal - otherwise it sells on ROI!!
|
|
|
|
default_conf['experimental'] = {"use_sell_signal": True}
|
2018-10-17 04:54:07 +00:00
|
|
|
default_conf['ticker_interval'] = '1m'
|
2018-04-21 22:19:11 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
2018-07-20 18:59:56 +00:00
|
|
|
backtesting.advise_buy = _trend_alternate # Override
|
|
|
|
backtesting.advise_sell = _trend_alternate # Override
|
2018-04-21 22:19:11 +00:00
|
|
|
results = backtesting.backtest(backtest_conf)
|
2018-06-13 04:42:24 +00:00
|
|
|
backtesting._store_backtest_result("test_.json", results)
|
2018-10-17 04:54:07 +00:00
|
|
|
# 200 candles in backtest data
|
|
|
|
# won't buy on first (shifted by 1)
|
|
|
|
# 100 buys signals
|
2018-12-15 14:34:25 +00:00
|
|
|
assert len(results) == 100
|
2018-06-13 04:42:24 +00:00
|
|
|
# One trade was force-closed at the end
|
2018-10-16 18:35:08 +00:00
|
|
|
assert len(results.loc[results.open_at_end]) == 0
|
2018-02-08 19:49:43 +00:00
|
|
|
|
|
|
|
|
2018-11-05 19:03:04 +00:00
|
|
|
def test_backtest_multi_pair(default_conf, fee, mocker):
|
|
|
|
|
|
|
|
def _trend_alternate_hold(dataframe=None, metadata=None):
|
|
|
|
"""
|
|
|
|
Buy every 8th candle - sell every other 8th -2 (hold on to pairs a bit)
|
|
|
|
"""
|
|
|
|
multi = 8
|
|
|
|
dataframe['buy'] = np.where(dataframe.index % multi == 0, 1, 0)
|
|
|
|
dataframe['sell'] = np.where((dataframe.index + multi - 2) % multi == 0, 1, 0)
|
|
|
|
if metadata['pair'] in('ETH/BTC', 'LTC/BTC'):
|
|
|
|
dataframe['buy'] = dataframe['buy'].shift(-4)
|
|
|
|
dataframe['sell'] = dataframe['sell'].shift(-4)
|
|
|
|
return dataframe
|
|
|
|
|
|
|
|
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
2018-11-06 19:37:59 +00:00
|
|
|
patch_exchange(mocker)
|
2018-11-05 19:03:04 +00:00
|
|
|
pairs = ['ADA/BTC', 'DASH/BTC', 'ETH/BTC', 'LTC/BTC', 'NXT/BTC']
|
2018-12-15 19:14:13 +00:00
|
|
|
data = history.load_data(datadir=None, ticker_interval='5m', pairs=pairs)
|
2018-11-05 19:03:04 +00:00
|
|
|
data = trim_dictlist(data, -500)
|
|
|
|
# We need to enable sell-signal - otherwise it sells on ROI!!
|
|
|
|
default_conf['experimental'] = {"use_sell_signal": True}
|
|
|
|
default_conf['ticker_interval'] = '5m'
|
|
|
|
|
|
|
|
backtesting = Backtesting(default_conf)
|
|
|
|
backtesting.advise_buy = _trend_alternate_hold # Override
|
|
|
|
backtesting.advise_sell = _trend_alternate_hold # Override
|
|
|
|
|
|
|
|
data_processed = backtesting.strategy.tickerdata_to_dataframe(data)
|
|
|
|
min_date, max_date = get_timeframe(data_processed)
|
|
|
|
backtest_conf = {
|
|
|
|
'stake_amount': default_conf['stake_amount'],
|
|
|
|
'processed': data_processed,
|
|
|
|
'max_open_trades': 3,
|
|
|
|
'position_stacking': False,
|
|
|
|
'start_date': min_date,
|
|
|
|
'end_date': max_date,
|
|
|
|
}
|
|
|
|
|
|
|
|
results = backtesting.backtest(backtest_conf)
|
|
|
|
|
|
|
|
# Make sure we have parallel trades
|
|
|
|
assert len(evaluate_result_multi(results, '5min', 2)) > 0
|
|
|
|
# make sure we don't have trades with more than configured max_open_trades
|
|
|
|
assert len(evaluate_result_multi(results, '5min', 3)) == 0
|
|
|
|
|
|
|
|
backtest_conf = {
|
|
|
|
'stake_amount': default_conf['stake_amount'],
|
|
|
|
'processed': data_processed,
|
|
|
|
'max_open_trades': 1,
|
|
|
|
'position_stacking': False,
|
|
|
|
'start_date': min_date,
|
|
|
|
'end_date': max_date,
|
|
|
|
}
|
|
|
|
results = backtesting.backtest(backtest_conf)
|
|
|
|
assert len(evaluate_result_multi(results, '5min', 1)) == 0
|
|
|
|
|
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_backtest_record(default_conf, fee, mocker):
|
2018-02-08 19:49:43 +00:00
|
|
|
names = []
|
|
|
|
records = []
|
2018-06-17 20:32:56 +00:00
|
|
|
patch_exchange(mocker)
|
2018-06-17 20:29:57 +00:00
|
|
|
mocker.patch('freqtrade.exchange.Exchange.get_fee', fee)
|
2018-03-04 00:42:37 +00:00
|
|
|
mocker.patch(
|
|
|
|
'freqtrade.optimize.backtesting.file_dump_json',
|
|
|
|
new=lambda n, r: (names.append(n), records.append(r))
|
|
|
|
)
|
2018-06-13 04:31:42 +00:00
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
backtesting = Backtesting(default_conf)
|
2018-06-13 04:31:42 +00:00
|
|
|
results = pd.DataFrame({"pair": ["UNITTEST/BTC", "UNITTEST/BTC",
|
|
|
|
"UNITTEST/BTC", "UNITTEST/BTC"],
|
|
|
|
"profit_percent": [0.003312, 0.010801, 0.013803, 0.002780],
|
|
|
|
"profit_abs": [0.000003, 0.000011, 0.000014, 0.000003],
|
|
|
|
"open_time": [Arrow(2017, 11, 14, 19, 32, 00).datetime,
|
|
|
|
Arrow(2017, 11, 14, 21, 36, 00).datetime,
|
|
|
|
Arrow(2017, 11, 14, 22, 12, 00).datetime,
|
|
|
|
Arrow(2017, 11, 14, 22, 44, 00).datetime],
|
|
|
|
"close_time": [Arrow(2017, 11, 14, 21, 35, 00).datetime,
|
|
|
|
Arrow(2017, 11, 14, 22, 10, 00).datetime,
|
|
|
|
Arrow(2017, 11, 14, 22, 43, 00).datetime,
|
|
|
|
Arrow(2017, 11, 14, 22, 58, 00).datetime],
|
2018-06-23 12:19:50 +00:00
|
|
|
"open_rate": [0.002543, 0.003003, 0.003089, 0.003214],
|
|
|
|
"close_rate": [0.002546, 0.003014, 0.003103, 0.003217],
|
2018-06-13 04:31:42 +00:00
|
|
|
"open_index": [1, 119, 153, 185],
|
|
|
|
"close_index": [118, 151, 184, 199],
|
2018-06-23 12:19:50 +00:00
|
|
|
"trade_duration": [123, 34, 31, 14],
|
2018-07-11 18:32:56 +00:00
|
|
|
"open_at_end": [False, False, False, True],
|
|
|
|
"sell_reason": [SellType.ROI, SellType.STOP_LOSS,
|
|
|
|
SellType.ROI, SellType.FORCE_SELL]
|
2018-06-23 12:19:50 +00:00
|
|
|
})
|
2018-06-13 04:31:42 +00:00
|
|
|
backtesting._store_backtest_result("backtest-result.json", results)
|
2018-06-10 11:25:52 +00:00
|
|
|
assert len(results) == 4
|
2018-02-08 19:49:43 +00:00
|
|
|
# Assert file_dump_json was only called once
|
|
|
|
assert names == ['backtest-result.json']
|
|
|
|
records = records[0]
|
|
|
|
# Ensure records are of correct type
|
2018-06-10 11:25:52 +00:00
|
|
|
assert len(records) == 4
|
2018-07-28 20:00:12 +00:00
|
|
|
|
|
|
|
# reset test to test with strategy name
|
|
|
|
names = []
|
|
|
|
records = []
|
|
|
|
backtesting._store_backtest_result("backtest-result.json", results, "DefStrat")
|
|
|
|
assert len(results) == 4
|
|
|
|
# Assert file_dump_json was only called once
|
|
|
|
assert names == ['backtest-result-DefStrat.json']
|
|
|
|
records = records[0]
|
|
|
|
# Ensure records are of correct type
|
|
|
|
assert len(records) == 4
|
|
|
|
|
2018-02-03 16:15:40 +00:00
|
|
|
# ('UNITTEST/BTC', 0.00331158, '1510684320', '1510691700', 0, 117)
|
2018-02-08 19:49:43 +00:00
|
|
|
# Below follows just a typecheck of the schema/type of trade-records
|
|
|
|
oix = None
|
2018-06-23 12:19:50 +00:00
|
|
|
for (pair, profit, date_buy, date_sell, buy_index, dur,
|
2018-07-11 18:32:56 +00:00
|
|
|
openr, closer, open_at_end, sell_reason) in records:
|
2018-02-03 16:15:40 +00:00
|
|
|
assert pair == 'UNITTEST/BTC'
|
2018-06-23 12:19:50 +00:00
|
|
|
assert isinstance(profit, float)
|
2018-02-08 19:49:43 +00:00
|
|
|
# FIX: buy/sell should be converted to ints
|
2018-06-23 12:19:50 +00:00
|
|
|
assert isinstance(date_buy, float)
|
|
|
|
assert isinstance(date_sell, float)
|
|
|
|
assert isinstance(openr, float)
|
|
|
|
assert isinstance(closer, float)
|
|
|
|
assert isinstance(open_at_end, bool)
|
2018-07-11 18:32:56 +00:00
|
|
|
assert isinstance(sell_reason, str)
|
2018-02-08 19:49:43 +00:00
|
|
|
isinstance(buy_index, pd._libs.tslib.Timestamp)
|
|
|
|
if oix:
|
|
|
|
assert buy_index > oix
|
|
|
|
oix = buy_index
|
|
|
|
assert dur > 0
|
2017-12-28 14:58:02 +00:00
|
|
|
|
2017-12-28 19:05:33 +00:00
|
|
|
|
2018-04-21 22:19:11 +00:00
|
|
|
def test_backtest_start_live(default_conf, mocker, caplog):
|
2018-07-30 12:40:52 +00:00
|
|
|
default_conf['exchange']['pair_whitelist'] = ['UNITTEST/BTC']
|
2018-08-19 17:39:22 +00:00
|
|
|
|
|
|
|
async def load_pairs(pair, timeframe, since):
|
|
|
|
return _load_pair_as_ticks(pair, timeframe)
|
|
|
|
|
|
|
|
api_mock = MagicMock()
|
|
|
|
api_mock.fetch_ohlcv = load_pairs
|
|
|
|
|
|
|
|
patch_exchange(mocker, api_mock)
|
2018-03-04 00:42:37 +00:00
|
|
|
mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest', MagicMock())
|
|
|
|
mocker.patch('freqtrade.optimize.backtesting.Backtesting._generate_text_table', MagicMock())
|
|
|
|
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
2018-07-30 12:40:52 +00:00
|
|
|
read_data=json.dumps(default_conf)
|
2018-03-04 00:42:37 +00:00
|
|
|
))
|
|
|
|
|
|
|
|
args = [
|
|
|
|
'--config', 'config.json',
|
2018-03-24 19:44:04 +00:00
|
|
|
'--strategy', 'DefaultStrategy',
|
2018-06-10 17:46:52 +00:00
|
|
|
'--datadir', 'freqtrade/tests/testdata',
|
2018-03-04 00:42:37 +00:00
|
|
|
'backtesting',
|
2018-03-25 20:03:26 +00:00
|
|
|
'--ticker-interval', '1m',
|
2018-03-04 00:42:37 +00:00
|
|
|
'--live',
|
2018-06-10 17:46:52 +00:00
|
|
|
'--timerange', '-100',
|
2018-07-17 19:05:03 +00:00
|
|
|
'--enable-position-stacking',
|
|
|
|
'--disable-max-market-positions'
|
2018-03-04 00:42:37 +00:00
|
|
|
]
|
|
|
|
args = get_args(args)
|
|
|
|
start(args)
|
2018-02-08 19:49:43 +00:00
|
|
|
# check the logs, that will contain the backtest result
|
2018-03-04 00:42:37 +00:00
|
|
|
exists = [
|
|
|
|
'Parameter -i/--ticker-interval detected ...',
|
2018-03-25 20:03:26 +00:00
|
|
|
'Using ticker_interval: 1m ...',
|
2018-03-04 00:42:37 +00:00
|
|
|
'Parameter -l/--live detected ...',
|
2018-07-17 19:05:03 +00:00
|
|
|
'Ignoring max_open_trades (--disable-max-market-positions was used) ...',
|
2018-06-10 17:46:52 +00:00
|
|
|
'Parameter --timerange detected: -100 ...',
|
2018-06-02 08:32:05 +00:00
|
|
|
'Using data folder: freqtrade/tests/testdata ...',
|
2018-03-04 00:42:37 +00:00
|
|
|
'Using stake_currency: BTC ...',
|
|
|
|
'Using stake_amount: 0.001 ...',
|
|
|
|
'Downloading data for all pairs in whitelist ...',
|
2018-12-15 14:34:25 +00:00
|
|
|
'Measuring data from 2017-11-14T19:31:00+00:00 up to 2017-11-14T22:58:00+00:00 (0 days)..',
|
2018-07-17 18:26:59 +00:00
|
|
|
'Parameter --enable-position-stacking detected ...'
|
2018-03-04 00:42:37 +00:00
|
|
|
]
|
|
|
|
|
2018-02-08 19:49:43 +00:00
|
|
|
for line in exists:
|
2018-06-10 17:46:52 +00:00
|
|
|
assert log_has(line, caplog.record_tuples)
|
2018-07-28 05:55:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_backtest_start_multi_strat(default_conf, mocker, caplog):
|
2018-07-31 19:08:03 +00:00
|
|
|
default_conf['exchange']['pair_whitelist'] = ['UNITTEST/BTC']
|
2018-08-19 17:39:22 +00:00
|
|
|
|
|
|
|
async def load_pairs(pair, timeframe, since):
|
|
|
|
return _load_pair_as_ticks(pair, timeframe)
|
|
|
|
api_mock = MagicMock()
|
|
|
|
api_mock.fetch_ohlcv = load_pairs
|
|
|
|
|
|
|
|
patch_exchange(mocker, api_mock)
|
2018-07-28 05:55:59 +00:00
|
|
|
backtestmock = MagicMock()
|
|
|
|
mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest', backtestmock)
|
|
|
|
gen_table_mock = MagicMock()
|
|
|
|
mocker.patch('freqtrade.optimize.backtesting.Backtesting._generate_text_table', gen_table_mock)
|
2018-07-29 11:07:30 +00:00
|
|
|
gen_strattable_mock = MagicMock()
|
|
|
|
mocker.patch('freqtrade.optimize.backtesting.Backtesting._generate_text_table_strategy',
|
|
|
|
gen_strattable_mock)
|
2018-07-28 05:55:59 +00:00
|
|
|
mocker.patch('freqtrade.configuration.open', mocker.mock_open(
|
2018-07-31 19:08:03 +00:00
|
|
|
read_data=json.dumps(default_conf)
|
2018-07-28 05:55:59 +00:00
|
|
|
))
|
|
|
|
|
|
|
|
args = [
|
|
|
|
'--config', 'config.json',
|
|
|
|
'--datadir', 'freqtrade/tests/testdata',
|
|
|
|
'backtesting',
|
|
|
|
'--ticker-interval', '1m',
|
|
|
|
'--live',
|
|
|
|
'--timerange', '-100',
|
|
|
|
'--enable-position-stacking',
|
|
|
|
'--disable-max-market-positions',
|
|
|
|
'--strategy-list',
|
|
|
|
'DefaultStrategy',
|
|
|
|
'TestStrategy',
|
|
|
|
]
|
|
|
|
args = get_args(args)
|
|
|
|
start(args)
|
|
|
|
# 2 backtests, 4 tables
|
|
|
|
assert backtestmock.call_count == 2
|
|
|
|
assert gen_table_mock.call_count == 4
|
2018-07-29 11:07:30 +00:00
|
|
|
assert gen_strattable_mock.call_count == 1
|
2018-07-28 05:55:59 +00:00
|
|
|
|
|
|
|
# check the logs, that will contain the backtest result
|
|
|
|
exists = [
|
|
|
|
'Parameter -i/--ticker-interval detected ...',
|
|
|
|
'Using ticker_interval: 1m ...',
|
|
|
|
'Parameter -l/--live detected ...',
|
|
|
|
'Ignoring max_open_trades (--disable-max-market-positions was used) ...',
|
|
|
|
'Parameter --timerange detected: -100 ...',
|
|
|
|
'Using data folder: freqtrade/tests/testdata ...',
|
|
|
|
'Using stake_currency: BTC ...',
|
|
|
|
'Using stake_amount: 0.001 ...',
|
|
|
|
'Downloading data for all pairs in whitelist ...',
|
2018-12-15 14:34:25 +00:00
|
|
|
'Measuring data from 2017-11-14T19:31:00+00:00 up to 2017-11-14T22:58:00+00:00 (0 days)..',
|
2018-07-28 05:55:59 +00:00
|
|
|
'Parameter --enable-position-stacking detected ...',
|
|
|
|
'Running backtesting for Strategy DefaultStrategy',
|
|
|
|
'Running backtesting for Strategy TestStrategy',
|
|
|
|
]
|
|
|
|
|
|
|
|
for line in exists:
|
|
|
|
assert log_has(line, caplog.record_tuples)
|