Hi All,
I am new here. When I applied the simple strategy, it pops up below error. Could anyone help? Thanks a lot.
Best Regards,
Yao Yiyang
Code:
import numpy as np
import datetime
class SellInMayBuyInNov(QCAlgorithm):
def Initialize(self):
self.SetStartDate(1998,1, 1) #Set Start Date
self.SetEndDate(2019,2,1) #Set End Date
self.SetCash(1000000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.AddEquity("SPY", Resolution.Minute,Leverage=4,fillDataForward = True, extendedMarketHours = False)
self.SetRunMode(RunMode.Series)
def OnData(self, data):
if self.Time.month == 5:
if self.Portfolio.Invested:
self.SetHoldings("SPY", -Qty)
self.Debug("Sell In May" + Time.year +" Quantity:"+Qty)
elif self.Time.month == 11:
if not self.Portfolio.Invested:
Qty= self.Portfolio.Cash/["SPY"].Close
self.SetHoldings("SPY", Qty)
self.Debug("Buy In Nov" + Time.year+" Quantity:"+Qty)
Gurumeher Sawhney
Hi Yao, The error is in the line:
Qty= self.Portfolio.Cash/["SPY"].Close
This is because the data for SPY needs to be accessed using:
Qty= self.Portfolio.Cash/data["SPY"].Close
Below is a working backtest:
Yao Yiyang
Hi Gurumeher,
Thanks a lot, The algorithm works. But may I ask why there is no even one trade activated? Based on the algorithm, it should buy at Nov period which the timeframe has covered.
Thanks.
Yao Yiyang
Error here.:)
Eric Kirk
It looks like you're ordering more than your margin allows. You're only allowed 2x leverage for a margin account. If you switch to a pattern day trade model you're allowed 4x intraday and 2x leverage overnight. You can try adding the pattern day trade model to initialize or setting leverage to 2 . Go to the cash and brokerage models in documentation to read more.
Eric
https://www.quantconnect.com/docs/algorithm-reference/initializing-algorithmsYao Yiyang
Hi Eric,
Thanks. I changed the leverage=1 but still see the same error. One finding is, it keeps buying until cannot buy any more, But cannot see any sell action. Any logic problem of the script?
Thanks
Yao Yiyang
import numpy as np
import datetime
class SellInMayBuyInNov(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2018,1, 1) #Set Start Date
self.SetEndDate(2019,2,1) #Set End Date
self.SetCash(10000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.AddEquity("SPY", Resolution.Minute,Leverage=1,fillDataForward = True, extendedMarketHours = False)
self.SetRunMode(RunMode.Series)
def OnData(self, data):
if self.Time.month == 5:
if self.Portfolio.Invested:
self.SetHoldings("SPY", -Qty)
self.Debug("Sell In May " + str(self.Time.year) +" Quantity:"+ str(Qty))
elif self.Time.month == 11:
if not self.Portfolio.Invested:
Qty= self.Portfolio.Cash/data["SPY"].Close
self.SetHoldings("SPY", Qty)
self.Debug("Buy In Nov " + str(self.Time.year) +" Quantity:"+str(Qty))
Gurumeher Sawhney
Hi Yao, few things to consider when creating this algorithm:
The algorithm runs in minute resolution. Is there a reason to why you are iterating through all that data if you only trade twice a month?
Also if you would like to use all of the cash in your portfolio to buy SPY, the line using SetHoldings can just be:
//to sell self.SetHoldings("SPY", -1) //to buy self.SetHoldings("SPY", 1)
Below is a backtest that should run to the specifications you want:
Yao Yiyang
Hi Gurumeher,
Thanks for sharing. I copied your code but found some strange thing from the trades.
1. Orignally, it only bought 3950 shares of SPY in Nov'2017 but can sell 7886 shares in May'2018? The quantity not match.
2.By right, in May, it only allows sell action. But you can see below, it also has "buy" action in May.
Gurumeher Sawhney
Yao, I apologize, it looks like I took a short position in May instead of liquidating the assets. Here is the update! I just changed line 17.
Yao Yiyang
Thanks a lot for your help Guru
Yao Yiyang
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.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!