Python backtrader.Cerebro() Examples

The following are 30 code examples of backtrader.Cerebro(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module backtrader , or try the search function .
Example #1
Source File: test_issue30.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
def test_github_issue30():
    cerebro = bt.Cerebro()

    cerebro.addstrategy(MyStrategy)

    data = bt.feeds.YahooFinanceCSVData(
        dataname=getdatadir("orcl-1995-2014.txt"),
        fromdate=datetime.datetime(2000, 1, 1),
        todate=datetime.datetime(2001, 2, 28),
        reverse=False,
    )
    cerebro.adddata(data)
    cerebro.addanalyzer(bt.analyzers.SharpeRatio)

    cerebro.run()

    b = backtrader_plotting.Bokeh(filename='chart.html', style='bar', scheme=Tradimo(), output_mode='memory')

    figs = cerebro.plot(b)

    assert isinstance(figs[0][0], backtrader_plotting.bokeh.bokeh.FigurePage)
    assert len(figs[0][0].figure_envs) == 4
    assert len(figs[0][0].analyzers) == 1 
Example #2
Source File: order-execution.py    From backtrader with GNU General Public License v3.0 6 votes vote down vote up
def runstrat():
    args = parse_args()

    cerebro = bt.Cerebro()

    data = getdata(args)
    cerebro.adddata(data)

    cerebro.addstrategy(
        OrderExecutionStrategy,
        exectype=args.exectype,
        perc1=args.perc1,
        perc2=args.perc2,
        valid=args.valid,
        smaperiod=args.smaperiod
    )
    cerebro.run()

    if args.plot:
        cerebro.plot(numfigs=args.numfigs, style=args.plotstyle) 
Example #3
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
def cerebro() -> bt.Cerebro:
    cerebro = bt.Cerebro()

    datapath = getdatadir('orcl-1995-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.addanalyzer(bt.analyzers.TradeAnalyzer)
    cerebro.addanalyzer(bt.analyzers.SharpeRatio, compression=2)
    cerebro.addanalyzer(bt.analyzers.TimeDrawDown)

    return cerebro 
Example #4
Source File: ksignal.py    From backtrader with GNU General Public License v3.0 6 votes vote down vote up
def runstrat(pargs=None):
    args = parse_args(pargs)

    cerebro = bt.Cerebro()
    cerebro.broker.set_cash(args.cash)
    cerebro.broker.set_coc(args.coc)
    data0 = bt.feeds.YahooFinanceData(
        dataname=args.data,
        fromdate=datetime.datetime.strptime(args.fromdate, '%Y-%m-%d'),
        todate=datetime.datetime.strptime(args.todate, '%Y-%m-%d'),
        round=False)

    cerebro.adddata(data0)

    cerebro.addsizer(bt.sizers.FixedSize, stake=args.stake)
    cerebro.addstrategy(TheStrategy, **(eval('dict(' + args.strat + ')')))
    cerebro.addobserver(bt.observers.Value)
    cerebro.addobserver(bt.observers.Trades)
    cerebro.addobserver(bt.observers.BuySell, barplot=True)

    cerebro.run(stdstats=False)
    if args.plot:
        cerebro.plot(**(eval('dict(' + args.plot + ')'))) 
Example #5
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: sigsmacross.py    From backtrader with GNU General Public License v3.0 6 votes vote down vote up
def runstrat(pargs=None):
    args = parse_args(pargs)

    cerebro = bt.Cerebro()
    cerebro.broker.set_cash(args.cash)

    data0 = bt.feeds.YahooFinanceData(
        dataname=args.data,
        fromdate=datetime.datetime.strptime(args.fromdate, '%Y-%m-%d'),
        todate=datetime.datetime.strptime(args.todate, '%Y-%m-%d'))
    cerebro.adddata(data0)

    cerebro.addstrategy(SmaCross, **(eval('dict(' + args.strat + ')')))
    cerebro.addsizer(bt.sizers.FixedSize, stake=args.stake)

    cerebro.run()
    if args.plot:
        cerebro.plot(**(eval('dict(' + args.plot + ')'))) 
Example #7
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #8
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
def test_optimize(cerebro: bt.Cerebro):
    cerebro.optstrategy(bt.strategies.MA_CrossOver, slow=[5, 10, 20], fast=[5, 10, 20])
    res = cerebro.run(optreturn=True)

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

    browser = OptBrowser(b, res)
    model = browser.build_optresult_model()
    # browser.start()

    def count_children(obj):
        numo = 1
        if hasattr(obj, "children"):
            numo = count_children(obj.children)
        if hasattr(obj, '__len__'):
            numo += len(obj)
        return numo

    num = count_children(model)

    assert num == 3 
Example #9
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
def test_optimize_no_optreturn(cerebro_no_optreturn: bt.Cerebro):
    cerebro_no_optreturn.optstrategy(bt.strategies.MA_CrossOver, slow=[5, 10, 20], fast=[5, 10, 20])
    res = cerebro_no_optreturn.run()

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

    browser = OptBrowser(b, res)
    model = browser.build_optresult_model()
    #browser.start()

    def count_children(obj):
        numo = 1
        if hasattr(obj, "children"):
            numo = count_children(obj.children)
        if hasattr(obj, '__len__'):
            numo += len(obj)
        return numo

    num = count_children(model)

    assert num == 3 
Example #10
Source File: test_optional_fetch_balance.py    From bt-ccxt-store with MIT License 6 votes vote down vote up
def backtesting(config):
    cerebro = Cerebro()

    cerebro.addstrategy(TestStrategy)

    cerebro.adddata(CCXTFeed(exchange='binance',
                             dataname='BNB/USDT',
                             timeframe=TimeFrame.Minutes,
                             fromdate=datetime(2019, 1, 1, 0, 0),
                             todate=datetime(2019, 1, 1, 0, 2),
                             compression=1,
                             ohlcv_limit=2,
                             currency='BNB',
                             config=config,
                             retries=5))

    finished_strategies = cerebro.run()
    return finished_strategies 
Example #11
Source File: close-minute.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat():
    args = parse_args()

    cerebro = bt.Cerebro()
    cerebro.adddata(getdata(args))
    cerebro.addstrategy(St)
    if args.eosbar:
        cerebro.broker.seteosbar(True)

    cerebro.run() 
Example #12
Source File: tablibsartest.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    dkwargs = dict()
    if args.fromdate:
        fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
        dkwargs['fromdate'] = fromdate

    if args.todate:
        todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
        dkwargs['todate'] = todate

    data0 = bt.feeds.YahooFinanceCSVData(dataname=args.data0, **dkwargs)
    cerebro.adddata(data0)

    cerebro.addstrategy(TALibStrategy)
    cerebro.run(runonce=not args.use_next, stdstats=False)
    if args.plot:
        pkwargs = dict(style='candle')
        if args.plot is not True:  # evals to True but is not True
            npkwargs = eval('dict(' + args.plot + ')')  # args were passed
            pkwargs.update(npkwargs)

        cerebro.plot(**pkwargs) 
Example #13
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def test_std_backtest_volume_subplot(cerebro: bt.Cerebro):
    cerebro.addstrategy(bt.strategies.MA_CrossOver)
    cerebro.run()

    s = backtrader_plotting.schemes.Blackly()
    s.voloverlay = False
    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, 5) 
Example #14
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #15
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def test_std_backtest_tabs_multi(cerebro: bt.Cerebro):
    cerebro.addstrategy(bt.strategies.MA_CrossOver)
    cerebro.run()

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

    assert len(figs) == 1
    assert_num_tabs(figs, 5)
    assert_num_figures(figs, 4) 
Example #16
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #17
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def test_optimize_2strat(cerebro: bt.Cerebro):
    cerebro.optstrategy(bt.strategies.MA_CrossOver, slow=[5, 10, 20], fast=[5, 10, 20])
    cerebro.optstrategy(ToggleStrategy, modbuy=[12, 15], modsell=[17, 19])
    res = cerebro.run()

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

    browser = OptBrowser(b, res)

    with pytest.raises(RuntimeError):
        browser.build_optresult_model()
    # browser.start() 
Example #18
Source File: test_backtest.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def test_ordered_optimize(cerebro: bt.Cerebro):
    cerebro.optstrategy(bt.strategies.MA_CrossOver, slow=[20], fast=[5, 10, 20])
    res = cerebro.run(optreturn=True)

    def df(optresults):
        a = [x.analyzers.tradeanalyzer.get_analysis() for x in optresults]
        return sum([x.pnl.gross.total if 'pnl' in x else 0 for x in a])

    usercolumns = {
        'Profit & Loss': df,
    }

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

    browser = OptBrowser(b, res, usercolumns=usercolumns, sortcolumn='Profit & Loss')
    model = browser.build_optresult_model()
    # browser.start()

    def count_children(obj):
        numo = 1
        if hasattr(obj, "children"):
            numo = count_children(obj.children)
        if hasattr(obj, '__len__'):
            numo += len(obj)
        return numo

    num = count_children(model)

    assert num == 3 
Example #19
Source File: plotlistener.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **kwargs):
        self._cerebro: Optional[bt.Cerebro] = None
        self._webapp = BokehWebapp(self.p.title,
                                   'basic.html.j2',
                                   self.p.scheme,
                                   self._bokeh_cb_build_root_model,
                                   on_session_destroyed=self._on_session_destroyed,
                                   port=self.p.http_port)
        self._lock = Lock()
        self._datastore = None
        self._clients: Dict[str, LiveClient] = {}
        self._bokeh_kwargs = kwargs
        self._bokeh = self._create_bokeh()
        self._patch_pkgs = defaultdict(lambda: []) 
