When and how to execute the first an only trade in a buy-and-hold strategy
Stefan Krecher last edited by
I'm using a BuyAndHold strategy to compare the results of a strategy that I'm developing.
I'd like to calculate the maximum number of stocks that I'm able to buy, based on the current price and the available cash:
class BuyAndHold(bt.Strategy): def start(self): self.val_start = self.broker.get_cash() # keep the starting cash def nextstart(self): # Buy all the available cash size = int(self.broker.get_cash() / self.data) print("nextstart price %.2f size=%s" % (float(10000.0 / float(self.broker.get_cash() / self.data)), size)) self.buy(size=size)
Output of the above is:
nextstart price 12.96 size=771
size is calculated based on the closing price of the very first entry in the dataset.
But the buy-order in the "nextstart" function will not be executed.
By playing around with different sizes, I found out that self.buy will be executed with a number of 751 (instead of the calculated number of 771).
When I divide 10000 by the opening price of the second candle in the dataset - I'll get the correct number of shares (751) that I'm allowed to buy in the nextstart function.
So what am I missing here? Assuming that "nextstart" is the place to execute the very first trade of the strategy, I would need to get the opening-price of the second entry in the dataset. But how?
Or is this a bug? If I would like to buy at the very first possible point in time, I should see the opening price of the very first candle.
Looking forward to any suggestions.
def next(self): if not self.position: self.buy()
So what am I missing here?
btexecutes the orders on the next bar
openprice since this is the next available price after the order is issued in the