Hi, so we were using multiple tickets. Specifically SPY and TESLA. And the problem is that when the backtest it's working, this error appears:
This is the ERROR!class BootCampTask(QCAlgorithm):
# Order ticket for our stop order, Datetime when stop order was last hit
stopMarketTicket = None
stopMarketOrderFillTime = datetime.min
highestTSLAPrice = 0
openingBar = None
def Initialize(self):
self.SetStartDate(2017, 10, 2)
self.SetEndDate(2019, 5, 30)
self.SetCash(100000)
self.SetSecurityInitializer(self.CustomSecurityInitializer)
tickers = ['SPY','TSLA']
self.symbol_data_by_symbol = {}
for ticker in tickers:
openingBar = None
symbol = self.AddEquity(ticker, Resolution.Minute).Symbol
self.symbol_data_by_symbol[symbol] = SymbolData()
self.Consolidate(symbol, timedelta(minutes=30), self.OnDataConsolidated)
self.Schedule.On(self.DateRules.EveryDay(symbol), self.TimeRules.At(13,30), self.ClosePositions)
#3. Create a scheduled event triggered at 13:30 calling the ClosePositions function
def CustomSecurityInitializer(self, security):
security.SetDataNormalizationMode(DataNormalizationMode.Raw)
def OnData(self, data):
if self.openingBar is None:
return
for symbol, symbol_data in self.symbol_data_by_symbol.items():
if not data.ContainsKey(symbol) or data[symbol] is None:
continue
if data[symbol].Close > self.openingBar.High and not self.Portfolio.Invested:
quantity = self.CalculateOrderQuantity(symbol, 0.45)
self.MarketOrder(symbol, quantity) # orders 45% of portfolio
self.stopMarketTicket = self.StopMarketOrder(symbol, -self.Portfolio[symbol].Quantity, data[symbol].Close * 0.9)
if self.Portfolio.Invested and data[symbol].Close > self.highestTSLAPrice:
self.highestTSLAPrice = self.Securities[symbol].Close
updateFields = UpdateOrderFields()
updateFields.StopPrice = self.highestTSLAPrice * 0.9
self.stopMarketTicket.Update(updateFields)
def OnOrderEvent(self, orderEvent):
if orderEvent.Status != OrderStatus.Filled:
self.openingBar = None
return
if self.stopMarketTicket is not None and self.stopMarketTicket.OrderId == orderEvent.OrderId:
self.stopMarketOrderFillTime = self.Time
def OnDataConsolidated(self, bar):
self.Log(f"Bar at {self.Time} for {bar.Symbol}")
if bar.Time.hour == 9 and bar.Time.minute == 30:
self.openingBar = bar
def ClosePositions(self):
#2. Set self.openingBar to None, and liquidate TSLA
self.openingBar = None
self.Liquidate() # liquidate entire portfolio
class SymbolData:
def __init__(self):
# Order ticket for our stop order, Datetime when stop order was last hit
stopMarketTicket = None
stopMarketOrderFillTime = datetime.min
highestPrice = 0
openingBar = None
This is the code. And the information required only appears for a single ticket, in this case only for TSLA. Thanks!!
Yaros
The problem it's that the backtest it's not working, I got confused before. I will appreciate any help I've having this error.
Louis Szeto
Hi Yaros,
Your algorithm will work on single ticker. However, if you need to use multiple tickers, you will need to hash through the corresponding data mapped for the particular ticker in your created dictionary self.symbol_data_by_symbol. If you do not store and call the data inside the particular key-value-pair in the dictionary (SymbolData class object), the variables will be overwritten by another symbol's data causing errors.
Also, you will need to use prefix of "self." in order to make the variables public and static, such that it is callable and modifiable in future.
We suggest using data.Bars[symbol] instead of data[symbol] as data object might not contain tradebar.
The attached backtest is for your reference. Hope it helps!
Best,
Louis Szeto
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.
Yaros
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!