Python backtrader.num2date() Examples

The following are 30 code examples of backtrader.num2date(). 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: 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 #2
Source File: utils.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
def convert_to_pandas(strat_clk, obj: bt.LineSeries, start: datetime = None, end: datetime = None, name_prefix: str = "", num_back=None) -> pd.DataFrame:
    lines_clk = obj.lines.datetime.plotrange(start, end)

    df = pd.DataFrame()
    # iterate all lines
    for lineidx in range(obj.size()):
        line = obj.lines[lineidx]
        linealias = obj.lines._getlinealias(lineidx)
        if linealias == 'datetime':
            continue

        # get data limited to time range
        data = line.plotrange(start, end)

        ndata = convert_by_line_clock(data, lines_clk, strat_clk)

        df[name_prefix + linealias] = ndata

    df[name_prefix + 'datetime'] = [bt.num2date(x) for x in strat_clk]

    return df 
Example #3
Source File: oanda.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def _st_start(self, instart=True, tmout=None):
        if self.p.historical:
            self.put_notification(self.DELAYED)
            dtend = None
            if self.todate < float('inf'):
                dtend = num2date(self.todate)

            dtbegin = None
            if self.fromdate > float('-inf'):
                dtbegin = num2date(self.fromdate)

            self.qhist = self.o.candles(
                self.p.dataname, dtbegin, dtend,
                self._timeframe, self._compression,
                candleFormat=self._candleFormat,
                includeFirst=self.p.includeFirst)

            self._state = self._ST_HISTORBACK
            return True

        self.qlive = self.o.streaming_prices(self.p.dataname, tmout=tmout)
        if instart:
            self._statelivereconn = self.p.backfill_start
        else:
            self._statelivereconn = self.p.backfill

        if self._statelivereconn:
            self.put_notification(self.DELAYED)

        self._state = self._ST_LIVE
        if instart:
            self._reconns = self.p.reconnections

        return True  # no return before - implicit continue 
Example #4
Source File: strategy_multiple_datas.py    From alpaca-backtrader-api with Apache License 2.0 5 votes vote down vote up
def log(self, txt, dt=None):
        dt = dt or self.data.datetime[0]
        dt = bt.num2date(dt)
        print('%s, %s' % (dt.isoformat(), txt)) 
Example #5
Source File: strategy_sma_crossover.py    From alpaca-backtrader-api with Apache License 2.0 5 votes vote down vote up
def log(self, txt, dt=None):
        dt = dt or self.data.datetime[0]
        dt = bt.num2date(dt)
        print('%s, %s' % (dt.isoformat(), txt)) 
Example #6
Source File: strategy_multiple_indicators.py    From alpaca-backtrader-api with Apache License 2.0 5 votes vote down vote up
def log(self, txt, dt=None):
        dt = dt or self.data.datetime[0]
        dt = bt.num2date(dt)
        print('%s, %s' % (dt.isoformat(), txt)) 
Example #7
Source File: alpacadata.py    From alpaca-backtrader-api with Apache License 2.0 5 votes vote down vote up
def _st_start(self, instart=True, tmout=None):
        if self.p.historical:
            self.put_notification(self.DELAYED)
            dtend = None
            if self.todate < float('inf'):
                dtend = num2date(self.todate)

            dtbegin = None
            if self.fromdate > float('-inf'):
                dtbegin = num2date(self.fromdate)

            self.qhist = self.o.candles(
                self.p.dataname, dtbegin, dtend,
                self._timeframe, self._compression,
                candleFormat=self._candleFormat,
                includeFirst=self.p.includeFirst)

            self._state = self._ST_HISTORBACK
            return True
        self.qlive = self.o.streaming_prices(self.p.dataname, tmout=tmout)
        if instart:
            self._statelivereconn = self.p.backfill_start
        else:
            self._statelivereconn = self.p.backfill

        if self._statelivereconn:
            self.put_notification(self.DELAYED)

        self._state = self._ST_LIVE
        if instart:
            self._reconns = self.p.reconnections

        return True  # no return before - implicit continue 
Example #8
Source File: oandav20feed.py    From backtrader-oandav20 with Apache License 2.0 5 votes vote down vote up
def _t_poll(self):
        dtstart = self._getstarttime(
            self._timeframe,
            self._compression,
            offset=1)
        while True:
            dtcurr = self._getstarttime(self._timeframe, self._compression)
            # request candles in live instead of stream
            if dtcurr > dtstart:
                if len(self) > 1:
                    # len == 1 ... forwarded for the 1st time
                    dtbegin = self.datetime.datetime(-1)
                elif self.fromdate > float('-inf'):
                    dtbegin = num2date(self.fromdate)
                else:  # 1st bar and no begin set
                    dtbegin = dtstart
                self.qlive = self.o.candles(
                    self.p.dataname, dtbegin, None,
                    self._timeframe, self._compression,
                    candleFormat=self._candleFormat,
                    onlyComplete=True,
                    includeFirst=False)
                dtstart = dtbegin
                # sleep until next call
                dtnow = datetime.utcnow()
                dtnext = self._getstarttime(
                    self._timeframe,
                    self._compression,
                    dt=dtnow,
                    offset=-1)
                dtdiff = dtnext - dtnow
                tmout = (dtdiff.days * 24 * 60 * 60) + dtdiff.seconds + 1
                if tmout <= 0:
                    tmout = 5
                _time.sleep(tmout) 
