Пример #1
0
def test_std_backtest(cerebro: bt.Cerebro):
    cerebro.addstrategy(bt.strategies.MA_CrossOver)
    cerebro.run()

    s = backtrader_plotting.schemes.Blackly()
    b = Bokeh(style='bar', scheme=s, output_mode=_output_mode)
    figs = cerebro.plot(b)

    assert len(figs) == 1
    assert_num_tabs(figs, 3)
    assert_num_figures(figs, 4)
Пример #2
0
def test_backtest_2strats(cerebro: bt.Cerebro):
    cerebro.addstrategy(bt.strategies.MA_CrossOver)
    cerebro.addstrategy(ToggleStrategy)
    cerebro.run()

    b = Bokeh(style='bar', output_mode=_output_mode)

    figs = cerebro.plot(b)

    assert len(figs) == 2
    assert_num_tabs(figs, 3, 3)
    assert_num_figures(figs, 4, 3)
Пример #3
0
def test_std_backtest_ind_on_line(cerebro: bt.Cerebro):
    '''In the past it crashed when creating indicators with specific lines case LineSeriesStub was not handled correctly'''
    class TestStrategy(bt.Strategy):
        def __init__(self):
            self._sma = bt.indicators.SMA(self.data.close)

    cerebro.addstrategy(TestStrategy)
    cerebro.run()

    s = backtrader_plotting.schemes.Blackly()
    b = Bokeh(style='bar', scheme=s, output_mode=_output_mode)
    figs = cerebro.plot(b)

    assert len(figs) == 1
    assert_num_tabs(figs, 3)
    assert_num_figures(figs, 3)
Пример #4
0
def test_std_backtest_ind_subplot(cerebro: bt.Cerebro):
    cerebro.addstrategy(bt.strategies.MA_CrossOver)
    cerebro.run()

    plotconfig = {
        '#:i-0': {
            'subplot': True,
        }
    }

    s = backtrader_plotting.schemes.Blackly()
    b = Bokeh(style='bar',
              scheme=s,
              output_mode=_output_mode,
              plotconfig=plotconfig)

    figs = cerebro.plot(b)

    assert_num_tabs(figs, 3)
    assert_num_figures(figs, 5)
Пример #5
0
def test_std_backtest_2datas(cerebro: bt.Cerebro):
    datapath = getdatadir('nvda-1999-2014.txt')
    data = bt.feeds.YahooFinanceCSVData(
        dataname=datapath,
        fromdate=datetime.datetime(1998, 1, 1),
        todate=datetime.datetime(2000, 12, 31),
        reverse=False,
        swapcloses=True,
    )
    cerebro.adddata(data)

    cerebro.addstrategy(bt.strategies.MA_CrossOver)
    cerebro.run()

    s = backtrader_plotting.schemes.Blackly()
    b = Bokeh(style='bar',
              scheme=s,
              output_mode=_output_mode,
              merge_data_hovers=True)
    figs = cerebro.plot(b)

    assert len(figs) == 1
    assert_num_tabs(figs, 3)
    assert_num_figures(figs, 5)
Пример #6
0
from backtrader import Cerebro, TimeFrame
from BackTraderQuik.QKStore import QKStore  # Хранилище QUIK
import Strategy as ts  # Торговые системы

if __name__ == '__main__':  # Точка входа при запуске этого скрипта
    cerebro = Cerebro()  # Инициируем "движок" BackTrader

    # Склейка фьючерсов (Rollover)
    symbols = ['SPBFUT.SiH9', 'SPBFUT.SiM9', 'SPBFUT.SiU9', 'SPBFUT.SiZ9',
    'SPBFUT.SiH0', 'SPBFUT.SiM0', 'SPBFUT.SiU0', 'SPBFUT.SiZ0',
    'SPBFUT.SiH1', 'SPBFUT.SiM1', 'SPBFUT.SiU1', 'SPBFUT.SiZ1']  # Тикеры для склейки
    store = QKStore()  # Хранилище QUIK (QUIK на локальном компьютере)
    # store = QKStore(Host='<Ваш IP адрес>')  # Хранилище QUIK (К QUIK на удаленном компьютере обращаемся по IP или названию)
    data = [store.getdata(dataname=symbol, timeframe=TimeFrame.Minutes, compression=5) for symbol in symbols]  # Получаем по ним исторические данные
    cerebro.rolloverdata(name='Si', *data, checkdate=True, checkcondition=True)  # Склеенный тикер
    cerebro.addstrategy(ts.PrintStatusAndBars)  # Добавляем торговую систему

    cerebro.run()  # Запуск торговой системы
    cerebro.plot()  # Рисуем график. Требуется matplotlib версии 3.2.2 (pip install matplotlib==3.2.2)
Пример #7
0
import pandas
import backtrader
from backtrader import Cerebro
from strategies.BuyAndHold import BuyAndHold
from strategies.GoldenCross import GoldenCross

cerebro = backtrader.Cerebro()

pricesData = pandas.read_csv('SPY.csv', index_col='Date', parse_dates=True)

# initializing Cerebro
cerebro = Cerebro()
cerebro.broker.setcash(100000)

feed = backtrader.feeds.PandasData(dataname=pricesData)  # add data feed
cerebro.adddata(feed)

strategies = {"golden_cross": GoldenCross, "buy_hold": BuyAndHold}

parser = argparse.ArgumentParser()  # parse command line arguments
parser.add_argument("strategy", help="Which strategy to run", type=str)
args = parser.parse_args()

if not args.strategy in strategies:
    print("Invalid strategy, must select one of {}".format(strategies.keys()))
    sys.exit()

cerebro.addstrategy(strategy=strategies[args.strategy])
cerebro.run()
cerebro.plot()  # plot the chart
Пример #8
0
cerebro = bt.Cerebro()

prices = pd.read_csv('data/spy_2000-2020.csv', index_col='Date', parse_dates=True)

# initialize the Cerebro engine
cerebro = Cerebro()
cerebro.broker.setcash(100000)

# add OHLC data feed
feed = bt.feeds.PandasData(dataname=prices)
cerebro.adddata(feed)

strategies = {
    "golden_cross": GoldenCross,
    "buy_hold": BuyHold
}

# parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("strategy", help="Which strategy to run", type=str)
args = parser.parse_args()

if not args.strategy in strategies:
    print("Invalid strategy, must select one of {}".format(strategies.keys()))
    sys.exit()

cerebro.addstrategy(strategy=strategies[args.strategy])
cerebro.run()
cerebro.plot()