| 1 | # pragma pylint: disable=missing-docstring, W0212, line-too-long, C0103, unused-argument |
| 2 | |
| 3 | import random |
| 4 | from pathlib import Path |
| 5 | from unittest.mock import MagicMock, PropertyMock |
| 6 | |
| 7 | import numpy as np |
| 8 | import pandas as pd |
| 9 | import pytest |
| 10 | from arrow import Arrow |
| 11 | |
| 12 | from freqtrade.commands.optimize_commands import setup_optimize_configuration, start_backtesting |
| 13 | from freqtrade.configuration import TimeRange |
| 14 | from freqtrade.data import history |
| 15 | from freqtrade.data.btanalysis import BT_DATA_COLUMNS, evaluate_result_multi |
| 16 | from freqtrade.data.converter import clean_ohlcv_dataframe |
| 17 | from freqtrade.data.dataprovider import DataProvider |
| 18 | from freqtrade.data.history import get_timerange |
| 19 | from freqtrade.exceptions import DependencyException, OperationalException |
| 20 | from freqtrade.optimize.backtesting import Backtesting |
| 21 | from freqtrade.persistence import LocalTrade |
| 22 | from freqtrade.resolvers import StrategyResolver |
| 23 | from freqtrade.state import RunMode |
| 24 | from freqtrade.strategy.interface import SellType |
| 25 | from tests.conftest import (get_args, log_has, log_has_re, patch_exchange, |
| 26 | patched_configuration_load_config_file) |
| 27 | |
| 28 | |
| 29 | ORDER_TYPES = [ |
| 30 | { |
| 31 | 'buy': 'limit', |
| 32 | 'sell': 'limit', |
| 33 | 'stoploss': 'limit', |
| 34 | 'stoploss_on_exchange': False |
| 35 | }, |
| 36 | { |
| 37 | 'buy': 'limit', |
| 38 | 'sell': 'limit', |
| 39 | 'stoploss': 'limit', |
| 40 | 'stoploss_on_exchange': True |
| 41 | }] |
| 42 | |
| 43 | |
| 44 | def trim_dictlist(dict_list, num): |
| 45 | new = {} |
| 46 | for pair, pair_data in dict_list.items(): |
| 47 | new[pair] = pair_data[num:].reset_index() |
| 48 | return new |
| 49 | |
| 50 | |
| 51 | def load_data_test(what, testdatadir): |
| 52 | timerange = TimeRange.parse_timerange('1510694220-1510700340') |
| 53 | data = history.load_pair_history(pair='UNITTEST/BTC', datadir=testdatadir, |
| 54 | timeframe='1m', timerange=timerange, |
| 55 | drop_incomplete=False, |
| 56 | fill_up_missing=False) |
| 57 | |
| 58 | base = 0.001 |
| 59 | if what == 'raise': |
| 60 | data.loc[:, 'open'] = data.index * base |
| 61 | data.loc[:, 'high'] = data.index * base + 0.0001 |
| 62 | data.loc[:, 'low'] = data.index * base - 0.0001 |
| 63 | data.loc[:, 'close'] = data.index * base |
| 64 | |
| 65 | if what == 'lower': |
| 66 | data.loc[:, 'open'] = 1 - data.index * base |
| 67 | data.loc[:, 'high'] = 1 - data.index * base + 0.0001 |
| 68 | data.loc[:, 'low'] = 1 - data.index * base - 0.0001 |
| 69 | data.loc[:, 'close'] = 1 - data.index * base |
| 70 | |
| 71 | if what == 'sine': |
| 72 | hz = 0.1 # frequency |
| 73 | data.loc[:, 'open'] = np.sin(data.index * hz) / 1000 + base |
| 74 | data.loc[:, 'high'] = np.sin(data.index * hz) / 1000 + base + 0.0001 |
| 75 | data.loc[:, 'low'] = np.sin(data.index * hz) / 1000 + base - 0.0001 |
| 76 | data.loc[:, 'close'] = np.sin(data.index * hz) / 1000 + base |
| 77 | |
| 78 | return {'UNITTEST/BTC': clean_ohlcv_dataframe(data, timeframe='1m', pair='UNITTEST/BTC', |
| 79 | fill_missing=True)} |
| 80 | |
| 81 | |
| 82 | def simple_backtest(config, contour, mocker, testdatadir) -> None: |
| 83 | patch_exchange(mocker) |
| 84 | config['timeframe'] = '1m' |
| 85 | backtesting = Backtesting(config) |
| 86 | |
| 87 | data = load_data_test(contour, testdatadir) |
| 88 | processed = backtesting.strategy.ohlcvdata_to_dataframe(data) |
| 89 | min_date, max_date = get_timerange(processed) |
| 90 | assert isinstance(processed, dict) |
| 91 | results = backtesting.backtest( |
| 92 | processed=processed, |
| 93 | start_date=min_date, |
| 94 | end_date=max_date, |
| 95 | max_open_trades=1, |
| 96 | position_stacking=False, |
| 97 | enable_protections=config.get('enable_protections', False), |
| 98 | ) |
| 99 | # results :: <class 'pandas.core.frame.DataFrame'> |
| 100 | return results |
| 101 | |
| 102 | |
| 103 | # FIX: fixturize this? |
| 104 | def _make_backtest_conf(mocker, datadir, conf=None, pair='UNITTEST/BTC'): |
| 105 | data = history.load_data(datadir=datadir, timeframe='1m', pairs=[pair]) |
| 106 | data = trim_dictlist(data, -201) |
| 107 | patch_exchange(mocker) |
| 108 | backtesting = Backtesting(conf) |
| 109 | processed = backtesting.strategy.ohlcvdata_to_dataframe(data) |
| 110 | min_date, max_date = get_timerange(processed) |
| 111 | return { |
| 112 | 'processed': processed, |
| 113 | 'start_date': min_date, |
| 114 | 'end_date': max_date, |
| 115 | 'max_open_trades': 10, |
| 116 | 'position_stacking': False, |
| 117 | } |
| 118 | |
| 119 | |
| 120 | def _trend(signals, buy_value, sell_value): |
| 121 | n = len(signals['low']) |
| 122 | buy = np.zeros(n) |
| 123 | sell = np.zeros(n) |
| 124 | for i in range(0, len(signals['buy'])): |
| 125 | if random.random() > 0.5: # Both buy and sell signals at same timeframe |
| 126 | buy[i] = buy_value |
| 127 | sell[i] = sell_value |
| 128 | signals['buy'] = buy |
| 129 | signals['sell'] = sell |
| 130 | return signals |
| 131 | |
| 132 | |
| 133 | def _trend_alternate(dataframe=None, metadata=None): |
| 134 | signals = dataframe |
| 135 | low = signals['low'] |
| 136 | n = len(low) |
| 137 | buy = np.zeros(n) |
| 138 | sell = np.zeros(n) |
| 139 | for i in range(0, len(buy)): |
| 140 | if i % 2 == 0: |
| 141 | buy[i] = 1 |
| 142 | else: |
| 143 | sell[i] = 1 |
| 144 | signals['buy'] = buy |
| 145 | signals['sell'] = sell |
| 146 | return dataframe |
| 147 | |
| 148 | |
| 149 | # Unit tests |
| 150 | def test_setup_optimize_configuration_without_arguments(mocker, default_conf, caplog) -> None: |
| 151 | patched_configuration_load_config_file(mocker, default_conf) |
| 152 | |
| 153 | args = [ |
| 154 | 'backtesting', |
| 155 | '--config', 'config.json', |
| 156 | '--strategy', 'DefaultStrategy', |
| 157 | ] |
| 158 | |
| 159 | config = setup_optimize_configuration(get_args(args), RunMode.BACKTEST) |
| 160 | assert 'max_open_trades' in config |
| 161 | assert 'stake_currency' in config |
| 162 | assert 'stake_amount' in config |
| 163 | assert 'exchange' in config |
| 164 | assert 'pair_whitelist' in config['exchange'] |
| 165 | assert 'datadir' in config |
| 166 | assert log_has('Using data directory: {} ...'.format(config['datadir']), caplog) |
| 167 | assert 'timeframe' in config |
| 168 | assert not log_has_re('Parameter -i/--ticker-interval detected .*', caplog) |
| 169 | |
| 170 | assert 'position_stacking' not in config |
| 171 | assert not log_has('Parameter --enable-position-stacking detected ...', caplog) |
| 172 | |
| 173 | assert 'timerange' not in config |
| 174 | assert 'export' not in config |
| 175 | assert 'runmode' in config |
| 176 | assert config['runmode'] == RunMode.BACKTEST |
| 177 | |
| 178 | |
| 179 | def test_setup_bt_configuration_with_arguments(mocker, default_conf, caplog) -> None: |
| 180 | patched_configuration_load_config_file(mocker, default_conf) |
| 181 | mocker.patch( |
| 182 | 'freqtrade.configuration.configuration.create_datadir', |
| 183 | lambda c, x: x |
| 184 | ) |
| 185 | |
| 186 | args = [ |
| 187 | 'backtesting', |
| 188 | '--config', 'config.json', |
| 189 | '--strategy', 'DefaultStrategy', |
| 190 | '--datadir', '/foo/bar', |
| 191 | '--timeframe', '1m', |
| 192 | '--enable-position-stacking', |
| 193 | '--disable-max-market-positions', |
| 194 | '--timerange', ':100', |
| 195 | '--export', '/bar/foo', |
| 196 | '--export-filename', 'foo_bar.json', |
| 197 | '--fee', '0', |
| 198 | ] |
| 199 | |
| 200 | config = setup_optimize_configuration(get_args(args), RunMode.BACKTEST) |
| 201 | assert 'max_open_trades' in config |
| 202 | assert 'stake_currency' in config |
| 203 | assert 'stake_amount' in config |
| 204 | assert 'exchange' in config |
| 205 | assert 'pair_whitelist' in config['exchange'] |
| 206 | assert 'datadir' in config |
| 207 | assert config['runmode'] == RunMode.BACKTEST |
| 208 | |
| 209 | assert log_has('Using data directory: {} ...'.format(config['datadir']), caplog) |
| 210 | assert 'timeframe' in config |
| 211 | assert log_has('Parameter -i/--timeframe detected ... Using timeframe: 1m ...', |
| 212 | caplog) |
| 213 | |
| 214 | assert 'position_stacking' in config |
| 215 | assert log_has('Parameter --enable-position-stacking detected ...', caplog) |
| 216 | |
| 217 | assert 'use_max_market_positions' in config |
| 218 | assert log_has('Parameter --disable-max-market-positions detected ...', caplog) |
| 219 | assert log_has('max_open_trades set to unlimited ...', caplog) |
| 220 | |
| 221 | assert 'timerange' in config |
| 222 | assert log_has('Parameter --timerange detected: {} ...'.format(config['timerange']), caplog) |
| 223 | |
| 224 | assert 'export' in config |
| 225 | assert log_has('Parameter --export detected: {} ...'.format(config['export']), caplog) |
| 226 | assert 'exportfilename' in config |
| 227 | assert isinstance(config['exportfilename'], Path) |
| 228 | assert log_has('Storing backtest results to {} ...'.format(config['exportfilename']), caplog) |
| 229 | |
| 230 | assert 'fee' in config |
| 231 | assert log_has('Parameter --fee detected, setting fee to: {} ...'.format(config['fee']), caplog) |
| 232 | |
| 233 | |
| 234 | def test_setup_optimize_configuration_stake_amount(mocker, default_conf, caplog) -> None: |
| 235 | |
| 236 | patched_configuration_load_config_file(mocker, default_conf) |
| 237 | |
| 238 | args = [ |
| 239 | 'backtesting', |
| 240 | '--config', 'config.json', |
| 241 | '--strategy', 'DefaultStrategy', |
| 242 | '--stake-amount', '1', |
| 243 | '--starting-balance', '2' |
| 244 | ] |
| 245 | |
| 246 | conf = setup_optimize_configuration(get_args(args), RunMode.BACKTEST) |
| 247 | assert isinstance(conf, dict) |
| 248 | |
| 249 | args = [ |
| 250 | 'backtesting', |
| 251 | '--config', 'config.json', |
| 252 | '--strategy', 'DefaultStrategy', |
| 253 | '--stake-amount', '1', |
| 254 | '--starting-balance', '0.5' |
| 255 | ] |
| 256 | with pytest.raises(OperationalException, match=r"Starting balance .* smaller .*"): |
| 257 | setup_optimize_configuration(get_args(args), RunMode.BACKTEST) |
| 258 | |
| 259 | |
| 260 | def test_start(mocker, fee, default_conf, caplog) -> None: |
| 261 | start_mock = MagicMock() |
| 262 | mocker.patch('freqtrade.exchange.Exchange.get_fee', fee) |
| 263 | patch_exchange(mocker) |
| 264 | mocker.patch('freqtrade.optimize.backtesting.Backtesting.start', start_mock) |
| 265 | patched_configuration_load_config_file(mocker, default_conf) |
| 266 | |
| 267 | args = [ |
| 268 | 'backtesting', |
| 269 | '--config', 'config.json', |
| 270 | '--strategy', 'DefaultStrategy', |
| 271 | ] |
| 272 | pargs = get_args(args) |
| 273 | start_backtesting(pargs) |
| 274 | assert log_has('Starting freqtrade in Backtesting mode', caplog) |
| 275 | assert start_mock.call_count == 1 |
| 276 | |
| 277 | |
| 278 | @pytest.mark.parametrize("order_types", ORDER_TYPES) |
| 279 | def test_backtesting_init(mocker, default_conf, order_types) -> None: |
| 280 | """ |
| 281 | Check that stoploss_on_exchange is set to False while backtesting |
| 282 | since backtesting assumes a perfect stoploss anyway. |
| 283 | """ |
| 284 | default_conf["order_types"] = order_types |
| 285 | patch_exchange(mocker) |
| 286 | get_fee = mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.5)) |
| 287 | backtesting = Backtesting(default_conf) |
| 288 | assert backtesting.config == default_conf |
| 289 | assert backtesting.timeframe == '5m' |
| 290 | assert callable(backtesting.strategy.ohlcvdata_to_dataframe) |
| 291 | assert callable(backtesting.strategy.advise_buy) |
| 292 | assert callable(backtesting.strategy.advise_sell) |
| 293 | assert isinstance(backtesting.strategy.dp, DataProvider) |
| 294 | get_fee.assert_called() |
| 295 | assert backtesting.fee == 0.5 |
| 296 | assert not backtesting.strategy.order_types["stoploss_on_exchange"] |
| 297 | |
| 298 | |
| 299 | def test_backtesting_init_no_timeframe(mocker, default_conf, caplog) -> None: |
| 300 | patch_exchange(mocker) |
| 301 | del default_conf['timeframe'] |
| 302 | default_conf['strategy_list'] = ['DefaultStrategy', |
| 303 | 'SampleStrategy'] |
| 304 | |
| 305 | mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.5)) |
| 306 | with pytest.raises(OperationalException): |
| 307 | Backtesting(default_conf) |
| 308 | log_has("Ticker-interval needs to be set in either configuration " |
| 309 | "or as cli argument `--ticker-interval 5m`", caplog) |
| 310 | |
| 311 | |
| 312 | def test_data_with_fee(default_conf, mocker, testdatadir) -> None: |
| 313 | patch_exchange(mocker) |
| 314 | default_conf['fee'] = 0.1234 |
| 315 | |
| 316 | fee_mock = mocker.patch('freqtrade.exchange.Exchange.get_fee', MagicMock(return_value=0.5)) |
| 317 | backtesting = Backtesting(default_conf) |
| 318 | assert backtesting.fee == 0.1234 |
| 319 | assert fee_mock.call_count == 0 |
| 320 | |
| 321 | default_conf['fee'] = 0.0 |
| 322 | backtesting = Backtesting(default_conf) |
| 323 | assert backtesting.fee == 0.0 |
| 324 | assert fee_mock.call_count == 0 |
| 325 | |
| 326 | |
| 327 | def test_data_to_dataframe_bt(default_conf, mocker, testdatadir) -> None: |
| 328 | patch_exchange(mocker) |
| 329 | timerange = TimeRange.parse_timerange('1510694220-1510700340') |
| 330 | data = history.load_data(testdatadir, '1m', ['UNITTEST/BTC'], timerange=timerange, |
| 331 | fill_up_missing=True) |
| 332 | backtesting = Backtesting(default_conf) |
| 333 | processed = backtesting.strategy.ohlcvdata_to_dataframe(data) |
| 334 | assert len(processed['UNITTEST/BTC']) == 102 |
| 335 | |
| 336 | # Load strategy to compare the result between Backtesting function and strategy are the same |
| 337 | default_conf.update({'strategy': 'DefaultStrategy'}) |
| 338 | strategy = StrategyResolver.load_strategy(default_conf) |
| 339 | |
| 340 | processed2 = strategy.ohlcvdata_to_dataframe(data) |
| 341 | assert processed['UNITTEST/BTC'].equals(processed2['UNITTEST/BTC']) |
| 342 | |
| 343 | |
| 344 | def test_backtesting_start(default_conf, mocker, testdatadir, caplog) -> None: |
| 345 | def get_timerange(input1): |
| 346 | return Arrow(2017, 11, 14, 21, 17), Arrow(2017, 11, 14, 22, 59) |
| 347 | |
| 348 | mocker.patch('freqtrade.data.history.get_timerange', get_timerange) |
| 349 | patch_exchange(mocker) |
| 350 | mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest') |
| 351 | mocker.patch('freqtrade.optimize.backtesting.generate_backtest_stats') |
| 352 | mocker.patch('freqtrade.optimize.backtesting.show_backtest_results') |
| 353 | sbs = mocker.patch('freqtrade.optimize.backtesting.store_backtest_stats') |
| 354 | mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist', |
| 355 | PropertyMock(return_value=['UNITTEST/BTC'])) |
| 356 | |
| 357 | default_conf['timeframe'] = '1m' |
| 358 | default_conf['datadir'] = testdatadir |
| 359 | default_conf['export'] = 'trades' |
| 360 | default_conf['exportfilename'] = 'export.txt' |
| 361 | default_conf['timerange'] = '-1510694220' |
| 362 | |
| 363 | backtesting = Backtesting(default_conf) |
| 364 | backtesting.strategy.bot_loop_start = MagicMock() |
| 365 | backtesting.start() |
| 366 | # check the logs, that will contain the backtest result |
| 367 | exists = [ |
| 368 | 'Backtesting with data from 2017-11-14 21:17:00 ' |
| 369 | 'up to 2017-11-14 22:59:00 (0 days)..' |
| 370 | ] |
| 371 | for line in exists: |
| 372 | assert log_has(line, caplog) |
| 373 | assert backtesting.strategy.dp._pairlists is not None |
| 374 | assert backtesting.strategy.bot_loop_start.call_count == 1 |
| 375 | assert sbs.call_count == 1 |
| 376 | |
| 377 | |
| 378 | def test_backtesting_start_no_data(default_conf, mocker, caplog, testdatadir) -> None: |
| 379 | def get_timerange(input1): |
| 380 | return Arrow(2017, 11, 14, 21, 17), Arrow(2017, 11, 14, 22, 59) |
| 381 | |
| 382 | mocker.patch('freqtrade.data.history.history_utils.load_pair_history', |
| 383 | MagicMock(return_value=pd.DataFrame())) |
| 384 | mocker.patch('freqtrade.data.history.get_timerange', get_timerange) |
| 385 | patch_exchange(mocker) |
| 386 | mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest') |
| 387 | mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist', |
| 388 | PropertyMock(return_value=['UNITTEST/BTC'])) |
| 389 | |
| 390 | default_conf['timeframe'] = "1m" |
| 391 | default_conf['datadir'] = testdatadir |
| 392 | default_conf['export'] = None |
| 393 | default_conf['timerange'] = '20180101-20180102' |
| 394 | |
| 395 | backtesting = Backtesting(default_conf) |
| 396 | with pytest.raises(OperationalException, match='No data found. Terminating.'): |
| 397 | backtesting.start() |
| 398 | |
| 399 | |
| 400 | def test_backtesting_no_pair_left(default_conf, mocker, caplog, testdatadir) -> None: |
| 401 | mocker.patch('freqtrade.exchange.Exchange.exchange_has', MagicMock(return_value=True)) |
| 402 | mocker.patch('freqtrade.data.history.history_utils.load_pair_history', |
| 403 | MagicMock(return_value=pd.DataFrame())) |
| 404 | mocker.patch('freqtrade.data.history.get_timerange', get_timerange) |
| 405 | patch_exchange(mocker) |
| 406 | mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest') |
| 407 | mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist', |
| 408 | PropertyMock(return_value=[])) |
| 409 | |
| 410 | default_conf['timeframe'] = "1m" |
| 411 | default_conf['datadir'] = testdatadir |
| 412 | default_conf['export'] = None |
| 413 | default_conf['timerange'] = '20180101-20180102' |
| 414 | |
| 415 | with pytest.raises(OperationalException, match='No pair in whitelist.'): |
| 416 | Backtesting(default_conf) |
| 417 | |
| 418 | default_conf['pairlists'] = [{"method": "VolumePairList", "number_assets": 5}] |
| 419 | with pytest.raises(OperationalException, match='VolumePairList not allowed for backtesting.'): |
| 420 | Backtesting(default_conf) |
| 421 | |
| 422 | |
| 423 | def test_backtesting_pairlist_list(default_conf, mocker, caplog, testdatadir, tickers) -> None: |
| 424 | mocker.patch('freqtrade.exchange.Exchange.exchange_has', MagicMock(return_value=True)) |
| 425 | mocker.patch('freqtrade.exchange.Exchange.get_tickers', tickers) |
| 426 | mocker.patch('freqtrade.exchange.Exchange.price_to_precision', lambda s, x, y: y) |
| 427 | mocker.patch('freqtrade.data.history.get_timerange', get_timerange) |
| 428 | patch_exchange(mocker) |
| 429 | mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest') |
| 430 | mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist', |
| 431 | PropertyMock(return_value=['XRP/BTC'])) |
| 432 | mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.refresh_pairlist') |
| 433 | |
| 434 | default_conf['ticker_interval'] = "1m" |
| 435 | default_conf['datadir'] = testdatadir |
| 436 | default_conf['export'] = None |
| 437 | # Use stoploss from strategy |
| 438 | del default_conf['stoploss'] |
| 439 | default_conf['timerange'] = '20180101-20180102' |
| 440 | |
| 441 | default_conf['pairlists'] = [{"method": "VolumePairList", "number_assets": 5}] |
| 442 | with pytest.raises(OperationalException, match='VolumePairList not allowed for backtesting.'): |
| 443 | Backtesting(default_conf) |
| 444 | |
| 445 | default_conf['pairlists'] = [{"method": "StaticPairList"}, {"method": "PerformanceFilter"}] |
| 446 | with pytest.raises(OperationalException, |
| 447 | match='PerformanceFilter not allowed for backtesting.'): |
| 448 | Backtesting(default_conf) |
| 449 | |
| 450 | default_conf['pairlists'] = [{"method": "StaticPairList"}, {"method": "PrecisionFilter"}, ] |
| 451 | Backtesting(default_conf) |
| 452 | |
| 453 | # Multiple strategies |
| 454 | default_conf['strategy_list'] = ['DefaultStrategy', 'TestStrategyLegacy'] |
| 455 | with pytest.raises(OperationalException, |
| 456 | match='PrecisionFilter not allowed for backtesting multiple strategies.'): |
| 457 | Backtesting(default_conf) |
| 458 | |
| 459 | |
| 460 | def test_backtest__enter_trade(default_conf, fee, mocker, testdatadir) -> None: |
| 461 | default_conf['ask_strategy']['use_sell_signal'] = False |
| 462 | mocker.patch('freqtrade.exchange.Exchange.get_fee', fee) |
| 463 | mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001) |
| 464 | patch_exchange(mocker) |
| 465 | default_conf['stake_amount'] = 'unlimited' |
| 466 | backtesting = Backtesting(default_conf) |
| 467 | pair = 'UNITTEST/BTC' |
| 468 | row = [ |
| 469 | pd.Timestamp(year=2020, month=1, day=1, hour=5, minute=0), |
| 470 | 1, # Sell |
| 471 | 0.001, # Open |
| 472 | 0.0011, # Close |
| 473 | 0, # Sell |
| 474 | 0.00099, # Low |
| 475 | 0.0012, # High |
| 476 | ] |
| 477 | trade = backtesting._enter_trade(pair, row=row, max_open_trades=2, open_trade_count=0) |
| 478 | assert isinstance(trade, LocalTrade) |
| 479 | assert trade.stake_amount == 495 |
| 480 | |
| 481 | trade = backtesting._enter_trade(pair, row=row, max_open_trades=2, open_trade_count=2) |
| 482 | assert trade is None |
| 483 | |
| 484 | # Stake-amount too high! |
| 485 | mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=600.0) |
| 486 | |
| 487 | trade = backtesting._enter_trade(pair, row=row, max_open_trades=2, open_trade_count=0) |
| 488 | assert trade is None |
| 489 | |
| 490 | # Stake-amount too high! |
| 491 | mocker.patch("freqtrade.wallets.Wallets.get_trade_stake_amount", |
| 492 | side_effect=DependencyException) |
| 493 | |
| 494 | trade = backtesting._enter_trade(pair, row=row, max_open_trades=2, open_trade_count=0) |
| 495 | assert trade is None |
| 496 | |
| 497 | |
| 498 | def test_backtest_one(default_conf, fee, mocker, testdatadir) -> None: |
| 499 | default_conf['ask_strategy']['use_sell_signal'] = False |
| 500 | mocker.patch('freqtrade.exchange.Exchange.get_fee', fee) |
| 501 | mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001) |
| 502 | patch_exchange(mocker) |
| 503 | backtesting = Backtesting(default_conf) |
| 504 | pair = 'UNITTEST/BTC' |
| 505 | timerange = TimeRange('date', None, 1517227800, 0) |
| 506 | data = history.load_data(datadir=testdatadir, timeframe='5m', pairs=['UNITTEST/BTC'], |
| 507 | timerange=timerange) |
| 508 | processed = backtesting.strategy.ohlcvdata_to_dataframe(data) |
| 509 | min_date, max_date = get_timerange(processed) |
| 510 | results = backtesting.backtest( |
| 511 | processed=processed, |
| 512 | start_date=min_date, |
| 513 | end_date=max_date, |
| 514 | max_open_trades=10, |
| 515 | position_stacking=False, |
| 516 | ) |
| 517 | assert not results.empty |
| 518 | assert len(results) == 2 |
| 519 | |
| 520 | expected = pd.DataFrame( |
| 521 | {'pair': [pair, pair], |
| 522 | 'stake_amount': [0.001, 0.001], |
| 523 | 'amount': [0.00957442, 0.0097064], |
| 524 | 'open_date': pd.to_datetime([Arrow(2018, 1, 29, 18, 40, 0).datetime, |
| 525 | Arrow(2018, 1, 30, 3, 30, 0).datetime], utc=True |
| 526 | ), |
| 527 | 'close_date': pd.to_datetime([Arrow(2018, 1, 29, 22, 35, 0).datetime, |
| 528 | Arrow(2018, 1, 30, 4, 10, 0).datetime], utc=True), |
| 529 | 'open_rate': [0.104445, 0.10302485], |
| 530 | 'close_rate': [0.104969, 0.103541], |
| 531 | 'fee_open': [0.0025, 0.0025], |
| 532 | 'fee_close': [0.0025, 0.0025], |
| 533 | 'trade_duration': [235, 40], |
| 534 | 'profit_ratio': [0.0, 0.0], |
| 535 | 'profit_abs': [0.0, 0.0], |
| 536 | 'sell_reason': [SellType.ROI.value, SellType.ROI.value], |
| 537 | 'initial_stop_loss_abs': [0.0940005, 0.09272236], |
| 538 | 'initial_stop_loss_ratio': [-0.1, -0.1], |
| 539 | 'stop_loss_abs': [0.0940005, 0.09272236], |
| 540 | 'stop_loss_ratio': [-0.1, -0.1], |
| 541 | 'min_rate': [0.1038, 0.10302485], |
| 542 | 'max_rate': [0.10501, 0.1038888], |
| 543 | 'is_open': [False, False], |
| 544 | }) |
| 545 | pd.testing.assert_frame_equal(results, expected) |
| 546 | data_pair = processed[pair] |
| 547 | for _, t in results.iterrows(): |
| 548 | ln = data_pair.loc[data_pair["date"] == t["open_date"]] |
| 549 | # Check open trade rate alignes to open rate |
| 550 | assert ln is not None |
| 551 | assert round(ln.iloc[0]["open"], 6) == round(t["open_rate"], 6) |
| 552 | # check close trade rate alignes to close rate or is between high and low |
| 553 | ln = data_pair.loc[data_pair["date"] == t["close_date"]] |
| 554 | assert (round(ln.iloc[0]["open"], 6) == round(t["close_rate"], 6) or |
| 555 | round(ln.iloc[0]["low"], 6) < round( |
| 556 | t["close_rate"], 6) < round(ln.iloc[0]["high"], 6)) |
| 557 | |
| 558 | |
| 559 | def test_backtest_1min_timeframe(default_conf, fee, mocker, testdatadir) -> None: |
| 560 | default_conf['ask_strategy']['use_sell_signal'] = False |
| 561 | mocker.patch('freqtrade.exchange.Exchange.get_fee', fee) |
| 562 | mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001) |
| 563 | patch_exchange(mocker) |
| 564 | backtesting = Backtesting(default_conf) |
| 565 | |
| 566 | # Run a backtesting for an exiting 1min timeframe |
| 567 | timerange = TimeRange.parse_timerange('1510688220-1510700340') |
| 568 | data = history.load_data(datadir=testdatadir, timeframe='1m', pairs=['UNITTEST/BTC'], |
| 569 | timerange=timerange) |
| 570 | processed = backtesting.strategy.ohlcvdata_to_dataframe(data) |
| 571 | min_date, max_date = get_timerange(processed) |
| 572 | results = backtesting.backtest( |
| 573 | processed=processed, |
| 574 | start_date=min_date, |
| 575 | end_date=max_date, |
| 576 | max_open_trades=1, |
| 577 | position_stacking=False, |
| 578 | ) |
| 579 | assert not results.empty |
| 580 | assert len(results) == 1 |
| 581 | |
| 582 | |
| 583 | def test_processed(default_conf, mocker, testdatadir) -> None: |
| 584 | patch_exchange(mocker) |
| 585 | backtesting = Backtesting(default_conf) |
| 586 | |
| 587 | dict_of_tickerrows = load_data_test('raise', testdatadir) |
| 588 | dataframes = backtesting.strategy.ohlcvdata_to_dataframe(dict_of_tickerrows) |
| 589 | dataframe = dataframes['UNITTEST/BTC'] |
| 590 | cols = dataframe.columns |
| 591 | # assert the dataframe got some of the indicator columns |
| 592 | for col in ['close', 'high', 'low', 'open', 'date', |
| 593 | 'ema10', 'rsi', 'fastd', 'plus_di']: |
| 594 | assert col in cols |
| 595 | |
| 596 | |
| 597 | def test_backtest_pricecontours_protections(default_conf, fee, mocker, testdatadir) -> None: |
| 598 | # While this test IS a copy of test_backtest_pricecontours, it's needed to ensure |
| 599 | # results do not carry-over to the next run, which is not given by using parametrize. |
| 600 | default_conf['protections'] = [ |
| 601 | { |
| 602 | "method": "CooldownPeriod", |
| 603 | "stop_duration": 3, |
| 604 | }] |
| 605 | |
| 606 | default_conf['enable_protections'] = True |
| 607 | mocker.patch('freqtrade.exchange.Exchange.get_fee', fee) |
| 608 | mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001) |
| 609 | tests = [ |
| 610 | ['sine', 9], |
| 611 | ['raise', 10], |
| 612 | ['lower', 0], |
| 613 | ['sine', 9], |
| 614 | ['raise', 10], |
| 615 | ] |
| 616 | # While buy-signals are unrealistic, running backtesting |
| 617 | # over and over again should not cause different results |
| 618 | for [contour, numres] in tests: |
| 619 | assert len(simple_backtest(default_conf, contour, mocker, testdatadir)) == numres |
| 620 | |
| 621 | |
| 622 | @pytest.mark.parametrize('protections,contour,expected', [ |
| 623 | (None, 'sine', 35), |
| 624 | (None, 'raise', 19), |
| 625 | (None, 'lower', 0), |
| 626 | (None, 'sine', 35), |
| 627 | (None, 'raise', 19), |
| 628 | ([{"method": "CooldownPeriod", "stop_duration": 3}], 'sine', 9), |
| 629 | ([{"method": "CooldownPeriod", "stop_duration": 3}], 'raise', 10), |
| 630 | ([{"method": "CooldownPeriod", "stop_duration": 3}], 'lower', 0), |
| 631 | ([{"method": "CooldownPeriod", "stop_duration": 3}], 'sine', 9), |
| 632 | ([{"method": "CooldownPeriod", "stop_duration": 3}], 'raise', 10), |
| 633 | ]) |
| 634 | def test_backtest_pricecontours(default_conf, fee, mocker, testdatadir, |
| 635 | protections, contour, expected) -> None: |
| 636 | if protections: |
| 637 | default_conf['protections'] = protections |
| 638 | default_conf['enable_protections'] = True |
| 639 | |
| 640 | mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001) |
| 641 | mocker.patch('freqtrade.exchange.Exchange.get_fee', fee) |
| 642 | # While buy-signals are unrealistic, running backtesting |
| 643 | # over and over again should not cause different results |
| 644 | assert len(simple_backtest(default_conf, contour, mocker, testdatadir)) == expected |
| 645 | |
| 646 | |
| 647 | def test_backtest_clash_buy_sell(mocker, default_conf, testdatadir): |
| 648 | # Override the default buy trend function in our default_strategy |
| 649 | def fun(dataframe=None, pair=None): |
| 650 | buy_value = 1 |
| 651 | sell_value = 1 |
| 652 | return _trend(dataframe, buy_value, sell_value) |
| 653 | |
| 654 | backtest_conf = _make_backtest_conf(mocker, conf=default_conf, datadir=testdatadir) |
| 655 | backtesting = Backtesting(default_conf) |
| 656 | backtesting.strategy.advise_buy = fun # Override |
| 657 | backtesting.strategy.advise_sell = fun # Override |
| 658 | results = backtesting.backtest(**backtest_conf) |
| 659 | assert results.empty |
| 660 | |
| 661 | |
| 662 | def test_backtest_only_sell(mocker, default_conf, testdatadir): |
| 663 | # Override the default buy trend function in our default_strategy |
| 664 | def fun(dataframe=None, pair=None): |
| 665 | buy_value = 0 |
| 666 | sell_value = 1 |
| 667 | return _trend(dataframe, buy_value, sell_value) |
| 668 | |
| 669 | backtest_conf = _make_backtest_conf(mocker, conf=default_conf, datadir=testdatadir) |
| 670 | backtesting = Backtesting(default_conf) |
| 671 | backtesting.strategy.advise_buy = fun # Override |
| 672 | backtesting.strategy.advise_sell = fun # Override |
| 673 | results = backtesting.backtest(**backtest_conf) |
| 674 | assert results.empty |
| 675 | |
| 676 | |
| 677 | def test_backtest_alternate_buy_sell(default_conf, fee, mocker, testdatadir): |
| 678 | mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001) |
| 679 | mocker.patch('freqtrade.exchange.Exchange.get_fee', fee) |
| 680 | backtest_conf = _make_backtest_conf(mocker, conf=default_conf, |
| 681 | pair='UNITTEST/BTC', datadir=testdatadir) |
| 682 | default_conf['timeframe'] = '1m' |
| 683 | backtesting = Backtesting(default_conf) |
| 684 | backtesting.strategy.advise_buy = _trend_alternate # Override |
| 685 | backtesting.strategy.advise_sell = _trend_alternate # Override |
| 686 | results = backtesting.backtest(**backtest_conf) |
| 687 | # 200 candles in backtest data |
| 688 | # won't buy on first (shifted by 1) |
| 689 | # 100 buys signals |
| 690 | assert len(results) == 100 |
| 691 | # One trade was force-closed at the end |
| 692 | assert len(results.loc[results['is_open']]) == 0 |
| 693 | |
| 694 | |
| 695 | @pytest.mark.parametrize("pair", ['ADA/BTC', 'LTC/BTC']) |
| 696 | @pytest.mark.parametrize("tres", [0, 20, 30]) |
| 697 | def test_backtest_multi_pair(default_conf, fee, mocker, tres, pair, testdatadir): |
| 698 | |
| 699 | def _trend_alternate_hold(dataframe=None, metadata=None): |
| 700 | """ |
| 701 | Buy every xth candle - sell every other xth -2 (hold on to pairs a bit) |
| 702 | """ |
| 703 | if metadata['pair'] in ('ETH/BTC', 'LTC/BTC'): |
| 704 | multi = 20 |
| 705 | else: |
| 706 | multi = 18 |
| 707 | dataframe['buy'] = np.where(dataframe.index % multi == 0, 1, 0) |
| 708 | dataframe['sell'] = np.where((dataframe.index + multi - 2) % multi == 0, 1, 0) |
| 709 | return dataframe |
| 710 | |
| 711 | mocker.patch("freqtrade.exchange.Exchange.get_min_pair_stake_amount", return_value=0.00001) |
| 712 | mocker.patch('freqtrade.exchange.Exchange.get_fee', fee) |
| 713 | patch_exchange(mocker) |
| 714 | |
| 715 | pairs = ['ADA/BTC', 'DASH/BTC', 'ETH/BTC', 'LTC/BTC', 'NXT/BTC'] |
| 716 | data = history.load_data(datadir=testdatadir, timeframe='5m', pairs=pairs) |
| 717 | # Only use 500 lines to increase performance |
| 718 | data = trim_dictlist(data, -500) |
| 719 | |
| 720 | # Remove data for one pair from the beginning of the data |
| 721 | data[pair] = data[pair][tres:].reset_index() |
| 722 | default_conf['timeframe'] = '5m' |
| 723 | |
| 724 | backtesting = Backtesting(default_conf) |
| 725 | backtesting.strategy.advise_buy = _trend_alternate_hold # Override |
| 726 | backtesting.strategy.advise_sell = _trend_alternate_hold # Override |
| 727 | |
| 728 | processed = backtesting.strategy.ohlcvdata_to_dataframe(data) |
| 729 | min_date, max_date = get_timerange(processed) |
| 730 | backtest_conf = { |
| 731 | 'processed': processed, |
| 732 | 'start_date': min_date, |
| 733 | 'end_date': max_date, |
| 734 | 'max_open_trades': 3, |
| 735 | 'position_stacking': False, |
| 736 | } |
| 737 | |
| 738 | results = backtesting.backtest(**backtest_conf) |
| 739 | |
| 740 | # Make sure we have parallel trades |
| 741 | assert len(evaluate_result_multi(results, '5m', 2)) > 0 |
| 742 | # make sure we don't have trades with more than configured max_open_trades |
| 743 | assert len(evaluate_result_multi(results, '5m', 3)) == 0 |
| 744 | |
| 745 | backtest_conf = { |
| 746 | 'processed': processed, |
| 747 | 'start_date': min_date, |
| 748 | 'end_date': max_date, |
| 749 | 'max_open_trades': 1, |
| 750 | 'position_stacking': False, |
| 751 | } |
| 752 | results = backtesting.backtest(**backtest_conf) |
| 753 | assert len(evaluate_result_multi(results, '5m', 1)) == 0 |
| 754 | |
| 755 | |
| 756 | def test_backtest_start_timerange(default_conf, mocker, caplog, testdatadir): |
| 757 | |
| 758 | patch_exchange(mocker) |
| 759 | mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest') |
| 760 | mocker.patch('freqtrade.optimize.backtesting.generate_backtest_stats') |
| 761 | mocker.patch('freqtrade.optimize.backtesting.show_backtest_results') |
| 762 | mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist', |
| 763 | PropertyMock(return_value=['UNITTEST/BTC'])) |
| 764 | patched_configuration_load_config_file(mocker, default_conf) |
| 765 | |
| 766 | args = [ |
| 767 | 'backtesting', |
| 768 | '--config', 'config.json', |
| 769 | '--strategy', 'DefaultStrategy', |
| 770 | '--datadir', str(testdatadir), |
| 771 | '--timeframe', '1m', |
| 772 | '--timerange', '1510694220-1510700340', |
| 773 | '--enable-position-stacking', |
| 774 | '--disable-max-market-positions' |
| 775 | ] |
| 776 | args = get_args(args) |
| 777 | start_backtesting(args) |
| 778 | # check the logs, that will contain the backtest result |
| 779 | exists = [ |
| 780 | 'Parameter -i/--timeframe detected ... Using timeframe: 1m ...', |
| 781 | 'Ignoring max_open_trades (--disable-max-market-positions was used) ...', |
| 782 | 'Parameter --timerange detected: 1510694220-1510700340 ...', |
| 783 | f'Using data directory: {testdatadir} ...', |
| 784 | 'Loading data from 2017-11-14 20:57:00 ' |
| 785 | 'up to 2017-11-14 22:58:00 (0 days)..', |
| 786 | 'Backtesting with data from 2017-11-14 21:17:00 ' |
| 787 | 'up to 2017-11-14 22:58:00 (0 days)..', |
| 788 | 'Parameter --enable-position-stacking detected ...' |
| 789 | ] |
| 790 | |
| 791 | for line in exists: |
| 792 | assert log_has(line, caplog) |
| 793 | |
| 794 | |
| 795 | @pytest.mark.filterwarnings("ignore:deprecated") |
| 796 | def test_backtest_start_multi_strat(default_conf, mocker, caplog, testdatadir): |
| 797 | |
| 798 | patch_exchange(mocker) |
| 799 | backtestmock = MagicMock(return_value=pd.DataFrame(columns=BT_DATA_COLUMNS)) |
| 800 | mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist', |
| 801 | PropertyMock(return_value=['UNITTEST/BTC'])) |
| 802 | mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest', backtestmock) |
| 803 | text_table_mock = MagicMock() |
| 804 | sell_reason_mock = MagicMock() |
| 805 | strattable_mock = MagicMock() |
| 806 | strat_summary = MagicMock() |
| 807 | |
| 808 | mocker.patch.multiple('freqtrade.optimize.optimize_reports', |
| 809 | text_table_bt_results=text_table_mock, |
| 810 | text_table_strategy=strattable_mock, |
| 811 | generate_pair_metrics=MagicMock(), |
| 812 | generate_sell_reason_stats=sell_reason_mock, |
| 813 | generate_strategy_metrics=strat_summary, |
| 814 | generate_daily_stats=MagicMock(), |
| 815 | ) |
| 816 | patched_configuration_load_config_file(mocker, default_conf) |
| 817 | |
| 818 | args = [ |
| 819 | 'backtesting', |
| 820 | '--config', 'config.json', |
| 821 | '--datadir', str(testdatadir), |
| 822 | '--strategy-path', str(Path(__file__).parents[1] / 'strategy/strats'), |
| 823 | '--timeframe', '1m', |
| 824 | '--timerange', '1510694220-1510700340', |
| 825 | '--enable-position-stacking', |
| 826 | '--disable-max-market-positions', |
| 827 | '--strategy-list', |
| 828 | 'DefaultStrategy', |
| 829 | 'TestStrategyLegacy', |
| 830 | ] |
| 831 | args = get_args(args) |
| 832 | start_backtesting(args) |
| 833 | # 2 backtests, 4 tables |
| 834 | assert backtestmock.call_count == 2 |
| 835 | assert text_table_mock.call_count == 4 |
| 836 | assert strattable_mock.call_count == 1 |
| 837 | assert sell_reason_mock.call_count == 2 |
| 838 | assert strat_summary.call_count == 1 |
| 839 | |
| 840 | # check the logs, that will contain the backtest result |
| 841 | exists = [ |
| 842 | 'Parameter -i/--timeframe detected ... Using timeframe: 1m ...', |
| 843 | 'Ignoring max_open_trades (--disable-max-market-positions was used) ...', |
| 844 | 'Parameter --timerange detected: 1510694220-1510700340 ...', |
| 845 | f'Using data directory: {testdatadir} ...', |
| 846 | 'Loading data from 2017-11-14 20:57:00 ' |
| 847 | 'up to 2017-11-14 22:58:00 (0 days)..', |
| 848 | 'Backtesting with data from 2017-11-14 21:17:00 ' |
| 849 | 'up to 2017-11-14 22:58:00 (0 days)..', |
| 850 | 'Parameter --enable-position-stacking detected ...', |
| 851 | 'Running backtesting for Strategy DefaultStrategy', |
| 852 | 'Running backtesting for Strategy TestStrategyLegacy', |
| 853 | ] |
| 854 | |
| 855 | for line in exists: |
| 856 | assert log_has(line, caplog) |
| 857 | |
| 858 | |
| 859 | @pytest.mark.filterwarnings("ignore:deprecated") |
| 860 | def test_backtest_start_multi_strat_nomock(default_conf, mocker, caplog, testdatadir, capsys): |
| 861 | |
| 862 | patch_exchange(mocker) |
| 863 | backtestmock = MagicMock(side_effect=[ |
| 864 | pd.DataFrame({'pair': ['XRP/BTC', 'LTC/BTC'], |
| 865 | 'profit_ratio': [0.0, 0.0], |
| 866 | 'profit_abs': [0.0, 0.0], |
| 867 | 'open_date': pd.to_datetime(['2018-01-29 18:40:00', |
| 868 | '2018-01-30 03:30:00', ], utc=True |
| 869 | ), |
| 870 | 'close_date': pd.to_datetime(['2018-01-29 20:45:00', |
| 871 | '2018-01-30 05:35:00', ], utc=True), |
| 872 | 'trade_duration': [235, 40], |
| 873 | 'is_open': [False, False], |
| 874 | 'stake_amount': [0.01, 0.01], |
| 875 | 'open_rate': [0.104445, 0.10302485], |
| 876 | 'close_rate': [0.104969, 0.103541], |
| 877 | 'sell_reason': [SellType.ROI, SellType.ROI] |
| 878 | }), |
| 879 | pd.DataFrame({'pair': ['XRP/BTC', 'LTC/BTC', 'ETH/BTC'], |
| 880 | 'profit_ratio': [0.03, 0.01, 0.1], |
| 881 | 'profit_abs': [0.01, 0.02, 0.2], |
| 882 | 'open_date': pd.to_datetime(['2018-01-29 18:40:00', |
| 883 | '2018-01-30 03:30:00', |
| 884 | '2018-01-30 05:30:00'], utc=True |
| 885 | ), |
| 886 | 'close_date': pd.to_datetime(['2018-01-29 20:45:00', |
| 887 | '2018-01-30 05:35:00', |
| 888 | '2018-01-30 08:30:00'], utc=True), |
| 889 | 'trade_duration': [47, 40, 20], |
| 890 | 'is_open': [False, False, False], |
| 891 | 'stake_amount': [0.01, 0.01, 0.01], |
| 892 | 'open_rate': [0.104445, 0.10302485, 0.122541], |
| 893 | 'close_rate': [0.104969, 0.103541, 0.123541], |
| 894 | 'sell_reason': [SellType.ROI, SellType.ROI, SellType.STOP_LOSS] |
| 895 | }), |
| 896 | ]) |
| 897 | mocker.patch('freqtrade.plugins.pairlistmanager.PairListManager.whitelist', |
| 898 | PropertyMock(return_value=['UNITTEST/BTC'])) |
| 899 | mocker.patch('freqtrade.optimize.backtesting.Backtesting.backtest', backtestmock) |
| 900 | |
| 901 | patched_configuration_load_config_file(mocker, default_conf) |
| 902 | |
| 903 | args = [ |
| 904 | 'backtesting', |
| 905 | '--config', 'config.json', |
| 906 | '--datadir', str(testdatadir), |
| 907 | '--strategy-path', str(Path(__file__).parents[1] / 'strategy/strats'), |
| 908 | '--timeframe', '1m', |
| 909 | '--timerange', '1510694220-1510700340', |
| 910 | '--enable-position-stacking', |
| 911 | '--disable-max-market-positions', |
| 912 | '--strategy-list', |
| 913 | 'DefaultStrategy', |
| 914 | 'TestStrategyLegacy', |
| 915 | ] |
| 916 | args = get_args(args) |
| 917 | start_backtesting(args) |
| 918 | |
| 919 | # check the logs, that will contain the backtest result |
| 920 | exists = [ |
| 921 | 'Parameter -i/--timeframe detected ... Using timeframe: 1m ...', |
| 922 | 'Ignoring max_open_trades (--disable-max-market-positions was used) ...', |
| 923 | 'Parameter --timerange detected: 1510694220-1510700340 ...', |
| 924 | f'Using data directory: {testdatadir} ...', |
| 925 | 'Loading data from 2017-11-14 20:57:00 ' |
| 926 | 'up to 2017-11-14 22:58:00 (0 days)..', |
| 927 | 'Backtesting with data from 2017-11-14 21:17:00 ' |
| 928 | 'up to 2017-11-14 22:58:00 (0 days)..', |
| 929 | 'Parameter --enable-position-stacking detected ...', |
| 930 | 'Running backtesting for Strategy DefaultStrategy', |
| 931 | 'Running backtesting for Strategy TestStrategyLegacy', |
| 932 | ] |
| 933 | |
| 934 | for line in exists: |
| 935 | assert log_has(line, caplog) |
| 936 | |
| 937 | captured = capsys.readouterr() |
| 938 | assert 'BACKTESTING REPORT' in captured.out |
| 939 | assert 'SELL REASON STATS' in captured.out |
| 940 | assert 'LEFT OPEN TRADES REPORT' in captured.out |
| 941 | assert 'STRATEGY SUMMARY' in captured.out |