| 1 | from pathlib import Path |
| 2 | from unittest.mock import MagicMock |
| 3 | |
| 4 | import pytest |
| 5 | from arrow import Arrow |
| 6 | from pandas import DataFrame, DateOffset, Timestamp, to_datetime |
| 7 | |
| 8 | from freqtrade.configuration import TimeRange |
| 9 | from freqtrade.constants import LAST_BT_RESULT_FN |
| 10 | from freqtrade.data.btanalysis import (BT_DATA_COLUMNS, BT_DATA_COLUMNS_MID, BT_DATA_COLUMNS_OLD, |
| 11 | analyze_trade_parallelism, calculate_csum, |
| 12 | calculate_market_change, calculate_max_drawdown, |
| 13 | combine_dataframes_with_mean, create_cum_profit, |
| 14 | extract_trades_of_period, get_latest_backtest_filename, |
| 15 | get_latest_hyperopt_file, load_backtest_data, load_trades, |
| 16 | load_trades_from_db) |
| 17 | from freqtrade.data.history import load_data, load_pair_history |
| 18 | from tests.conftest import create_mock_trades |
| 19 | from tests.conftest_trades import MOCK_TRADE_COUNT |
| 20 | |
| 21 | |
| 22 | def test_get_latest_backtest_filename(testdatadir, mocker): |
| 23 | with pytest.raises(ValueError, match=r"Directory .* does not exist\."): |
| 24 | get_latest_backtest_filename(testdatadir / 'does_not_exist') |
| 25 | |
| 26 | with pytest.raises(ValueError, |
| 27 | match=r"Directory .* does not seem to contain .*"): |
| 28 | get_latest_backtest_filename(testdatadir.parent) |
| 29 | |
| 30 | res = get_latest_backtest_filename(testdatadir) |
| 31 | assert res == 'backtest-result_new.json' |
| 32 | |
| 33 | res = get_latest_backtest_filename(str(testdatadir)) |
| 34 | assert res == 'backtest-result_new.json' |
| 35 | |
| 36 | mocker.patch("freqtrade.data.btanalysis.json_load", return_value={}) |
| 37 | |
| 38 | with pytest.raises(ValueError, match=r"Invalid '.last_result.json' format."): |
| 39 | get_latest_backtest_filename(testdatadir) |
| 40 | |
| 41 | |
| 42 | def test_get_latest_hyperopt_file(testdatadir, mocker): |
| 43 | res = get_latest_hyperopt_file(testdatadir / 'does_not_exist', 'testfile.pickle') |
| 44 | assert res == testdatadir / 'does_not_exist/testfile.pickle' |
| 45 | |
| 46 | res = get_latest_hyperopt_file(testdatadir.parent) |
| 47 | assert res == testdatadir.parent / "hyperopt_results.pickle" |
| 48 | |
| 49 | res = get_latest_hyperopt_file(str(testdatadir.parent)) |
| 50 | assert res == testdatadir.parent / "hyperopt_results.pickle" |
| 51 | |
| 52 | |
| 53 | def test_load_backtest_data_old_format(testdatadir): |
| 54 | |
| 55 | filename = testdatadir / "backtest-result_test.json" |
| 56 | bt_data = load_backtest_data(filename) |
| 57 | assert isinstance(bt_data, DataFrame) |
| 58 | assert list(bt_data.columns) == BT_DATA_COLUMNS_OLD + ['profit_abs', 'profit_ratio'] |
| 59 | assert len(bt_data) == 179 |
| 60 | |
| 61 | # Test loading from string (must yield same result) |
| 62 | bt_data2 = load_backtest_data(str(filename)) |
| 63 | assert bt_data.equals(bt_data2) |
| 64 | |
| 65 | with pytest.raises(ValueError, match=r"File .* does not exist\."): |
| 66 | load_backtest_data(str("filename") + "nofile") |
| 67 | |
| 68 | |
| 69 | def test_load_backtest_data_new_format(testdatadir): |
| 70 | |
| 71 | filename = testdatadir / "backtest-result_new.json" |
| 72 | bt_data = load_backtest_data(filename) |
| 73 | assert isinstance(bt_data, DataFrame) |
| 74 | assert set(bt_data.columns) == set(BT_DATA_COLUMNS_MID) |
| 75 | assert len(bt_data) == 179 |
| 76 | |
| 77 | # Test loading from string (must yield same result) |
| 78 | bt_data2 = load_backtest_data(str(filename)) |
| 79 | assert bt_data.equals(bt_data2) |
| 80 | |
| 81 | # Test loading from folder (must yield same result) |
| 82 | bt_data3 = load_backtest_data(testdatadir) |
| 83 | assert bt_data.equals(bt_data3) |
| 84 | |
| 85 | with pytest.raises(ValueError, match=r"File .* does not exist\."): |
| 86 | load_backtest_data(str("filename") + "nofile") |
| 87 | |
| 88 | with pytest.raises(ValueError, match=r"Unknown dataformat."): |
| 89 | load_backtest_data(testdatadir / LAST_BT_RESULT_FN) |
| 90 | |
| 91 | |
| 92 | def test_load_backtest_data_multi(testdatadir): |
| 93 | |
| 94 | filename = testdatadir / "backtest-result_multistrat.json" |
| 95 | for strategy in ('DefaultStrategy', 'TestStrategy'): |
| 96 | bt_data = load_backtest_data(filename, strategy=strategy) |
| 97 | assert isinstance(bt_data, DataFrame) |
| 98 | assert set(bt_data.columns) == set(BT_DATA_COLUMNS_MID) |
| 99 | assert len(bt_data) == 179 |
| 100 | |
| 101 | # Test loading from string (must yield same result) |
| 102 | bt_data2 = load_backtest_data(str(filename), strategy=strategy) |
| 103 | assert bt_data.equals(bt_data2) |
| 104 | |
| 105 | with pytest.raises(ValueError, match=r"Strategy XYZ not available in the backtest result\."): |
| 106 | load_backtest_data(filename, strategy='XYZ') |
| 107 | |
| 108 | with pytest.raises(ValueError, match=r"Detected backtest result with more than one strategy.*"): |
| 109 | load_backtest_data(filename) |
| 110 | |
| 111 | |
| 112 | @pytest.mark.usefixtures("init_persistence") |
| 113 | def test_load_trades_from_db(default_conf, fee, mocker): |
| 114 | |
| 115 | create_mock_trades(fee) |
| 116 | # remove init so it does not init again |
| 117 | init_mock = mocker.patch('freqtrade.data.btanalysis.init_db', MagicMock()) |
| 118 | |
| 119 | trades = load_trades_from_db(db_url=default_conf['db_url']) |
| 120 | assert init_mock.call_count == 1 |
| 121 | assert len(trades) == MOCK_TRADE_COUNT |
| 122 | assert isinstance(trades, DataFrame) |
| 123 | assert "pair" in trades.columns |
| 124 | assert "open_date" in trades.columns |
| 125 | assert "profit_ratio" in trades.columns |
| 126 | |
| 127 | for col in BT_DATA_COLUMNS: |
| 128 | if col not in ['index', 'open_at_end']: |
| 129 | assert col in trades.columns |
| 130 | trades = load_trades_from_db(db_url=default_conf['db_url'], strategy='DefaultStrategy') |
| 131 | assert len(trades) == 4 |
| 132 | trades = load_trades_from_db(db_url=default_conf['db_url'], strategy='NoneStrategy') |
| 133 | assert len(trades) == 0 |
| 134 | |
| 135 | |
| 136 | def test_extract_trades_of_period(testdatadir): |
| 137 | pair = "UNITTEST/BTC" |
| 138 | # 2018-11-14 06:07:00 |
| 139 | timerange = TimeRange('date', None, 1510639620, 0) |
| 140 | |
| 141 | data = load_pair_history(pair=pair, timeframe='1m', |
| 142 | datadir=testdatadir, timerange=timerange) |
| 143 | |
| 144 | trades = DataFrame( |
| 145 | {'pair': [pair, pair, pair, pair], |
| 146 | 'profit_ratio': [0.0, 0.1, -0.2, -0.5], |
| 147 | 'profit_abs': [0.0, 1, -2, -5], |
| 148 | 'open_date': to_datetime([Arrow(2017, 11, 13, 15, 40, 0).datetime, |
| 149 | Arrow(2017, 11, 14, 9, 41, 0).datetime, |
| 150 | Arrow(2017, 11, 14, 14, 20, 0).datetime, |
| 151 | Arrow(2017, 11, 15, 3, 40, 0).datetime, |
| 152 | ], utc=True |
| 153 | ), |
| 154 | 'close_date': to_datetime([Arrow(2017, 11, 13, 16, 40, 0).datetime, |
| 155 | Arrow(2017, 11, 14, 10, 41, 0).datetime, |
| 156 | Arrow(2017, 11, 14, 15, 25, 0).datetime, |
| 157 | Arrow(2017, 11, 15, 3, 55, 0).datetime, |
| 158 | ], utc=True) |
| 159 | }) |
| 160 | trades1 = extract_trades_of_period(data, trades) |
| 161 | # First and last trade are dropped as they are out of range |
| 162 | assert len(trades1) == 2 |
| 163 | assert trades1.iloc[0].open_date == Arrow(2017, 11, 14, 9, 41, 0).datetime |
| 164 | assert trades1.iloc[0].close_date == Arrow(2017, 11, 14, 10, 41, 0).datetime |
| 165 | assert trades1.iloc[-1].open_date == Arrow(2017, 11, 14, 14, 20, 0).datetime |
| 166 | assert trades1.iloc[-1].close_date == Arrow(2017, 11, 14, 15, 25, 0).datetime |
| 167 | |
| 168 | |
| 169 | def test_analyze_trade_parallelism(default_conf, mocker, testdatadir): |
| 170 | filename = testdatadir / "backtest-result_test.json" |
| 171 | bt_data = load_backtest_data(filename) |
| 172 | |
| 173 | res = analyze_trade_parallelism(bt_data, "5m") |
| 174 | assert isinstance(res, DataFrame) |
| 175 | assert 'open_trades' in res.columns |
| 176 | assert res['open_trades'].max() == 3 |
| 177 | assert res['open_trades'].min() == 0 |
| 178 | |
| 179 | |
| 180 | def test_load_trades(default_conf, mocker): |
| 181 | db_mock = mocker.patch("freqtrade.data.btanalysis.load_trades_from_db", MagicMock()) |
| 182 | bt_mock = mocker.patch("freqtrade.data.btanalysis.load_backtest_data", MagicMock()) |
| 183 | |
| 184 | load_trades("DB", |
| 185 | db_url=default_conf.get('db_url'), |
| 186 | exportfilename=default_conf.get('exportfilename'), |
| 187 | no_trades=False, |
| 188 | strategy="DefaultStrategy", |
| 189 | ) |
| 190 | |
| 191 | assert db_mock.call_count == 1 |
| 192 | assert bt_mock.call_count == 0 |
| 193 | |
| 194 | db_mock.reset_mock() |
| 195 | bt_mock.reset_mock() |
| 196 | default_conf['exportfilename'] = Path("testfile.json") |
| 197 | load_trades("file", |
| 198 | db_url=default_conf.get('db_url'), |
| 199 | exportfilename=default_conf.get('exportfilename'), |
| 200 | ) |
| 201 | |
| 202 | assert db_mock.call_count == 0 |
| 203 | assert bt_mock.call_count == 1 |
| 204 | |
| 205 | db_mock.reset_mock() |
| 206 | bt_mock.reset_mock() |
| 207 | default_conf['exportfilename'] = "testfile.json" |
| 208 | load_trades("file", |
| 209 | db_url=default_conf.get('db_url'), |
| 210 | exportfilename=default_conf.get('exportfilename'), |
| 211 | no_trades=True |
| 212 | ) |
| 213 | |
| 214 | assert db_mock.call_count == 0 |
| 215 | assert bt_mock.call_count == 0 |
| 216 | |
| 217 | |
| 218 | def test_calculate_market_change(testdatadir): |
| 219 | pairs = ["ETH/BTC", "ADA/BTC"] |
| 220 | data = load_data(datadir=testdatadir, pairs=pairs, timeframe='5m') |
| 221 | result = calculate_market_change(data) |
| 222 | assert isinstance(result, float) |
| 223 | assert pytest.approx(result) == 0.00955514 |
| 224 | |
| 225 | |
| 226 | def test_combine_dataframes_with_mean(testdatadir): |
| 227 | pairs = ["ETH/BTC", "ADA/BTC"] |
| 228 | data = load_data(datadir=testdatadir, pairs=pairs, timeframe='5m') |
| 229 | df = combine_dataframes_with_mean(data) |
| 230 | assert isinstance(df, DataFrame) |
| 231 | assert "ETH/BTC" in df.columns |
| 232 | assert "ADA/BTC" in df.columns |
| 233 | assert "mean" in df.columns |
| 234 | |
| 235 | |
| 236 | def test_create_cum_profit(testdatadir): |
| 237 | filename = testdatadir / "backtest-result_test.json" |
| 238 | bt_data = load_backtest_data(filename) |
| 239 | timerange = TimeRange.parse_timerange("20180110-20180112") |
| 240 | |
| 241 | df = load_pair_history(pair="TRX/BTC", timeframe='5m', |
| 242 | datadir=testdatadir, timerange=timerange) |
| 243 | |
| 244 | cum_profits = create_cum_profit(df.set_index('date'), |
| 245 | bt_data[bt_data["pair"] == 'TRX/BTC'], |
| 246 | "cum_profits", timeframe="5m") |
| 247 | assert "cum_profits" in cum_profits.columns |
| 248 | assert cum_profits.iloc[0]['cum_profits'] == 0 |
| 249 | assert cum_profits.iloc[-1]['cum_profits'] == 0.0798005 |
| 250 | |
| 251 | |
| 252 | def test_create_cum_profit1(testdatadir): |
| 253 | filename = testdatadir / "backtest-result_test.json" |
| 254 | bt_data = load_backtest_data(filename) |
| 255 | # Move close-time to "off" the candle, to make sure the logic still works |
| 256 | bt_data.loc[:, 'close_date'] = bt_data.loc[:, 'close_date'] + DateOffset(seconds=20) |
| 257 | timerange = TimeRange.parse_timerange("20180110-20180112") |
| 258 | |
| 259 | df = load_pair_history(pair="TRX/BTC", timeframe='5m', |
| 260 | datadir=testdatadir, timerange=timerange) |
| 261 | |
| 262 | cum_profits = create_cum_profit(df.set_index('date'), |
| 263 | bt_data[bt_data["pair"] == 'TRX/BTC'], |
| 264 | "cum_profits", timeframe="5m") |
| 265 | assert "cum_profits" in cum_profits.columns |
| 266 | assert cum_profits.iloc[0]['cum_profits'] == 0 |
| 267 | assert cum_profits.iloc[-1]['cum_profits'] == 0.0798005 |
| 268 | |
| 269 | with pytest.raises(ValueError, match='Trade dataframe empty.'): |
| 270 | create_cum_profit(df.set_index('date'), bt_data[bt_data["pair"] == 'NOTAPAIR'], |
| 271 | "cum_profits", timeframe="5m") |
| 272 | |
| 273 | |
| 274 | def test_calculate_max_drawdown(testdatadir): |
| 275 | filename = testdatadir / "backtest-result_test.json" |
| 276 | bt_data = load_backtest_data(filename) |
| 277 | drawdown, hdate, lowdate, hval, lval = calculate_max_drawdown(bt_data) |
| 278 | assert isinstance(drawdown, float) |
| 279 | assert pytest.approx(drawdown) == 0.21142322 |
| 280 | assert isinstance(hdate, Timestamp) |
| 281 | assert isinstance(lowdate, Timestamp) |
| 282 | assert isinstance(hval, float) |
| 283 | assert isinstance(lval, float) |
| 284 | assert hdate == Timestamp('2018-01-24 14:25:00', tz='UTC') |
| 285 | assert lowdate == Timestamp('2018-01-30 04:45:00', tz='UTC') |
| 286 | with pytest.raises(ValueError, match='Trade dataframe empty.'): |
| 287 | drawdown, hdate, lowdate, hval, lval = calculate_max_drawdown(DataFrame()) |
| 288 | |
| 289 | |
| 290 | def test_calculate_csum(testdatadir): |
| 291 | filename = testdatadir / "backtest-result_test.json" |
| 292 | bt_data = load_backtest_data(filename) |
| 293 | csum_min, csum_max = calculate_csum(bt_data) |
| 294 | |
| 295 | assert isinstance(csum_min, float) |
| 296 | assert isinstance(csum_max, float) |
| 297 | assert csum_min < 0.01 |
| 298 | assert csum_max > 0.02 |
| 299 | csum_min1, csum_max1 = calculate_csum(bt_data, 5) |
| 300 | |
| 301 | assert csum_min1 == csum_min + 5 |
| 302 | assert csum_max1 == csum_max + 5 |
| 303 | |
| 304 | with pytest.raises(ValueError, match='Trade dataframe empty.'): |
| 305 | csum_min, csum_max = calculate_csum(DataFrame()) |
| 306 | |
| 307 | |
| 308 | def test_calculate_max_drawdown2(): |
| 309 | values = [0.011580, 0.010048, 0.011340, 0.012161, 0.010416, 0.010009, 0.020024, |
| 310 | -0.024662, -0.022350, 0.020496, -0.029859, -0.030511, 0.010041, 0.010872, |
| 311 | -0.025782, 0.010400, 0.012374, 0.012467, 0.114741, 0.010303, 0.010088, |
| 312 | -0.033961, 0.010680, 0.010886, -0.029274, 0.011178, 0.010693, 0.010711] |
| 313 | |
| 314 | dates = [Arrow(2020, 1, 1).shift(days=i) for i in range(len(values))] |
| 315 | df = DataFrame(zip(values, dates), columns=['profit', 'open_date']) |
| 316 | # sort by profit and reset index |
| 317 | df = df.sort_values('profit').reset_index(drop=True) |
| 318 | df1 = df.copy() |
| 319 | drawdown, hdate, ldate, hval, lval = calculate_max_drawdown( |
| 320 | df, date_col='open_date', value_col='profit') |
| 321 | # Ensure df has not been altered. |
| 322 | assert df.equals(df1) |
| 323 | |
| 324 | assert isinstance(drawdown, float) |
| 325 | # High must be before low |
| 326 | assert hdate < ldate |
| 327 | # High value must be higher than low value |
| 328 | assert hval > lval |
| 329 | assert drawdown == 0.091755 |
| 330 | |
| 331 | df = DataFrame(zip(values[:5], dates[:5]), columns=['profit', 'open_date']) |
| 332 | with pytest.raises(ValueError, match='No losing trade, therefore no drawdown.'): |
| 333 | calculate_max_drawdown(df, date_col='open_date', value_col='profit') |