Example #9
Source File: oandav20feed.py    From backtrader-oandav20 with Apache License 2.0 5 votes vote down vote up
def _st_start(self, instart=True):
        if self.p.historical:
            self.put_notification(self.DELAYED)
            dtend = None
            if self.todate < float('inf'):
                dtend = num2date(self.todate)

            dtbegin = None
            if self.fromdate > float('-inf'):
                dtbegin = num2date(self.fromdate)

            self.qhist = self.o.candles(
                self.p.dataname, dtbegin, dtend,
                self._timeframe, self._compression,
                candleFormat=self._candleFormat,
                includeFirst=True)

            self._state = self._ST_HISTORBACK
            return True

        # depending on candles, either stream or use poll
        if instart:
            self._statelivereconn = self.p.backfill_start
        else:
            self._statelivereconn = self.p.backfill
        if self._statelivereconn:
            self.put_notification(self.DELAYED)
        if not self.p.candles:
            # recreate a new stream on call
            self.qlive = self.o.streaming_prices(
                self.p.dataname)
        elif instart:
            # poll thread will never die, so no need to recreate it
            self.poll_thread()
        self._state = self._ST_LIVE
        return True  # no return before - implicit continue 
Example #10
Source File: test_dump_data.py    From sptrader with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def next(self):
        # Simply log the closing price of the series from the reference
        self.log(bt.num2date(self.datas[0].datetime[0]),
                 bt.num2date(self.datas[1].datetime[0]),
                 self.datas[0].open[0],
                 self.datas[1].open[0]) 
Example #11
Source File: ptstrategy_cointegration.py    From pairstrade-fyp-2019 with MIT License 5 votes vote down vote up
def log_status(self):
        status_dict = {}

        # general status
        status_dict["date"] = bt.num2date(self.data0.datetime[0])
        status_dict["data0"] = self.data0[0]
        status_dict["data1"] = self.data1[0]
        status_dict["lookback"] = self.lookback
        status_dict["max_lookback"] = self.max_lookback
        status_dict["enter_threshold_size"] = self.enter_threshold_size
        status_dict["exit_threshold_size"] = self.exit_threshold_size
        status_dict["loss_limit"] = self.loss_limit
        status_dict["status"] = self.status
        status_dict["qty0"] = self.qty0
        status_dict["qty1"] = self.qty1 
        status_dict["initial_price_data0"] = self.initial_price_data0 
        status_dict["initial_price_data1"] = self.initial_price_data1 
        status_dict["initial_cash"] = self.initial_cash 
        status_dict["initial_long_pv"] = self.initial_long_pv
        status_dict["initial_short_pv"] = self.initial_short_pv
        status_dict["upper_limit"] = self.upper_limit 
        status_dict["lower_limit"] = self.lower_limit 
        status_dict["up_medium"] = self.up_medium 
        status_dict["low_medium"] = self.low_medium 
        status_dict["portfolio_value"] = self.broker.getvalue()
        status_dict["latest_trade_action"] =self.latest_trade_action
        status_dict["sell_stk"] = self.sell_stk
        status_dict["buy_stk"] = self.buy_stk
        status_dict["sell_amt"] = self.sell_amt 
        status_dict["buy_amt"] = self.buy_amt

        # strategy-specific status
        status_dict["spread"] = self.get_spread()
        status_dict["allow_trade"] = self.allow_trade 
        status_dict["alpha"] = self.alpha 
        status_dict["intercept"] = self.intercept
        status_dict["resid_mean"] = self.resid_mean
        status_dict["resid_std"] = self.resid_std

        # log the dictionary
        PTStrategy.log("[strategy-status]: {}".format(status_dict), None, self.data0) 
Example #12
Source File: ptstrategy.py    From pairstrade-fyp-2019 with MIT License 5 votes vote down vote up
def log(txt, dt=None, data=None):
        dt = dt or data.datetime[0]
        dt = bt.num2date(dt)
        _logger.info('%s, %s' % (dt.isoformat(), txt)) 
