For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

Not used cash make some return

  • Is it possible to inform backtrader that cash not used will have a return of x% a year as if it was invested in bonds for example?
    I know I could include the bonds as a datafeed and trade the available cash, but I would like to see if there was a simpler way to do this.

  • It sounds very interesting.

  • I have managed to do it in my analyzer.

  • @André-Tavares

    Can you share the code?

  •     def start(self):
            super(Analyzer, self).start()
            self._value_start = 0.0
            self._last_value =
        def notify_cashvalue(self, cash, value):
            self._cash = cash
            self._value = value  # the portfolio value if tracking no data
        def on_dt_over(self):
            # next is called in a new timeframe period
            if self._last_value is not None:
                self._value_start = self._last_value  # update value_start to last
        def next(self):
            # Calculate the return
            super(Analyzer, self).next()
            risk_free_return = self.get_risk_free_return(self.dtkey) * self._cash
            self.rets[self.dtkey] = ((self._value + risk_free_return) / self._value_start) - 1.0
            self._last_value = self._value  # keep last value

  • I notice there's an add cash function in broker. I haven't explored it other than to see if it actually adds cash, which it does.
    2020-08-03 09:30:00, Cash: 100000.0
    2020-08-03 09:31:00, Cash: 100100.0
    2020-08-03 09:32:00, Cash: 100200.0
    2020-08-03 09:33:00, Cash: 100300.0
    2020-08-03 09:34:00, Cash: 100400.0

    Here is the line of code in (line:375)

    def add_cash(self, cash):
        '''Add/Remove cash to the system (use a negative value to remove)'''

  • But the cash added this way will not be considered for the return of the strategy.

  • @André-Tavares OK, I just found it so I'm not sure it's implications.

Log in to reply