Back

Help with calculating slope of SMA

Hey, working on trying to figure out the slope of an SMA line.  The way I did it on quantopian was to calculate the mean of the close of the last 225 minute bars and then calculate the mean of the close of the last 1-226 minute bars.  Then I would take the difference and that is the slope (direction and magnitude). I cant figure out how to do that on quant connect.  

Also, the reason I dont use indicators is because I cant figure out a way to determine the SMA value at a point in history, like the minute before the current minute.

Here is my lines of code in OnData:

 

svxy_hist = self.History("SVXY", 250, Resolution.Minute)  #this gives the close bar data for last 250 minute bars.
        
        svxy_SMA_325 = svxy_hist[-225].mean() #gives the SMA225 of the last 225 minute bars
        svxy_SMA_325_previous = svxy_hist[-226:-1].mean() #gives the SMA225 from the last minute 
        svxy_slope = svxy_SMA_325-svxy_SMA_325_previous #gives the slope magnitude and direction

 

builds fine but the backtest gets stuck on the "-225"

Thanks in advance!

David

Update Backtest








IMHO -- you should get a RollingWindow (indicator) -- and then take the values out of it that you want and feed them into the SimpleMovingAverage class; this will be efficient and achieve the aim you want.

SMA is a helper but you can directly use "SimpleMovingAverage" class to calculate a SMA on any values you feed into it. 

0

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.


Thanks but I dont see a rolling window in the documentation.  I appologize in adanvce for my lack of programming knowledge.  Any place I could read up on it?  I did a search and started a practice code for this problem:

 

current_svxy_SMA225 = self.SMA("SVXY", 225, Resolution.Minute)
        RollingWindow lastMinute = new RollingWindow(1);
            lastMinute.Add(["SVXY"])
        previous_SVXY_SMA225 = lastMinute[1]
        svxy_slope = current_svxy_SMA225 - previous_SVXY_SMA225

0

ha you got him on this one david..........

https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/RollingWindowAlgorithm.py
0

also take a look at this new post of a strategy where a slope is used

https://www.quantconnect.com/forum/discussion/3260/etf-trend-following-algorithm
0

Gosh you're right! We'll add it to the docs today =)

1

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.


So I set it up as follows:

in def initialize:

        self.window = RollingWindow[TradeBar](2)  #Do I need 2 of these? one for each ETF?
        
        self.SMA("SVXY", 225, Resolution.Minute).Updated += self.SmaUpdated
        self.smasvxy = RollingWindow[IndicatorDataPoint](225)
        
        self.SMA("SOLX", 250, Resolution.Minute).Updated += self.SmaUpdated
        self.smasolx = RollingWindow[IndicatorDataPoint](250)

def SmaUpdated(self, sender, updated):
        '''Adds updated values to rolling window'''
        self.smasvxy.Add(updated)
        self.smasolx.Add(updated)

def OnData(self, data):

self.window.Add(data["SOXL"])
        self.window.Add(data["SVXY"])
        
        currSmasvxy = self.smasvxy[0]                     # Current SMA had index zero.
        pastSmasvxy = self.smasvxy[self.smaWin.Count-1]   # Oldest SMA has index of window count minus 1.
        
        currSmasoxl = self.smasoxl[0]                     # Current SMA had index zero.
        pastSmasoxl = self.smasoxl[self.smaWin.Count-1]   # Oldest SMA has index of window count minus 1.
        
        slopesvxy = currSmasvxy - pastSmasvxy
        slopesoxl = currSmasoxl - pastSmasoxl

 

Seems like it works.  At least the build works and when I run a backtest I dont get hung up on it anymore.  I'm still getting hung up though.  It says I Failed to initialize algorithm: Initialize(): Python.Runtime.PythonException: Exception : Please register to receive data for symbol ' ' using the AddSecurity() function.

 

in my initialize section I have the stocks set up as follows:

self.svxy = self.AddEquity("SVXY", Resolution.Minute).Symbol

 