Example #20
Source File: signals-strategy.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()
    cerebro.broker.set_cash(args.cash)

    dkwargs = dict()
    if args.fromdate is not None:
        fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
        dkwargs['fromdate'] = fromdate

    if args.todate is not None:
        todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
        dkwargs['todate'] = todate

    # if dataset is None, args.data has been given
    data = bt.feeds.BacktraderCSVData(dataname=args.data, **dkwargs)
    cerebro.adddata(data)

    cerebro.add_signal(MAINSIGNALS[args.signal],
                       SMACloseSignal, period=args.smaperiod)

    if args.exitsignal is not None:
        cerebro.add_signal(EXITSIGNALS[args.exitsignal],
                           SMAExitSignal,
                           p1=args.exitperiod,
                           p2=args.smaperiod)

    cerebro.run()
    if args.plot:
        pkwargs = dict(style='bar')
        if args.plot is not True:  # evals to True but is not True
            npkwargs = eval('dict(' + args.plot + ')')  # args were passed
            pkwargs.update(npkwargs)

        cerebro.plot(**pkwargs) 
Example #21
Source File: psar.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    # Data feed kwargs
    kwargs = dict()

    # Parse from/to-date
    dtfmt, tmfmt = '%Y-%m-%d', 'T%H:%M:%S'
    for a, d in ((getattr(args, x), x) for x in ['fromdate', 'todate']):
        if a:
            strpfmt = dtfmt + tmfmt * ('T' in a)
            kwargs[d] = datetime.datetime.strptime(a, strpfmt)

    # Data feed
    data0 = bt.feeds.BacktraderCSVData(dataname=args.data0, **kwargs)
    cerebro.adddata(data0)

    # Broker
    cerebro.broker = bt.brokers.BackBroker(**eval('dict(' + args.broker + ')'))

    # Sizer
    cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))

    # Strategy
    cerebro.addstrategy(St, **eval('dict(' + args.strat + ')'))

    # Execute
    cerebro.run(**eval('dict(' + args.cerebro + ')'))

    if args.plot:  # Plot if requested to
        cerebro.plot(**eval('dict(' + args.plot + ')')) 
