I would like to have this program run for 10-15 symbols. How can I do that without restructuring the entire program?
Can I just make a list and put the list name in the space where the symbol went?
I just posted the first half of my code... I think it gets the point across...
Thanks in advance!!
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)
tsla = self.AddEquity("TSLA", Resolution.Minute)
tsla.SetDataNormalizationMode(DataNormalizationMode.Raw)
self.Consolidate("TSLA", timedelta(minutes=30), self.OnDataConsolidated)
#3. Create a scheduled event triggered at 13:30 calling the ClosePositions function
self.Schedule.On(self.DateRules.EveryDay("TSLA"), self.TimeRules.At(13,30), self.ClosePositions)
def OnData(self, data):
# 1. Plot the current SPY price to "Data Chart" on series "Asset Price"
#self.Plot("Data Chart", "Asset Price", data["SPY"].Close)
if self.openingBar is None:
return
#if not self.Portfolio.Invested:
# self.MarketOrder("SPY", 500)
# self.stopMarketTicket = self.StopMarketOrder("SPY", -500, 0.9 * self.Securities["SPY"].Close)
if data["TSLA"].Close > self.openingBar.High and not self.Portfolio.Invested:
self.Debug("high of 30m bar: " + str(self.openingBar.High)) # print the high of the 30 minute bar
self.Debug("opening price bar where signal triggered " + str(data["TSLA"].Open)) # print the opening of the first minute bar after the initial 30 minute bar
#self.SetHoldings("TSLA", .5) # invest half of cash into it
self.MarketOrder("TSLA", 500) # orders 500 shares
self.Debug("price paid avg: " + str(self.Portfolio["TSLA"].AveragePrice))
Derek Melchin
Hi M Cochran,
We can run the algorithm above with a list of symbols. However, it requires some restructuring. See the attached backtest for reference. Note that since the algorithm above is incomplete, the attached algorithm doesn't place any trades.
To get more familiar with our API, consider reviewing our Introduction to Financial Python tutorial.
Best,
Derek Melchin
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.
M Cochran
class BootCampTask(QCAlgorithm): # Order ticket for our stop order, Datetime when stop order was last hit stopMarketTicket = None stopMarketOrderFillTime = datetime.min highestTSLAPrice = 0 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: self.Debug("symbol: " + str(data[symbol]) + "high of 30m bar: " + str(self.openingBar.High)) # print the high of the 30 minute bar self.Debug("opening price bar where signal triggered " + str(data[symbol].Close)) # print the opening of the first minute bar after the initial 30 minute bar quantity = self.CalculateOrderQuantity(symbol, 0.4) self.MarketOrder(symbol, quantity) # orders 40% of portfolio self.Debug("price paid avg: " + str(self.Portfolio[symbol].AveragePrice)) self.Debug("shares: " + str(self.Portfolio[symbol].Quantity)) self.Debug(" current price: " + str(self.Portfolio[symbol].Price)) self.stopMarketTicket = self.StopMarketOrder(symbol, -500, 0.95 * self.Securities[symbol].Close) if self.Portfolio.Invested and data[symbol].Close > self.highestTSLAPrice: self.highestTSLAPrice = self.Securities[symbol].Close updateFields = UpdateOrderFields() updateFields.StopPrice = self.highestTSLAPrice * 0.95 self.stopMarketTicket.Update(updateFields) #3. Print the new stop price with Debug() self.Debug(str(data[symbol]) + str(self.highestTSLAPrice) + " Stop: " + str(updateFields.StopPrice)) def OnOrderEvent(self, orderEvent): if orderEvent.Status != OrderStatus.Filled: self.Debug("supposedly closed") #self.Portfolio.Invested) self.openingBar = None return if self.stopMarketTicket is not None and self.stopMarketTicket.OrderId == orderEvent.OrderId: print("closing order") self.stopMarketOrderFillTime = self.Time def OnDataConsolidated(self, bar): 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(symbol) 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
awesome! Thanks Derek! I never would have gotten that. I think I'm really close now to having a working program.
Still I'm having trouble getting the program to itterate through multiple symbols. Part of this involves the 30 minute consolidated bar. How would I consolidate into a 30 minute bar for multiple tickers? I've gone ahead and pasted the entire script. Thanks for your help. I really appreciate it.
Derek Melchin
Hi M Cochran,
Isolating the consolidation part of the code, we can see the algorithm already successfully consolidates 30-minute bars for both securities. See the attached backtest logs for reference.
Best,
Derek Melchin
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.
M Cochran
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!