Problem using subclasses of a Strategy
-
Hey guys I'm definitely a 'novice' coder so maybe I'm messing something up with the way I'm using classes and it's not backtrader related. Would really appreciate any help. Basically I created a class for a general strategy called MyStrat then I created a subclass called MacdStrat that uses the MACD to place buys and sells. When I had the MACD code inside of MyStrat everything was working great but I decided to make a subclass so that I could make multiple subclasses with different strategies. Here's my code below with my first class and then the subclass. Thanks again.
import backtrader as bt class MyStrat(bt.Strategy): def notify_fund(self, cash, value, fundvalue, shares): self.cash = cash def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: return if order.status in [order.Completed]: # if order.isbuy(): # self.log("BOUGHT %i SHARES at $%.2f" % (order.executed.size, order.executed.price)) # elif order.issell(): # self.log("SOLD %i SHARES at $%.2f" % (order.executed.size, order.executed.price)) self.shares = self.shares + order.executed.size self.order = None def __init__(self): self.order = None self.shares = 0 self.cash = 0 def next(self): if self.order: return #if self.cash > 0: #BUY CONDITION: #self.log("BUY CREATED at $%.2f" % self.data.close[0]) #self.order = self.buy(size=int(self.cash*0.50/self.data.close[0])) #if self.shares > 0: #if SELL CONDITION: #self.log("SELL CREATED at $%.2f" % self.data.close[0]) #self.order = self.sell(size=int(self.shares*0.50)) def log(self, txt, dt=None): dt = dt or self.datas[0].datetime.date(0) print("%s, %s" % (dt.isoformat(), txt)) class MacdStrat(MyStrat): def __init__(self): self.macd = bt.indicators.MACD(self.data.close) self.cross = bt.indicators.CrossOver(self.macd.macd, self.macd.signal) self.order = None self.shares = 0 self.cash = 0 print(self.cross) def next(self): if self.order: return if self.cash > 0: if self.cross[0] > 0: #self.log("BUY CREATED at $%.2f" % self.data.close[0]) self.order = self.buy(size=int(self.cash*0.50/self.data.close[0])) if self.shares > 0: if self.cross[0] < 0: #self.log("SELL CREATED at $%.2f" % self.data.close[0]) self.order = self.sell(size=int(self.shares*0.50))
-
@frankles_42 Google
python class super function
That should get you on your way.
-
@run-out I have tried using the
super()
function before and that hasn't really helped. I forgot to include that my error was related to files in the indicators folder of the backtrader package, specifically a file calledbasicops.py
and specifically a class that's calledAverage
in that file. However now that I try implementing all of the indicators and if statements in theMyStrat
class, now its not working and is giving the same error. So at this point I think I'm messing something up with backtrader and not the classes. THx -
@frankles_42 We could probably help better if you share your error codes. Thanks