from System.Drawing import Color
class SMA_trading(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 8, 30) # the starting date for our backtest
#self.SetEndDate(2020, 2, 1) # the ending date for our backtest (if no date, then it will test up until today)
self.start_value = 5000 # define the amount of starting cash
self.SetCash(self.start_value) # initialize our wallet
self.EQY = "SPY" # define the stock ticker
self.AddEquity(self.EQY, Resolution.Daily) # add a stock to the list of those we want to trade, and how often to pull data
self.starting_price = None
self.spy_portfolio = None
self.period1 = 20
self.period2 = 50
self.period3 = 200
# create a consolidator for weekly data
self.Consolidate(self.EQY, Calendar.Weekly, self.OnWeeklyBar)
# # create a consolidator for monthly data
# self.Consolidate(self.EQY, Calendar.Weekly, self.OnMonthlyBar)
# set up an SMA20 indicator
#var sma = SMA(Symbol symbol, int period, Resolution resolution = null, Func`2[Data.IBaseData,Decimal] selector = null)
self.sma_daily1 = SimpleMovingAverage(self.period1)
self.sma_daily2 = SimpleMovingAverage(self.period2)
self.sma_daily3 = SimpleMovingAverage(self.period3)
self.sma_weekly1 = SimpleMovingAverage(self.period1)
self.sma_weekly2 = SimpleMovingAverage(self.period2)
self.sma_weekly3 = SimpleMovingAverage(self.period3)
# need to give the indicators data before running the algorithm
self.SetWarmUp(timedelta(self.period3 * 7))
# set up a chart to display our buy and sell dates
self.stockPlot = Chart('Equity')
self.SPY_candles = Series(self.EQY, SeriesType.Candle)
self.stockPlot.AddSeries(self.SPY_candles)
self.stockPlot.AddSeries(Series('Buy', SeriesType.Scatter, '$', Color.Green, ScatterMarkerSymbol.Triangle))
self.stockPlot.AddSeries(Series('Sell', SeriesType.Scatter, '$', Color.Red, ScatterMarkerSymbol.TriangleDown))
self.AddChart(self.stockPlot)
# this is for plotting the relative change of each stock and our portfolio value
def OnEndOfDay(self):
current_portfolio = self.Portfolio.TotalPortfolioValue
change_portfolio = (current_portfolio - self.start_value )/ self.start_value
self.Plot("Percent Change","Portfolio Change", change_portfolio)
# # if we haven't gotten the starting price, then get it
if self.starting_price == None:
self.starting_price = self.Securities[self.EQY].Price
start_price = self.starting_price
price = self.Securities[self.EQY].Price
change_in_price = (price - start_price)/ start_price
self.Plot("Percent Change", self.EQY + " Change", change_in_price)
# price = self.Securities[self.EQY].Price
# change_in_price = (price - start_price)/ start_price
# self.Plot("Strategy Equity", self.EQY + " Change", change_in_price * self.start_value)
def OnData(self,data):
# # if the indicators aren't ready, don't do anything
if (not self.sma_weekly3.IsReady): return
weekly_low_price = self.currentBar.Low
weekly_high_price = self.currentBar.High
self.sma_daily1.Update(self.Time, weeklyBar.Close)
self.sma_daily2.Update(self.Time, weeklyBar.Close)
self.sma_daily3.Update(self.Time, weeklyBar.Close)
# # extract the current value of each indicator
sma_weekly1 = self.sma1.Current.Value
sma_weekly2 = self.sma2.Current.Value
sma_weekly3 = self.sma3.Current.Value
# # determine where the price is relative to the sma
upSMA = low_price > sma_daily1 and low_price > sma_daily2 and low_price > sma_daily3
downSMA = high_price < sma_daily1 and high_price < sma_daily2 and high_price < sma_daily3
if (upSMA):
if not self.Portfolio[self.EQY].Invested:
self.SetHoldings(self.EQY, 1) # if the price is above the 20-day moving average, buy the stock
self.Plot("Equity", 'Buy', self.Securities[self.EQY].Price)
elif (downSMA):
if self.Portfolio[self.EQY].Invested:
self.SetHoldings(self.EQY, 0) # otherwise exit the position
self.Plot("Equity", 'Sell', self.Securities[self.EQY].Price)
def OnWeeklyBar(self, weeklyBar):
# self.Log(weeklyBar)
self.currentBar = weeklyBar
self.sma_weekly1.Update(weeklyBar.Time, weeklyBar.Close)
self.sma_weekly2.Update(weeklyBar.Time, weeklyBar.Close)
self.sma_weekly3.Update(weeklyBar.Time, weeklyBar.Close)
# plotting stuff
self.SPY_candles.AddPoint(self.Time + timedelta(minutes=1), weeklyBar.Open)
self.SPY_candles.AddPoint(self.Time + timedelta(minutes=2), weeklyBar.High)
self.SPY_candles.AddPoint(self.Time + timedelta(minutes=3), weeklyBar.Low)
self.SPY_candles.AddPoint(self.Time + timedelta(minutes=4), weeklyBar.Close)
#self.Plot("Equity",self.EQY + " HIGH", weeklyBar.High)
#self.Plot("Equity",self.EQY + " LOW", weeklyBar.Low)
#self.Plot("Equity",self.EQY, weeklyBar.High)
#self.Plot("Equity",self.EQY, weeklyBar.Low)
#self.Plot("Equity",self.EQY, weeklyBar.Close)
#self.Plot("Equity",self.EQY+' Price',self.Securities[self.EQY].Close)
self.Plot("Equity","SMA20", sma1)
self.Plot("Equity","SMA50", sma2)
self.Plot("Equity","SMA200", sma3)
def OnOrderEvent(self, orderEvent):
if orderEvent.Status != OrderStatus.Filled:
return
self.Log(f"Order Executed! Open Time: {self.currentBar.Time}, Close Time: {self.currentBar.EndTime} -- Bar: {self.currentBar}, SMA: {self.sma1.Current.Value}")