Example #13
Source File: ptstrategy_distance.py    From pairstrade-fyp-2019 with MIT License 5 votes vote down vote up
def log_status(self):
        status_dict = {}

        # general status
        status_dict["date"] = bt.num2date(self.data0.datetime[0])
        status_dict["data0"] = self.data0[0]
        status_dict["data1"] = self.data1[0]
        status_dict["lookback"] = self.lookback
        status_dict["max_lookback"] = self.max_lookback
        status_dict["enter_threshold_size"] = self.enter_threshold_size
        status_dict["exit_threshold_size"] = self.exit_threshold_size
        status_dict["loss_limit"] = self.loss_limit
        status_dict["status"] = self.status
        status_dict["qty0"] = self.qty0
        status_dict["qty1 "] = self.qty1 
        status_dict["initial_price_data0"] = self.initial_price_data0 
        status_dict["initial_price_data1"] = self.initial_price_data1 
        status_dict["initial_cash"] = self.initial_cash 
        status_dict["initial_long_pv"] = self.initial_long_pv
        status_dict["initial_short_pv"] = self.initial_short_pv
        status_dict["upper_limit"] = self.upper_limit 
        status_dict["lower_limit"] = self.lower_limit 
        status_dict["up_medium"] = self.up_medium 
        status_dict["low_medium"] = self.low_medium 
        status_dict["portfolio_value"] = self.broker.getvalue()
        status_dict["latest_trade_action"] =self.latest_trade_action
        status_dict["sell_stk"] = self.sell_stk
        status_dict["buy_stk"] = self.buy_stk
        status_dict["sell_amt"] = self.sell_amt 
        status_dict["buy_amt"] = self.buy_amt

        # strategy-specific status
        status_dict["spread"] = self.get_spread()
        status_dict["allow_trade"] = self.allow_trade 
        status_dict["resid_mean"] = self.resid_mean 
        status_dict["resid_std"] = self.resid_std

        # log the dictionary
        PTStrategy.log("[strategy-status]: {}".format(status_dict), None, self.data0) 
Example #14
Source File: mt5data.py    From Backtrader-MQL5-API with GNU General Public License v3.0 5 votes vote down vote up
def _st_start(self):
        self.put_notification(self.DELAYED)

        date_begin = num2date(
            self.fromdate) if self.fromdate > float('-inf') else None
        date_end = num2date(
            self.todate) if self.todate < float('inf') else None

        self.qhist = self.o.price_data(self.p.dataname, date_begin, date_end, self.p.timeframe,
                                       self.p.compression, self.p.include_last)

        self._state = self._ST_HISTORBACK

        return True 
Example #15
Source File: pair-trading.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None):
        if self.p.printout:
            dt = dt or self.data.datetime[0]
            dt = bt.num2date(dt)
            print('%s, %s' % (dt.isoformat(), txt)) 
Example #16
Source File: sigsmacross.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def notify_order(self, order):
        if not order.alive():
            print('{} {} {}@{}'.format(
                bt.num2date(order.executed.dt),
                'buy' if order.isbuy() else 'sell',
                order.executed.size,
                order.executed.price)
            ) 
Example #17
Source File: ibdata.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def _st_start(self):
        if self.p.historical:
            self.put_notification(self.DELAYED)
            dtend = None
            if self.todate < float('inf'):
                dtend = num2date(self.todate)

            dtbegin = None
            if self.fromdate > float('-inf'):
                dtbegin = num2date(self.fromdate)

            self.qhist = self.ib.reqHistoricalDataEx(
                contract=self.contract, enddate=dtend, begindate=dtbegin,
                timeframe=self._timeframe, compression=self._compression,
                what=self.p.what, useRTH=self.p.useRTH, tz=self._tz,
                sessionend=self.p.sessionend)

            self._state = self._ST_HISTORBACK
            return True  # continue before

        # Live is requested
        if not self.ib.reconnect(resub=True):
            self.put_notification(self.DISCONNECTED)
            self._state = self._ST_OVER
            return False  # failed - was so

        self._statelivereconn = self.p.backfill_start
        if self.p.backfill_start:
            self.put_notification(self.DELAYED)

        self._state = self._ST_LIVE
        return True  # no return before - implicit continue 
Example #18
Source File: test_strategy_optimized.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None):
        dt = dt or self.data.datetime[0]
        dt = bt.num2date(dt)
        print('%s, %s' % (dt.isoformat(), txt)) 
Example #19
Source File: test_analyzer-sqn.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None, nodate=False):
        if not nodate:
            dt = dt or self.data.datetime[0]
            dt = bt.num2date(dt)
            print('%s, %s' % (dt.isoformat(), txt))
        else:
            print('---------- %s' % (txt)) 
Example #20
Source File: test_strategy_unoptimized.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None, nodate=False):
        if not nodate:
            dt = dt or self.data.datetime[0]
            dt = bt.num2date(dt)
            print('%s, %s' % (dt.isoformat(), txt))
        else:
            print('---------- %s' % (txt)) 