Example #22
Source File: bracket.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    # Data feed kwargs
    kwargs = dict()

    # Parse from/to-date
    dtfmt, tmfmt = '%Y-%m-%d', 'T%H:%M:%S'
    for a, d in ((getattr(args, x), x) for x in ['fromdate', 'todate']):
        if a:
            strpfmt = dtfmt + tmfmt * ('T' in a)
            kwargs[d] = datetime.datetime.strptime(a, strpfmt)

    # Data feed
    data0 = bt.feeds.BacktraderCSVData(dataname=args.data0, **kwargs)
    cerebro.adddata(data0)

    # Broker
    cerebro.broker = bt.brokers.BackBroker(**eval('dict(' + args.broker + ')'))

    # Sizer
    cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))

    # Strategy
    cerebro.addstrategy(St, **eval('dict(' + args.strat + ')'))

    # Execute
    cerebro.run(**eval('dict(' + args.cerebro + ')'))

    if args.plot:  # Plot if requested to
        cerebro.plot(**eval('dict(' + args.plot + ')')) 
Example #23
Source File: volumefilling.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat():
    args = parse_args()

    datakwargs = dict()
    if args.fromdate:
        fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
        datakwargs['fromdate'] = fromdate

    if args.todate:
        todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
        datakwargs['todate'] = todate

    data = bt.feeds.BacktraderCSVData(dataname=args.data, **datakwargs)

    cerebro = bt.Cerebro()
    cerebro.adddata(data)

    cerebro.broker.set_cash(args.cash)
    if args.filler is not None:
        fillerkwargs = dict()
        if args.filler_args is not None:
            fillerkwargs = eval('dict(' + args.filler_args + ')')

        filler = FILLERS[args.filler](**fillerkwargs)
        cerebro.broker.set_filler(filler)

    cerebro.addstrategy(St, stakeperc=args.stakeperc, opbreak=args.opbreak)

    cerebro.run()
    if args.plot:
        cerebro.plot(style='bar') 
