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


Python backtrader.Strategy方法代碼示例

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


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

示例1: __init__

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def __init__(self):
        # To control operation entries
        self.orderid = list()
        self.order = None

        self.counttostop = 0
        self.datastatus = 0

        self.last_pos = None
        self.last_value = 0

        # Create SMA on 2nd data
        self.sma = bt.indicators.MovAv.SMA(self.data, period=self.p.smaperiod)

        print('--------------------------------------------------')
        print('Strategy Created')
        print('--------------------------------------------------') 
開發者ID:alpacahq,項目名稱:alpaca-backtrader-api,代碼行數:19,代碼來源:strategy_sample_code.py

示例2: set_broker_datalines

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def set_broker_datalines(self):
        """
        The following broker datalines are the baseline for any strategy.
        Any other custom data lines, should be explicitly defined by overriding this method with a call to super().
        Any new data line should have a corresponding method of form 'get_broker_{}'.
        Invoked once by Strategy.__init__().
        Data can then be retrieved by self.broker_stat[]
        """
        self.broker_datalines = [
            'cash',
            'value',
            'exposure',
            'drawdown',
            'realized_pnl',
            'unrealized_pnl',
        ] 
開發者ID:Kismuz,項目名稱:btgym,代碼行數:18,代碼來源:base.py

示例3: __init__

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def __init__(self, strategy: bt.Strategy, cds: ColumnDataSource, hoverc: HoverContainer, start, end, scheme, master, plotorder, is_multidata):
        self._strategy = strategy
        self._cds: ColumnDataSource = cds
        self._scheme = scheme
        self._start = start
        self._end = end
        self.figure: figure = None
        self._hover_line_set = False
        self._hover: Optional[HoverTool] = None
        self._hoverc = hoverc
        self._coloridx = collections.defaultdict(lambda: -1)
        self.master = master
        self.plottab = None
        self.plotorder = plotorder
        self.datas = []  # list of all datas that have been plotted to this figure
        self._is_multidata = is_multidata
        self._tradingdomain = None
        self._init_figure() 
開發者ID:verybadsoldier,項目名稱:backtrader_plotting,代碼行數:20,代碼來源:figureenvelope.py

示例4: _get_datas

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def _get_datas(strategy: bt.Strategy) -> str:
    md = '\n# Data Feeds\n'

    for data in strategy.datas:
        md += f'## {data.__class__.__name__}\n'

        tabdata = {
            'DataName:': str(data._dataname).replace("|", "\\|"),
            'Timezone:': data._tz,
            'Number of bars:': len(data),
            'Bar Length:': f"{data._compression} {bt.TimeFrame.getname(data._timeframe, data._compression)}",
        }

        # live trading does not have valid data parameters (other datas might also not have)
        if not math.isinf(data.fromdate):
            tabdata['Time From:'] = bt.num2date(data.fromdate)

        if not math.isinf(data.todate):
            tabdata['Time To:'] = bt.num2date(data.todate)

        md += _get_table(['Property', 'Value'], tabdata)

    return md 
開發者ID:verybadsoldier,項目名稱:backtrader_plotting,代碼行數:25,代碼來源:metadata.py

示例5: test_std_backtest_ind_on_line

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

示例6: run

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def run(self, symbols, cash, strategy, **params):
        path_dir = os.path.dirname(os.path.realpath(__file__))
        # Setup Cerebro
        cerebro = ob.Backtest.setup_cerebro(cash)
        # Add Data
        for s in symbols:
            df = pd.read_csv(os.path.join(path_dir, '{}.csv'.format(s)), parse_dates=True, index_col=0)
            data = bt.feeds.PandasData(dataname=df)
            cerebro.adddata(data)
        # Strategy
        cerebro.addstrategy(strategy, **params)
        # Backtest
        results = cerebro.run()
        pnl = cerebro.broker.getvalue() - cash

        return pnl, results[0] 
開發者ID:OmegaTrading,項目名稱:OmegaUI,代碼行數:18,代碼來源:test_backtest.py

示例7: set_datalines

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def set_datalines(self):
        """
        Default datalines are: Open, Low, High, Close, Volume.
        Any other custom data lines, indicators, etc. should be explicitly defined by overriding this method.
        Invoked once by Strategy.__init__().
        """
        pass 
開發者ID:Kismuz,項目名稱:btgym,代碼行數:9,代碼來源:base.py

示例8: main

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

示例9: __init__

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def __init__(self):
        # To control operation entries
        self.orderid = list()
        self.order = None

        self.counttostop = 0
        self.datastatus = 0

        # Create SMA on 2nd data
        self.sma = bt.indicators.MovAv.SMA(self.data, period=self.p.smaperiod)

        print('--------------------------------------------------')
        print('Strategy Created')
        print('--------------------------------------------------') 
開發者ID:mementum,項目名稱:backtrader,代碼行數:16,代碼來源:ibtest.py

示例10: runstrat

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

示例11: runstrat

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

示例12: runstrat

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def runstrat():
    args = parse_args()

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

    # Add a strategy
    cerebro.addstrategy(bt.Strategy)

    # Get the dates from the args
    fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
    todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')

    data = btfeeds.YahooFinanceData(
        dataname=args.data,
        fromdate=fromdate,
        todate=todate)

    # Add the resample data instead of the original
    cerebro.adddata(data)

    # Add a simple moving average if requirested
    cerebro.addindicator(btind.SMA, period=args.period)

    # Add a writer with CSV
    if args.writer:
        cerebro.addwriter(bt.WriterFile, csv=args.wrcsv)

    # Run over everything
    cerebro.run()

    # Plot if requested
    if args.plot:
        cerebro.plot(style='bar', numfigs=args.numfigs, volume=False) 
開發者ID:mementum,項目名稱:backtrader,代碼行數:36,代碼來源:yahoo-test.py

示例13: next

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def next(self):
        print('Strategy len {} datetime {}'.format(
            len(self), self.datetime.date()), end=' ')

        print('Data0 len {} datetime {}'.format(
            len(self.data0), self.data0.datetime.date()), end=' ')

        if len(self.data1):
            print('Data1 len {} datetime {}'.format(
                len(self.data1), self.data1.datetime.date()))
        else:
            print() 
開發者ID:mementum,項目名稱:backtrader,代碼行數:14,代碼來源:tcal.py

示例14: next

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def next(self):
        print('Strategy len {} datetime {}'.format(
            len(self), self.datetime.datetime()), end=' ')

        print('Data0 len {} datetime {}'.format(
            len(self.data0), self.data0.datetime.datetime()), end=' ')

        if len(self.data1):
            print('Data1 len {} datetime {}'.format(
                len(self.data1), self.data1.datetime.datetime()))
        else:
            print() 
開發者ID:mementum,項目名稱:backtrader,代碼行數:14,代碼來源:tcal-intra.py

示例15: runstrat

# 需要導入模塊: import backtrader [as 別名]
# 或者: from backtrader import Strategy [as 別名]
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    # Data feed kwargs
    kwargs = dict(
        timeframe=bt.TimeFrame.Days,
        compression=1,
        sessionstart=datetime.time(9, 0),
        sessionend=datetime.time(17, 30),
    )

    # 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,代碼行數:40,代碼來源:scheduled.py


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