Is that correct?

0

this error messages shows up when you try to work with an asset which you didnt subscribed to....whats that SOXL ?

0

How can I get subscribed to the assets? Soxl, svxy, uvxy and soxs are leveraged ETFs. Soxl and soxs are the oong and short of semiconductors and svxy and uvxy are long and shorts of volitility index.



Get Outlook for Android
0

I don't see how that error makes any sense.  If I make a simple algo just to buy into those stocks and hold them it works and backtests just fine so it doesn't have to do with the ticker symbols I'm using... Any thoughts?

0

Hi David, you need to subscribe the asset data of "SVXY" and "SOLX" in initialization before you use them in  indicator and trade

self.AddEquity(string ticker, Resolution resolution)
0

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.


hi if you have time take look at some basic parts of quantconnect:

https://www.quantconnect.com/forum/discussion/2931/boot-camp---interactive-tutorial-system
0

Hey, thanks for your help everyone.  I've reviewed the tutorials prior to posting this thread.  I had them set up as this in the initialize section but was missing a statement in the ondata section.

self.svxy = self.AddEquity("SVXY", Resolution.Minute).Symbol

0

So far I've got the rollingwindow working for a single stock using minute data but I cant figure out how to just do a simple subtraction of 2 values.  I have the currentSMA for SVXY and the previousSMA for SVXY.  To calculate slope at this point i just need slopesvxy = prevsma - currsma but it doesnt recognize the subtraction.  I tried using ".Value" after and without.  

def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''

# Add SPY TradeBar in rollling window
self.window.Add(data["SVXY"])

# Wait for windows to be ready.
if not (self.window.IsReady and self.smaWin.IsReady): return


currSma = self.smaWin[0] # Current SMA had index zero.
pastSma = self.smaWin[self.smaWin.Count-1] # Oldest SMA has index of window count minus 1.
self.Log("SMA: {0} -> {1} ... {2} -> {3}".format(pastSma.Time, pastSma.Value, currSma.Time, currSma.Value))

slopesvxy = (pastSma.Value - currSma.Value)
self.Log("Slope: {0} -> {1}".format(slopesvxy.Time, Slopesvxy.Value))
0

Hi David, can you Log the pastSma.Value or currSma.Value? It might be easier to check the error if you could attach the complete backtest 

0

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.


Yeah thanks, I've started this over.  Instead of trying to convert the whole algo at once I'm starting from the basics and from scratch.  I didn't realize how much different this is from quantopian.  So I've got an algo going with just one stock, SVXY, and I have the rolling window at least calculating some value which I'm able to log to track whats going on.  The values are not correct however.  I'm looking to obtain a value for the SMA of the close of the last 225 minute bars and then also what the SMA225minute value is for the last minute time point.  

If I do this correctly and log the current and past SMA.  The current SMA should read a value at 9:31.  At 9:32 the current SMA value should be new and the previous SMA value at 9:32 should be equal to what the current SMA value at 9:31 was.  However, in my log I'm definitely not getting that. 

0


Hi David, the values are correct. You are comparing the value of first SMA[0] and the last SMA[224]. As you said ' The current SMA should read a value at 9:31.  At 9:32 the current SMA value should be new and the previous SMA value at 9:32 should be equal to what the current SMA value at 9:31 was', you should compare the value of the first SMA[0] with the value of the previous one SMA[1] instead of the oldest SMA.

0

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.


Doh!  That's awesome thanks!  One more thing should help me get quite a bit further on my own.  How can I just add and subtract values?  Now that I have currSMA and prevSMA.  How can I make a line of code stating:

Slope = currSMA - prevSMA

 

I tried and the backtests doesn't accept the minus symbol.  Thought you could just do simple math anywhere in the algo

0

Hi David, you could subtract values like this

slope = currSma.Value - pastSma.Value
0

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.


Update Backtest





0

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.


Loading...

This discussion is closed