self.sma50 = bt.indicators.Mean(self.data.close, period=50)
self.sma200 = bt.indicators.Mean(self.data.close, period=200)
def next(self):
if not self.position:
if self.sma50 > self.sma200:
self.buy(size=50)
else:
if self.sma200 > self.sma50:
self.sell(size=50)
self.ama14 = bt.indicators.KAMA(self.data.close, period=14)
self.ama50 = bt.indicators.KAMA(self.data.close, period=50)
def next(self):
if not self.position:
if self.sma50 > self.sma200:
self.buy(size=50)
if self.ama14 > price and self.ama14 > self.ama50:
self.buy(size=100)
else:
if self.sma200 > self.sma50:
self.sell(size=50)
if self.ama14 < price and self.ama14 < self.ama50:
self.sell(size=100)
from datetime import datetime
import backtrader as bt
class SmaAmaStrategy(bt.Strategy):
def __init__(self):
self.sma50 = bt.indicators.SMA(self.data.close, period=50)
self.sma200 = bt.indicators.SMA(self.data.close, period=200)
self.ama14 = bt.indicators.KAMA(self.data.close, period=14)
self.ama50 = bt.indicators.KAMA(self.data.close, period=50)
def next(self):
if not self.position:
if self.sma50 > self.sma200:
self.buy(size=50)
if self.ama14 > price and self.ama14 > self.ama50:
self.buy(size=100)
else:
if self.sma200 > self.sma50:
self.sell(size=50)
if self.ama14 < price and self.ama14 < self.ama50:
self.sell(size=100)
startcash = 10000
cerebro = bt.Cerebro()
cerebro.addstrategy(FirstStrategy)
aapl_data = bt.feeds.Quandl(
dataname="AAPL",
fromdate=datetime(2006,1,1),
todate = datetime(2020,10,20),
buffered=True)
cerebro.adddata(aapl_data)
cerebro.broker.setcash(startcash)
cerebro.run()
portvalue = cerebro.broker.getvalue()
pnl = portvalue - startcash
print('Final Portfolio Value: ${}'.format(portvalue))
print('P/L: ${}'.format(pnl))
cerebro.plot(style='candlestick')