Example #24
Source File: bidask.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrategy():
    args = parse_args()

    cerebro = bt.Cerebro()  # Create a cerebro

    data = BidAskCSV(dataname=args.data, dtformat=args.dtformat)
    cerebro.adddata(data)  # Add the 1st data to cerebro
    # Add the strategy to cerebro
    cerebro.addstrategy(St, sma=args.sma, period=args.period)
    cerebro.run() 
Example #25
Source File: trail.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    # Data feed kwargs
    kwargs = dict()

    # Parse from/to-date
    dtfmt, tmfmt = '%Y-%m-%d', 'T%H:%M:%S'
    for a, d in ((getattr(args, x), x) for x in ['fromdate', 'todate']):
        if a:
            strpfmt = dtfmt + tmfmt * ('T' in a)
            kwargs[d] = datetime.datetime.strptime(a, strpfmt)

    # Data feed
    data0 = bt.feeds.BacktraderCSVData(dataname=args.data0, **kwargs)
    cerebro.adddata(data0)

    # Broker
    cerebro.broker = bt.brokers.BackBroker(**eval('dict(' + args.broker + ')'))

    # Sizer
    cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))

    # Strategy
    cerebro.addstrategy(St, **eval('dict(' + args.strat + ')'))

    # Execute
    cerebro.run(**eval('dict(' + args.cerebro + ')'))

    if args.plot:  # Plot if requested to
        cerebro.plot(**eval('dict(' + args.plot + ')')) 
Example #26
Source File: data-pandas-optix.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat():
    args = parse_args()

    # Create a cerebro entity
    cerebro = bt.Cerebro(stdstats=False)

    # Add a strategy
    cerebro.addstrategy(StrategyOptix)

    # Get a pandas dataframe
    datapath = ('../../datas/2006-day-001-optix.txt')

    # Simulate the header row isn't there if noheaders requested
    skiprows = 1 if args.noheaders else 0
    header = None if args.noheaders else 0

    dataframe = pandas.read_csv(datapath,
                                skiprows=skiprows,
                                header=header,
                                parse_dates=True,
                                index_col=0)

    if not args.noprint:
        print('--------------------------------------------------')
        print(dataframe)
        print('--------------------------------------------------')

    # Pass it to the backtrader datafeed and add it to the cerebro
    data = PandasDataOptix(dataname=dataframe)

    cerebro.adddata(data)

    # Run over everything
    cerebro.run()

    # Plot the result
    if not args.noplot:
        cerebro.plot(style='bar') 
