Skip to content

Instantly share code, notes, and snippets.

@ace3
Created May 25, 2020 08:05
Show Gist options
  • Save ace3/a5ccab1644d6af3e797c487d4c80ddd3 to your computer and use it in GitHub Desktop.
Save ace3/a5ccab1644d6af3e797c487d4c80ddd3 to your computer and use it in GitHub Desktop.
class MAcrossover(bt.Strategy):
#Moving Average Parameters
params = (('pfast',20),('pslow',50))
def log(self,txt,dt=None):
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(),txt))
def __init__(self):
self.dataclose = self.datas[0].close
# Order variable
self.order = None
# Instantiate moving averages
self.slow_sma = bt.indicators.SimpleMovingAverage(self.datas[0],period=self.params.pslow)
self.fast_sma = bt.indicators.SimpleMovingAverage(self.datas[0],period=self.params.pfast)
self.crossover = bt.indicators.CrossOver(self.slow_sma, self.fast_sma)
def notify_order(self,order):
if order.status in [order.Submitted, order.Accepted]:
#Active Buy/Sell order submitted/accepted - Nothing to do
return
#Check if an order has been completed
#Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.log('BUY EXECUTED, %.2f' % order.executed.price)
elif order.issell():
self.log('SELL EXECUTED, %.2f' % order.executed.price)
self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
#Reset orders
self.order = None
def next(self):
if self.order:
return
#Check if we are in the market
if not self.position:
#We are not in the market, look for a signal to OPEN trades
#If the 20 SMA is above the 50 SMA
if self.fast_sma[0] > self.slow_sma[0] and self.fast_sma[-1] < self.slow_sma[-1]:
self.log('BUY CREATE, %.2f' % self.dataclose[0])
#Keep track of the created order to avoid a 2nd order
self.order = self.buy()
#Otherwise if the 20 SMA is below the 50 SMA
elif self.fast_sma[0] < self.slow_sma[0] and self.fast_sma[-1] > self.slow_sma[-1]:
self.log('SELL CREATE, %.2f' % self.dataclose[0])
#Keep track of the created order to avoid a 2nd order
self.order = self.sell()
else:
# We are already in the market, look for a signal to CLOSE trades
if len(self) >= (self.bar_executed + 5):
self.log('CLOSE CREATE, %.2f' % self.dataclose[0])
self.order = self.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment