Python backtrader.Strategy() Examples

The following are 30 code examples of backtrader.Strategy(). 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: strategy_sample_code.py    From alpaca-backtrader-api with Apache License 2.0 6 votes vote down vote up
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('--------------------------------------------------') 
Example #2
Source File: metadata.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: base.py    From btgym with GNU Lesser General Public License v3.0 6 votes vote down vote up
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',
        ] 
Example #4
Source File: base.py    From btgym with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: bokeh.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def plot_and_generate_optmodel(self, obj: Union[bt.Strategy, bt.OptReturn]):
        self._reset()
        self.plot(obj)

        # we support only one strategy at a time so pass fixed zero index
        # if we ran optresults=False then we have a full strategy object -> pass it to get full plot
        return self.generate_model(0) 
Example #6
Source File: yahoo-test.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(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) 
Example #7
Source File: bokeh.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def _configure_plotting(self, strategy: bt.Strategy):
        datas, inds, obs = strategy.datas, strategy.getindicators(), strategy.getobservers()

        for objs in [datas, inds, obs]:
            for idx, obj in enumerate(objs):
                self._configure_plotobject(obj, idx, strategy) 
Example #8
Source File: bokeh.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, obj: Union[bt.Strategy, bt.OptReturn]):
        self.figure_envs: List[FigureEnvelope] = []
        self.strategy: Optional[bt.Strategy] = obj if isinstance(obj, bt.Strategy) else None
        self.cds: Optional[ColumnDataSource] = ColumnDataSource(data=dict(datetime=np.array([], dtype=np.datetime64), index=np.array([], np.float64)))
        self.analyzers: List[bt.Analyzer, bt.MetaStrategy, Optional[bt.AutoInfoClass]] = []
        self.model: Optional[Model] = None  # the whole generated model will we attached here after plotting 
Example #9
Source File: label_resolver.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def strategy2shortname(strategy: bt.Strategy) -> str:
    return strategy.plotinfo.plotname or strategy.__class__.__name__ 
Example #10
Source File: cheat-on-open.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 #11
Source File: order-history.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)

    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
    if not args.order_history:
        cerebro.addstrategy(SmaCross, **eval('dict(' + args.strat + ')'))
    else:
        cerebro.addstrategy(St, **eval('dict(' + args.strat + ')'))
        cerebro.add_order_history(ORDER_HISTORY, notify=True)

    cerebro.addanalyzer(bt.analyzers.TimeReturn, timeframe=bt.TimeFrame.Months)
    cerebro.addanalyzer(bt.analyzers.TimeReturn, timeframe=bt.TimeFrame.Years)
    cerebro.addanalyzer(bt.analyzers.TradeAnalyzer)

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

    if args.plot:  # Plot if requested to
        cerebro.plot(**eval('dict(' + args.plot + ')')) 
Example #12
Source File: order-history.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        print('Creating Empty Strategy')
        pass 
Example #13
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 #14
Source File: psar-intraday.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(
        timeframe=bt.TimeFrame.Minutes,
        compression=5,
    )

    # 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.Minutes, compression=15)

    # 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 #15
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 #16
Source File: relative-volume.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description='MultiData Strategy')

    parser.add_argument('--data', '-d',
                        default='../../datas/2006-01-02-volume-min-001.txt',
                        help='data to add to the system')

    parser.add_argument('--prestart',
                        default='08:00',
                        help='Start time for the Session Filter')

    parser.add_argument('--start',
                        default='09:15',
                        help='Start time for the Session Filter')

    parser.add_argument('--end', '-te',
                        default='17:15',
                        help='End time for the Session Filter')

    parser.add_argument('--fromdate', '-f',
                        default='2006-01-01',
                        help='Starting date in YYYY-MM-DD format')

    parser.add_argument('--todate', '-t',
                        default='2006-12-31',
                        help='Starting date in YYYY-MM-DD format')

    parser.add_argument('--writer', '-w', action='store_true',
                        help='Add a writer to cerebro')

    parser.add_argument('--wrcsv', '-wc', action='store_true',
                        help='Enable CSV Output in the writer')

    parser.add_argument('--plot', '-p', action='store_true',
                        help='Plot the read data')

    parser.add_argument('--numfigs', '-n', default=1,
                        help='Plot using numfigs figures')

    return parser.parse_args() 