Example #27
Source File: calmar-test.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    # Data feed kwargs
    kwargs = dict()

    # Parse from/to-date
    dtfmt, tmfmt = '%Y-%m-%d', 'T%H:%M:%S'
    for a, d in ((getattr(args, x), x) for x in ['fromdate', 'todate']):
        if a:
            strpfmt = dtfmt + tmfmt * ('T' in a)
            kwargs[d] = datetime.datetime.strptime(a, strpfmt)

    # Data feed
    data0 = bt.feeds.YahooFinanceCSVData(dataname=args.data0, **kwargs)
    cerebro.adddata(data0)

    # Broker
    cerebro.broker = bt.brokers.BackBroker(**eval('dict(' + args.broker + ')'))

    cerebro.addanalyzer(bt.analyzers.Calmar)
    # Sizer
    cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))

    # Strategy
    cerebro.addstrategy(St, **eval('dict(' + args.strat + ')'))

    # Execute
    st0 = cerebro.run(**eval('dict(' + args.cerebro + ')'))[0]
    i = 1
    for k, v in st0.analyzers.calmar.get_analysis().items():
        print(i, ': '.join((str(k), str(v))))
        i += 1

    if args.plot:  # Plot if requested to
        cerebro.plot(**eval('dict(' + args.plot + ')')) 
Example #28
Source File: memory-savings.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat():
    args = parse_args()

    cerebro = bt.Cerebro()
    data = btfeeds.YahooFinanceCSVData(dataname=args.data)
    cerebro.adddata(data)
    cerebro.addstrategy(
        St, datalines=args.datalines, lendetails=args.lendetails)

    cerebro.run(runonce=False, exactbars=args.save)
    if args.plot:
        cerebro.plot(style='bar') 
Example #29
Source File: partial-plot.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    # Data feed kwargs
    kwargs = dict()

    # Parse from/to-date
    dtfmt, tmfmt = '%Y-%m-%d', 'T%H:%M:%S'
    for a, d in ((getattr(args, x), x) for x in ['fromdate', 'todate']):
        if a:
            strpfmt = dtfmt + tmfmt * ('T' in a)
            kwargs[d] = datetime.datetime.strptime(a, strpfmt)

    # Data feed
    data0 = bt.feeds.BacktraderCSVData(dataname=args.data0, **kwargs)
    cerebro.adddata(data0)

    cerebro.resampledata(data0, timeframe=bt.TimeFrame.Weeks)

    # Broker
    cerebro.broker = bt.brokers.BackBroker(**eval('dict(' + args.broker + ')'))

    # Sizer
    cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))

    # Strategy
    cerebro.addstrategy(St, **eval('dict(' + args.strat + ')'))

    # Execute
    cerebro.run(**eval('dict(' + args.cerebro + ')'))

    if args.plot:  # Plot if requested to
        cerebro.plot(**eval('dict(' + args.plot + ')')) 
Example #30
Source File: rollover.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    fcodes = ['199FESXM4', '199FESXU4', '199FESXZ4', '199FESXH5', '199FESXM5']
    store = bt.stores.VChartFile()
    ffeeds = [store.getdata(dataname=x) for x in fcodes]

    rollkwargs = dict()
    if args.checkdate:
        rollkwargs['checkdate'] = checkdate

        if args.checkcondition:
            rollkwargs['checkcondition'] = checkvolume

    if not args.no_cerebro:
        if args.rollover:
            cerebro.rolloverdata(name='FESX', *ffeeds, **rollkwargs)
        else:
            cerebro.chaindata(name='FESX', *ffeeds)
    else:
        drollover = bt.feeds.RollOver(*ffeeds, dataname='FESX', **rollkwargs)
        cerebro.adddata(drollover)

    cerebro.addstrategy(TheStrategy)
    cerebro.run(stdstats=False)

    if args.plot:
        pkwargs = dict(style='bar')
        if args.plot is not True:  # evals to True but is not True
            npkwargs = eval('dict(' + args.plot + ')')  # args were passed
            pkwargs.update(npkwargs)

        cerebro.plot(**pkwargs)