def test_backtest(conf, pairs, mocker): trades = [] mocker.patch.dict('freqtrade.main._CONF', conf) for pair in pairs: with open('freqtrade/tests/testdata/'+pair+'.json') as data_file: data = json.load(data_file) mocker.patch('freqtrade.analyze.get_ticker_history', return_value=data) mocker.patch('arrow.utcnow', return_value=arrow.get('2017-08-20T14:50:00')) ticker = analyze_ticker(pair) # for each buy point for index, row in ticker[ticker.buy == 1].iterrows(): trade = Trade( open_rate=row['close'], open_date=arrow.get(row['date']).datetime, amount=1, ) # calculate win/lose forwards from buy point for index2, row2 in ticker[index:].iterrows(): if should_sell(trade, row2['close'], arrow.get(row2['date']).datetime): current_profit = (row2['close'] - trade.open_rate) / trade.open_rate trades.append((pair, current_profit, index2 - index)) break labels = ['currency', 'profit', 'duration'] results = DataFrame.from_records(trades, columns=labels) print('====================== BACKTESTING REPORT ================================') for pair in pairs: print('For currency {}:'.format(pair)) print_results(results[results.currency == pair]) print('TOTAL OVER ALL TRADES:') print_results(results)
def backtest(backtest_conf, backdata, mocker): trades = [] exchange._API = Bittrex({'key': '', 'secret': ''}) mocked_history = mocker.patch('freqtrade.analyze.get_ticker_history') mocker.patch.dict('freqtrade.main._CONF', backtest_conf) mocker.patch('arrow.utcnow', return_value=arrow.get('2017-08-20T14:50:00')) for pair, pair_data in backdata.items(): mocked_history.return_value = pair_data ticker = analyze_ticker(pair)[['close', 'date', 'buy']].copy() # for each buy point for row in ticker[ticker.buy == 1].itertuples(index=True): trade = Trade(open_rate=row.close, open_date=row.date, amount=1, fee=exchange.get_fee() * 2) # calculate win/lose forwards from buy point for row2 in ticker[row.Index:].itertuples(index=True): if should_sell(trade, row2.close, row2.date): current_profit = trade.calc_profit(row2.close) trades.append( (pair, current_profit, row2.Index - row.Index)) break labels = ['currency', 'profit', 'duration'] results = DataFrame.from_records(trades, columns=labels) return results
def plot_analyzed_dataframe(args) -> None: """ Calls analyze() and plots the returned dataframe :param pair: pair as str :return: None """ pair = args.pair # Init Bittrex to use public API exchange._API = exchange.Bittrex({'key': '', 'secret': ''}) ticker = exchange.get_ticker_history(pair) dataframe = analyze.analyze_ticker(ticker) dataframe.loc[dataframe['buy'] == 1, 'buy_price'] = dataframe['close'] dataframe.loc[dataframe['sell'] == 1, 'sell_price'] = dataframe['close'] # Two subplots sharing x axis fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True) fig.suptitle(pair, fontsize=14, fontweight='bold') ax1.plot(dataframe.index.values, dataframe['close'], label='close') # ax1.plot(dataframe.index.values, dataframe['sell'], 'ro', label='sell') ax1.plot(dataframe.index.values, dataframe['sma'], '--', label='SMA') ax1.plot(dataframe.index.values, dataframe['tema'], ':', label='TEMA') ax1.plot(dataframe.index.values, dataframe['blower'], '-.', label='BB low') ax1.plot(dataframe.index.values, dataframe['buy_price'], 'bo', label='buy') ax1.legend() ax2.plot(dataframe.index.values, dataframe['adx'], label='ADX') ax2.plot(dataframe.index.values, dataframe['mfi'], label='MFI') # ax2.plot(dataframe.index.values, [25] * len(dataframe.index.values)) ax2.legend() ax3.plot(dataframe.index.values, dataframe['fastk'], label='k') ax3.plot(dataframe.index.values, dataframe['fastd'], label='d') ax3.plot(dataframe.index.values, [20] * len(dataframe.index.values)) ax3.legend() # Fine-tune figure; make subplots close to each other and hide x ticks for # all but bottom plot. fig.subplots_adjust(hspace=0) plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False) plt.show()
def backtest(conf, pairs, mocker, buy_strategy): trades = [] mocker.patch.dict('freqtrade.main._CONF', conf) for pair in pairs: with open('freqtrade/tests/testdata/'+pair+'.json') as data_file: data = json.load(data_file) mocker.patch('freqtrade.analyze.get_ticker_history', return_value=data) mocker.patch('arrow.utcnow', return_value=arrow.get('2017-08-20T14:50:00')) mocker.patch('freqtrade.analyze.populate_buy_trend', side_effect=buy_strategy) ticker = analyze_ticker(pair) # for each buy point for index, row in ticker[ticker.buy == 1].iterrows(): trade = Trade( open_rate=row['close'], open_date=arrow.get(row['date']).datetime, amount=1, ) # calculate win/lose forwards from buy point for index2, row2 in ticker[index:].iterrows(): if should_sell(trade, row2['close'], arrow.get(row2['date']).datetime): current_profit = (row2['close'] - trade.open_rate) / trade.open_rate trades.append((pair, current_profit, index2 - index)) break labels = ['currency', 'profit', 'duration'] results = DataFrame.from_records(trades, columns=labels) print_results(results) # set the value below to suit your number concurrent trades so its realistic to 20days of data TARGET_TRADES = 1200 if results.profit.sum() == 0 or results.profit.mean() == 0: return 49999999999 # avoid division by zero, return huge value to discard result return abs(len(results.index) - 1200.1) / (results.profit.sum() ** 2) * results.duration.mean() # the smaller the better
# ensure directory exists base_path = os.path.join(os.path.expanduser('~'), 'freqtrade') data_path = os.path.join(base_path, 'ml_dev', 'data', 'markets') market_path = os.path.join(data_path, market) if not os.path.isdir(market_path): os.mkdir(market_path) # get configuration with open(os.path.join(base_path, 'config.json')) as file: _CONF = json.load(file) # initialize the exchange exchange.init(_CONF) # get ticker hisroty df = analyze_ticker(pair=market, tick_interval=time_interval) # remove first 100 rows to allow ema100 df = df[100:] df.to_csv('test.csv', index=False) master = pd.read_csv('test.csv') # get targets master['percent_change'] = 0. print(master.shape) for entry in range(len(master) - 1): print(entry)