當前位置: 首頁>>代碼示例>>Python>>正文


Python backtrader.Cerebro方法代碼示例

本文整理匯總了Python中backtrader.Cerebro方法的典型用法代碼示例。如果您正苦於以下問題:Python backtrader.Cerebro方法的具體用法?Python backtrader.Cerebro怎麽用?Python backtrader.Cerebro使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在backtrader的用法示例。


在下文中一共展示了backtrader.Cerebro方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: backtesting

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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 
開發者ID:Dave-Vallance,項目名稱:bt-ccxt-store,代碼行數:20,代碼來源:test_optional_fetch_balance.py

示例2: dopostinit

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
def dopostinit(cls, _obj, *args, **kwargs):
            # Go to parent
            res = super(_MetaTALibIndicator, cls).dopostinit(_obj,
                                                             *args, **kwargs)
            _obj, args, kwargs = res

            # Get the minimum period by using the abstract interface and params
            _obj._tabstract.set_function_args(**_obj.p._getkwargs())
            _obj._lookback = lookback = _obj._tabstract.lookback + 1
            _obj.updateminperiod(lookback)
            if _obj._unstable:
                _obj._lookback = 0

            elif cls.__name__ in cls._KNOWN_UNSTABLE:
                _obj._lookback = 0

            cerebro = bt.metabase.findowner(_obj, bt.Cerebro)
            tafuncinfo = _obj._tabstract.info
            _obj._tafunc = getattr(talib, tafuncinfo['name'], None)
            return _obj, args, kwargs  # return the object and args 
開發者ID:mementum,項目名稱:backtrader,代碼行數:22,代碼來源:talib.py

示例3: runstrat

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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 + ')'))) 
開發者ID:mementum,項目名稱:backtrader,代碼行數:25,代碼來源:ksignal.py

示例4: runstrat

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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 + ')'))) 
開發者ID:mementum,項目名稱:backtrader,代碼行數:20,代碼來源:sigsmacross.py

示例5: runstrat

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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) 
開發者ID:mementum,項目名稱:backtrader,代碼行數:22,代碼來源:order-execution.py

示例6: cerebro

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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 
開發者ID:verybadsoldier,項目名稱:backtrader_plotting,代碼行數:20,代碼來源:test_backtest.py

示例7: test_std_backtest_2datas

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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) 
開發者ID:verybadsoldier,項目名稱:backtrader_plotting,代碼行數:23,代碼來源:test_backtest.py

示例8: test_std_backtest_ind_subplot

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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) 
開發者ID:verybadsoldier,項目名稱:backtrader_plotting,代碼行數:19,代碼來源:test_backtest.py

示例9: test_optimize

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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 
開發者ID:verybadsoldier,項目名稱:backtrader_plotting,代碼行數:23,代碼來源:test_backtest.py

示例10: test_optimize_no_optreturn

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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 
開發者ID:verybadsoldier,項目名稱:backtrader_plotting,代碼行數:24,代碼來源:test_backtest.py

示例11: test_github_issue30

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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 
開發者ID:verybadsoldier,項目名稱:backtrader_plotting,代碼行數:25,代碼來源:test_issue30.py

示例12: runstrat

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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 + ')')) 
開發者ID:mementum,項目名稱:backtrader,代碼行數:35,代碼來源:lrsi-test.py

示例13: main

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
def main():
    class TestStrategy(bt.Strategy):
        def __init__(self):
            self.next_runs = 0

        def next(self, dt=None):
            dt = dt or self.datas[0].datetime.datetime(0)
            print('%s closing price: %s' % (dt.isoformat(), self.datas[0].close[0]))
            self.next_runs += 1

    cerebro = bt.Cerebro()

    cerebro.addstrategy(TestStrategy)

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

                             # 'apiKey' and 'secret' are skipped
                             config={'enableRateLimit': True, 'nonce': lambda: str(int(time.time() * 1000))}))

    # Run the strategy
    cerebro.run() 
開發者ID:Dave-Vallance,項目名稱:bt-ccxt-store,代碼行數:32,代碼來源:backtesting.py

示例14: donew

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
def donew(cls, *args, **kwargs):
        _obj, args, kwargs = super(MetaStrategy, cls).donew(*args, **kwargs)

        # Find the owner and store it
        _obj.env = _obj.cerebro = cerebro = findowner(_obj, bt.Cerebro)
        _obj._id = cerebro._next_stid()

        return _obj, args, kwargs 
開發者ID:mementum,項目名稱:backtrader,代碼行數:10,代碼來源:strategy.py

示例15: runstrat

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Cerebro [as 別名]
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)

    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
    StClass = APPROACHES[args.approach]
    cerebro.addstrategy(StClass, **eval('dict(' + args.strat + ')'))

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

    if args.plot:  # Plot if requested to
        cerebro.plot(**eval('dict(' + args.plot + ')')) 
開發者ID:mementum,項目名稱:backtrader,代碼行數:35,代碼來源:stop-loss-approaches.py


注:本文中的backtrader.Cerebro方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。