200 Day Moving Average

class BasicTemplateAlgorithm(QCAlgorithm):

def Initialize(self):

self.SetStartDate(2017,01,01) #Set Start Date
self.SetEndDate(2017,12,31) #Set End Date
self.SetCash(100000) #Set Strategy Cash


# below creates a 200 day exponential moving average

self.slow = self.EMA("SPY", 200, Resolution.Daily);
self.previous = None

def OnData(self, data):

if not self.slow.IsReady:

if self.previous is not None and ==

holdings = self.Portfolio["SPY"].Quantity

if holdings <= 0:

if self.slow.Current.Value < self.Securities["SPY"].Price

self.Log("BUY >> {0}".format(self.Securities["SPY"].Price))
self.SetHoldings("SPY", 1.0)

if holdings > 0 and self.slow > self.Securities["SPY"].Price

self.Log("SELL >> {0}".format(self.Securities["SPY"].Price))

self.previous = self.Time
Update Backtest

Believe my syntax is incorrect for line 30 - might be a few others too!

Just trying to create a very simple 200 day moving average strategy w/ price of SPY. If below MA all to cash - if above MA all to SPY. 



Hi Calvin, I'm a QC beginner but if it can be of help, I simply believe you forgot the ":" at the end of your if condition. So in row 30,

if self.slow.Current.Value < self.Securities["SPY"].Price

you need to add a ":" at the end -->

if self.slow.Current.Value < self.Securities["SPY"].Price:


uhm, truth is, even with that small fix, it still doesn't work on my end... what a frustration...


this is exactly what you want to do:

in this strategy is a daily sma 220.


Appreciate the the help Michael & Andrea. I still get the error also after adding the ":"

I have a much easier time understanding the code from the post Michael attached - going to swap over to that method. 

Thanks again!



Update Backtest


The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


This discussion is closed