Example #21
Source File: multidata-strategy-unaligned.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None):
        if self.p.printout:
            dt = dt or self.data.datetime[0]
            dt = bt.num2date(dt)
            print('%s, %s' % (dt.isoformat(), txt)) 
Example #22
Source File: multidata-strategy.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None):
        if self.p.printout:
            dt = dt or self.data.datetime[0]
            dt = bt.num2date(dt)
            print('%s, %s' % (dt.isoformat(), txt)) 
Example #23
Source File: multitrades.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None):
        if self.p.printout:
            dt = dt or self.data.datetime[0]
            dt = bt.num2date(dt)
            print('%s, %s' % (dt.isoformat(), txt)) 
Example #24
Source File: writer-test.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None):
        if self.p.printout:
            dt = dt or self.data.datetime[0]
            dt = bt.num2date(dt)
            print('%s, %s' % (dt.isoformat(), txt)) 
Example #25
Source File: close-minute.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def notify_order(self, order):
        curdtstr = self.data.datetime.datetime().strftime('%a %Y-%m-%d %H:%M:%S')
        if order.status in [order.Completed]:
            dtstr = bt.num2date(order.executed.dt).strftime('%a %Y-%m-%d %H:%M:%S')
            if order.isbuy():
                print('%s: BUY  EXECUTED, on:' % curdtstr, dtstr)
                self.order = None
            else:  # Sell
                print('%s: SELL EXECUTED, on:' % curdtstr, dtstr) 
Example #26
Source File: analyzer-annualreturn.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None):
        if self.p.printout:
            dt = dt or self.data.datetime[0]
            dt = bt.num2date(dt)
            print('%s, %s' % (dt.isoformat(), txt)) 
Example #27
Source File: observers-orderobserver.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.data.datetime[0]
        if isinstance(dt, float):
            dt = bt.num2date(dt)
        print('%s, %s' % (dt.isoformat(), txt)) 
Example #28
Source File: observers-default-drawdown.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.data.datetime[0]
        if isinstance(dt, float):
            dt = bt.num2date(dt)
        print('%s, %s' % (dt.isoformat(), txt)) 
Example #29
Source File: cheat-on-open.py    From backtrader with GNU General Public License v3.0 5 votes vote down vote up
def notify_order(self, order):
        if order.status != order.Completed:
            return

        self.order = None
        print('{} {} Executed at price {}'.format(
            bt.num2date(order.executed.dt).date(),
            'Buy' * order.isbuy() or 'Sell', order.executed.price)
        ) 
Example #30
Source File: ptstrategy_cointegration_kalman.py    From pairstrade-fyp-2019 with MIT License 4 votes vote down vote up
def log_status(self):
        status_dict = {}

        # general status
        status_dict["date"] = bt.num2date(self.data0.datetime[0])
        status_dict["data0"] = self.data0[0]
        status_dict["data1"] = self.data1[0]
        status_dict["lookback"] = self.lookback
        status_dict["max_lookback"] = self.max_lookback
        status_dict["enter_threshold_size"] = self.enter_threshold_size
        status_dict["exit_threshold_size"] = self.exit_threshold_size
        status_dict["loss_limit"] = self.loss_limit
        status_dict["status"] = self.status
        status_dict["qty0"] = self.qty0
        status_dict["qty1"] = self.qty1 
        status_dict["initial_price_data0"] = self.initial_price_data0 
        status_dict["initial_price_data1"] = self.initial_price_data1 
        status_dict["initial_cash"] = self.initial_cash 
        status_dict["initial_long_pv"] = self.initial_long_pv
        status_dict["initial_short_pv"] = self.initial_short_pv
        status_dict["upper_limit"] = self.upper_limit 
        status_dict["lower_limit"] = self.lower_limit 
        status_dict["up_medium"] = self.up_medium 
        status_dict["low_medium"] = self.low_medium 
        status_dict["portfolio_value"] = self.broker.getvalue()
        status_dict["latest_trade_action"] =self.latest_trade_action
        status_dict["sell_stk"] = self.sell_stk
        status_dict["buy_stk"] = self.buy_stk
        status_dict["sell_amt"] = self.sell_amt 
        status_dict["buy_amt"] = self.buy_amt

        # strategy-specific status
        status_dict["spread"] = self.get_spread()
        status_dict["allow_trade"] = self.allow_trade 
        status_dict["alpha"] = self.alpha 
        status_dict["intercept"] = self.intercept
        # status_dict["filtered_state_means"] = self.filtered_state_means
        # status_dict["filtered_state_covariances"] = self.filtered_state_covariances
        status_dict["spread_std"] = self.spread_std

        # log the dictionary
        PTStrategy.log("[strategy-status]: {}".format(status_dict), None, self.data0)