当前位置: 首页>>代码示例>>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;未经允许,请勿转载。