For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
Help ! Buy and Buy More Strategy - target_order_value fails to trigger a buy
-
Followed this blog post and this thread to come up with the following code:
class BuyAndHold_More(bt.Strategy): params = dict( monthly_cash=10000.0, # amount of cash to buy every month when=bt.timer.SESSION_START, timer=True, monthdays=[1], ) def __init__(self): self.add_timer( when=self.p.when, monthdays=self.p.monthdays, ) def log(self, txt, dt=None): print(self.datas[0].datetime.date(), txt) def start(self): self.cash_start = self.broker.get_cash() self.val_start = 100.0 # Add a timer which will be called on the 1st trading day of the month self.add_timer( bt.timer.SESSION_END, # when it will be called monthdays=[1], # called on the 1st day of the month monthcarry=True, # called on the 2nd day if the 1st is holiday ) def notify_timer(self, timer, when, *args, **kwargs): # Add the influx of monthly cash to the broker self.broker.add_cash(self.p.monthly_cash) print("Cash Added!") target_value = self.broker.get_value() + self.p.monthly_cash self.order_target_value(data=self.datas[0], target=target_value) def next(self): self.log("Cash {} Value {}".format(self.broker.cash, self.broker.get_value()))
It adds cash as intended but does not trigger a buy every month. What could possibly go wrong ?
-
@mahaaveer I cannot tell for sure with this limited information. Print a log from orders and I suspect you will find your answer. You are adding the monthly cash to a value that already has the monthly cash when figuring out your size. Then you are likely not having enough money in your account to cover the trade, because it's too big.
target_value = self.broker.get_value() + self.p.monthly_cash # get right of self.p.monthly_cash self.order_target_value(data=self.datas[0], target=target_value)