Example #17
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 #18
Source File: bokeh.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def plot(self, obj: Union[bt.Strategy, bt.OptReturn], figid=0, numfigs=1, iplot=True, start=None, end=None, use=None, fill_data=True, tradingdomain=None, **kwargs):
        """Called by backtrader to plot either a strategy or an optimization result."""

        # prepare new FigurePage
        fp = FigurePage(obj)
        self.figurepages.append(fp)
        self._current_fig_idx = len(self.figurepages) - 1
        self._is_optreturn = isinstance(obj, bt.OptReturn)

        if isinstance(obj, bt.Strategy):
            # only configure plotting for regular backtesting (not for optimization)
            self._configure_plotting(obj)

        if numfigs > 1:
            raise Exception("numfigs must be 1")
        if use is not None:
            raise Exception("Different backends by 'use' not supported")

        self._iplot = iplot and 'ipykernel' in sys.modules

        if isinstance(obj, bt.Strategy):
            self._blueprint_strategy(obj, start, end, tradingdomain, **kwargs)
            if fill_data:
                df: pd.DataFrame = self.build_strategy_data(obj, start, end)

                new_cds = ColumnDataSource.from_df(df)
                append_cds(fp.cds, new_cds)
        elif isinstance(obj, bt.OptReturn):
            # for optresults we only plot analyzers!
            self._cur_figurepage.analyzers += [a for _, a in obj.analyzers.getitems()]
        else:
            raise Exception(f'Unsupported plot source object: {str(type(obj))}')

        return [self._cur_figurepage] 
Example #19
Source File: figureenvelope.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #20
Source File: utils.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def find_by_plotid(strategy: bt.Strategy, plotid):
    objs = itertools.chain(strategy.datas, strategy.getindicators(), strategy.getobservers())
    founds = []
    for obj in objs:
        if getattr(obj.plotinfo, 'plotid', None) == plotid:
            founds.append(obj)

    num_results = len(founds)
    if num_results == 0:
        return None
    elif num_results == 1:
        return founds[0]
    else:
        raise RuntimeError(f'Found multiple objects with plotid "{plotid}"') 
Example #21
Source File: metadata.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def _get_strategy(strategy: bt.Strategy) -> str:
    md = f'\n# Strategy: {strategy.__class__.__name__}\n'

    md += _get_parameter_table(strategy.params)

    md += '## Indicators:\n\n'
    for i in strategy.getindicators():
        md += f'### {i.__class__.__name__} @ {indicator2fullid(i)}\n\n'
        # md += f'Data: \n'
        md += _get_parameter_table(i.params)

    md += 'Source Code:\n'
    md += f'\n```\n{inspect.getsource(strategy.__class__)}\n```\n\n'

    return md 
Example #22
Source File: metadata.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def _get_analyzers(strategy: bt.Strategy) -> str:
    if len(strategy.analyzers) == 0:
        return ""

    md = '\n# Analyzers\n'

    for a in strategy.analyzers:
        md += f'## {a.__class__.__name__}\n'
        md += _get_parameter_table(a.params)

    return md 
Example #23
Source File: metadata.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def _get_observers(strategy: bt.Strategy) -> str:
    md = '\n# Observers\n'

    for o in strategy.observers:
        md += f'## {o.__class__.__name__}\n'
        md += _get_parameter_table(o.params)

    return md 
Example #24
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_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) 
Example #25
Source File: test_backtest.py    From OmegaUI with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.date = self.datas[0].datetime.date
        self.dataclose = self.datas[0].close
        self.buy_bars = [1, 21, 41, 61]
        self.close_bars = [20, 40, 60, 80]
        self.sell_bars = []
        self.log(logging.INFO, 'Strategy Initialized!') 
Example #26
Source File: test_backtest.py    From OmegaUI with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.logger = logging.getLogger(__name__)

        self.date = self.datas[0].datetime.date
        self.dataclose = self.datas[0].close
        self.order = None  # To keep track of pending orders
        self.log(logging.INFO, 'Strategy Initialized!')
        self.log(logging.INFO, 'Param1: {} - Param2: {}'.format(self.p.param1, self.p.param2)) 
Example #27
Source File: test_backtest.py    From OmegaUI with GNU General Public License v3.0 5 votes vote down vote up
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] 
Example #28
Source File: oandav20test.py    From backtrader-oandav20 with Apache License 2.0 5 votes vote down vote up
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('--------------------------------------------------') 
Example #29
Source File: base.py    From btgym with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #30
Source File: base.py    From btgym with GNU Lesser General Public License v3.0 5 votes vote down vote up
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