Back

SPY Leveraged Pullback beginner help

I'm new here and to Python in general, and am trying to port my scripts from thinkorswim into QuantConnect and am having beginner's confusion.

This is the start of my SPY pullback strategy. Right now I only have 2 questions:

1. what is the sytax error I am getting and how do i fix it?

2. how do I define variables in python for buy and sell orders. For example I want to have a primary condition, in this case SPYHigh>SMA200. and use this to determine if I buy with 1 set of criteria or another. I have these conditions ## out in the code.

 

import numpy as np

class BasicTemplateAlgorithm(QCAlgorithm):
    '''Basic template algorithm simply initializes the date range and cash'''

    def Initialize(self):
        self.SetStartDate(2007,1, 1)  #Set Start Date
        self.SetEndDate(2018,9,31)    #Set End Date
        self.SetCash(10000)           #Set Strategy Cash
        self.AddEquity("SPY", Resolution.Day)
        self.AddEquity("UPRO", Resolution.Day)
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage) 
        self.RSI = self.RSI("SPY", 2)
        SMA200 = self.sma = self.SMA("SPY", 200)
        SMA20 = self.sma = self.SMA("SPY", 20) ## will use this later on

    def OnData(self, data):
        
        if not self.RSI.IsReady: 
            return
        
#var buy1 = RSI<24 && adx>20;
#var buy2 = RSI<10 && adx>30;
#if _spyhigh>Avg200 then buy1 else buy2;

        if self.spy.Current.High>SMA200 && rsi<24 and self.Portfolio["UPRO"].Invested <= 0:
            self.Debug("UPRO buy")
            self.MarketOrder("UPRO", 5000)
            self.Debug("Market order was placed")
        
#var sell1 = _spy>_Avg20 && RSI>85;
#var sell2 = _spy>Avg20 && RSI>80;
#if _spyhigh<SMA200 then sell1 else sell2;        
        
        if self.spy.Current.High<SMA200 then rsi<80 else rsi>85:
            self.Debug("UPRO sell")
            self.Liquidate()

 

Thanks!

Update Backtest







Thanks for attaching the code! I would suggest trying the Bootcamp. It is a series of tutorials for new users to help get them familiar with LEAN.

Here are the errors I spotted in the code:

self.SetEndDate(2018,9,31)

I changed this to September 30th, since September 31st is not a day.

self.spy = self.AddEquity("SPY", Resolution.Day)

The correct syntax for this is Resolution.Daily, not Resolution.Day. Here is the documentation for initializing algorithms. These go into detail regarding syntax and functionality.

 

In order to define variables for the algorithm, you need to use self._____. The term self is referencing the QCAlgorithm object. As a result, the lines:

self.rsi = self.RSI("SPY", 2)
self.sma200 = self.SMA("SPY", 200)
self.sma20 = self.SMA("SPY", 20) ## will use this later on

allow us to reference the indicators later. Here is the documentation for Indicators. The indicators in the above code need to be accessed via:

self.sma200.Current.Value

In this line, we are accessing the current value of the indicator. This, however, does not work for TradeBar objects that are given during the OnData(self, data) function. This needs to be accessed via:

data[self.spy.Symbol].High

Here is the documentation for handling the data that comes through OnData. The slice object is the object that contains all the relevant information for a specific time period, which we determine using Resolution. We then access the TradeBar, which is indexed via the stock symbol. Below is the running algorithm. Feel free to compare the code:

0


Thanks so much for that. That is very helpful.

Another question I have is how to determine the low or high for a specified length of time? For example I want to check for the lowest low in the current bar for the last 10 bars? I didn't see anything in the Indicators section, unless I missed it.

0

You can use the "MAX" and "MIN" indicator to get the lowest low for a specified length of time.

For example,

# in Initialize(), define the indicator to get the minimum of low price in the last ten daily bars
self.min = self.MIN("SPY", 10, Resolution.Daily, Field.Low)
# in OnData(), get the indicator value
if self.min.IsReady:
lowest_low = self.min.Current.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.


Thanks Jing!  

0

I'm having trouble getting the Closing Range defined in python. The logic is (close – low) / (high – low) to get a ratio from 0-1.

And I have this below, but it must not be structured right or I am not understanding how to write it out:

self.VixClosingRng = self.RegisterIndicator("VIX", (data[self.vix.Symbol].Close – data[self.vix.Symbol].Low) / (data[self.vix.Symbol].High – data[self.vix.Symbol].Low), Resolution.Daily)

0

You can create a custom indicator to calculate the closing range then you can update this indicator with self.RegisterIndicator(). Please see the attached example

Alternatively, as the closing range only has one period. You can calculate the value with the formula directly in OnData() without the custom indicator

data[self.vix.Symbol].Close – data[self.vix.Symbol].Low) / (data[self.vix.Symbol].High – data[self.vix.Symbol].Low 

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 so much for your help Jing. I was close but now I understand I can calculate simple values in the OnData for single bars.

Taking what you provided, I’m still not understanding how to put that into OnData correctly. Can you help here? Attached is my backtest with the VIX closing range logic on line 45.

0


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