I am new to QC and I am trying to understand how to use RollingWindow[ ] to get previous data for multiple equities and indicators.
I have been studying Python and so I prefer the example in Python.
I have searched the forum and studied the examples and I have not been able to determine how to apply RollingWindow[ ] to multiple equities.
Your help is appreciated.
Thank you.
Michael Manus
as i remember it right this sample uses an class that stores info about some stocks.
you would need to create such class that stores rolling window for every stock: -> class SymbolData(object):
Michael Manus
Jared Broad the python equivalent for MultipleSymbolConsolidationAlgorithm.cs is missing with storing rolling window in class for multiple symbols.....second or third time people asking in a week :)
Jared Broad
Ty! Will add tomorrow :)
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.
Hal Trade
Thank you for the reply Michael and Jared.
Michael I looked at the code that you referenced above (EmaCrossUniverseSelectionAlgorithm.py) and I did not see how I could use the code to do what I need to do.
I want to look back at previous prices (OHLC) and indicators (SMA etc) for multiple stocks and or ETFs. And when the right conditions occur take a position or close a position at that time.
If there is some other way to do this I would really appreciate your thoughts.
Thank you for your time :).
Michael Manus
you would need to add a rolling window in that class as you already know it
so you can look back to the values you added in the window.
thats a simpler example.....take a look....it holds info of some etfs:
Hal Trade
Michael,
Will you please give me an example of how I would add a rolling window to the strategy.
Thank you.
Jing Wu
Hi Michael and hal_trade, MultipleSymbolConsolidationAlgorithm python version has been added.
Michael Manus
thanks Jing Wu ......
one last hint:
when i copy the code in the lab it says : unexpected indent
here in line 94:
+def OnEndOfDay(self): + + i = 0 + for symbol in sorted(self.Data.keys()):
but then after moving the for loop to the left:
Failed to initialize algorithm: Initialize(): Python.Runtime.PythonException: AttributeError : 'MultipleSymbolConsolidationAlgorithm' object has no attribute 'OnDataConsolidated'
at QuantConnect.AlgorithmFactory.Python.Wrappers.AlgorithmPythonWrapper.Initialize () [0x00045] in <0c88b9ca11b74259bd317eba6892dda0>:0
at QuantConnect.Lean.Engine.Setup.BacktestingSetupHandler+<>c__DisplayClass19_0.<Setup>b__0 () [0x0007c] in <c118b4a93df0492aa91bee9d82a40e78>:0 (Open Stacktrace)
Michael Manus
ok sorry the output was not well formated in github after clicking on raw:
Raw MultipleSymbolConsolidationAlgorithm.py
Michael Manus
thanks Jing Wu for implementing it for Hal Trade
everything works as expected :)
Hal Trade
Jing Wu and Michael Manus I really appreciate your work.
Thank you for helping the community.
I will be working to implement this into my strategy.
Hal Trade
Michael, I cloned you algorithm above and when I run the backtest I get an error on the console:
Backtest Handled Error: Unable to submit order with id -10 which quantity (1) is less than lot size (1000).What does this error mean?
Michael Manus
the example has a problem....it buys every stock and currency of quantitiy 1 in his list. because of lot size quantitiy of 1000 has to be taken for buying a currency. thats why this example buys only stocks and gets order errors in the log for buying currencies.
Michael Manus
the example above will not work anymore because of using the older python 2.7 which changed to 3.6:
self.SetStartDate(2014, 12, 01)->
self.SetStartDate(2014, 12, 1) for symbol, symbolData in self.Data.iteritems():->
for symbol, symbolData in self.Data.items():OPS Agra
Hello im very new to QuantConnect, I just read this forum and found it very helpful. I have a question, is it possibe to use the rolling window and make a trigger for market order if most recent info '[0]' > second recent '[1]'. or currentprice > '[0]'. Based on the code Jing Wu posted above?Â
Michael Manus
Thank you
Alexandre Catarino
Hi OPS AgraÂ
In Jing's example, we have:
def OnData(self,data): # loop through each symbol in our structure for symbol in self.Data.keys(): symbolData = self.Data[symbol] # this check proves that this symbol was JUST updated prior to this OnData function being called if symbolData.IsReady() and symbolData.WasJustUpdated(self.Time): if not self.Portfolio[symbol].Invested: self.MarketOrder(symbol, 1)
where symbolData object has an attribute Bars which is a RollingWindow. with size 10,
Say we want to open a position for symbol if the close of the last element is bigger than the previous:
if (not self.Portfolio[symbol].Invested and symbolData.Bars[0].Close > symbolData.Bars[1].Close): self.MarketOrder(symbol, 1)
or the current price is bigger than the close of the previous element:Â
if (not self.Portfolio[symbol].Invested and data[symbol].Close > symbolData.Bars[1].Close): self.MarketOrder(symbol, 1)
Please do not skip the Bootcamp and the docs.Â
Anthony FJ Garner
Can I assume that this algo: ETF Global Rotation is less efficient than this: addMultiplesymbolConsolidator because the latter adds incrementally to the indicators/moving window while the formere calls for all fresh data each time?
Â
Â
Alexandre Catarino
Hi Anthony FJ Garner ,
Perhaps I didn't understand your comment well. However, the former, ETF Global Rotation, doesn't call for fresh data each time and both algorithms are equally efficient in the sense that they use Lean features correctly.
Grateful Trading
I've found this post and others like it very useful in my project. Â
One question for Alexandre Catarinoor any other brilliant Quant... In the working, adapted algo attached below, how is the indicator data stored in the rolling window bar?  How can it be accessed?  With MACD, are all three data points (fast, signal, slow) being stored in the rolling window?  If not, how should this be done when multiple equities are involved?  Many thanks.
from System import * from QuantConnect import * from QuantConnect.Data.Consolidators import * from QuantConnect.Data.Market import * from QuantConnect.Orders import OrderStatus from QuantConnect.Algorithm import QCAlgorithm from QuantConnect.Indicators import * import numpy as np from datetime import timedelta, datetime class MultipleSymbolConsolidationAlgorithm(QCAlgorithm): def Initialize(self): RollingWindowSize = 50 self.Data = {} EquitySymbols = ["AAPL","SPY","IBM"] # Date bookends self.SetStartDate(2014, 12, 1) self.SetEndDate(2016, 1, 1) # initialize our equity data for symbol in EquitySymbols: equity = self.AddEquity(symbol, Resolution.Daily) self.Data[symbol] = SymbolData(equity.Symbol, RollingWindowSize) # loop through all our symbols and request data subscriptions and initialize indicator for symbol, symbolData in self.Data.items(): # define the indicator symbolData.MACD = MovingAverageConvergenceDivergence("MACD", 12, 26, 9, Resolution.Daily) # define a consolidator to consolidate data for this symbol on the requested period consolidator = TradeBarConsolidator(1) # write up our consolidator to update the indicator consolidator.DataConsolidated += self.OnDataConsolidated # we need to add this consolidator so it gets auto updates self.SubscriptionManager.AddConsolidator(symbolData.Symbol, consolidator) def OnDataConsolidated(self, sender, bar): self.Data[bar.Symbol.Value].MACD.Update(bar.Time, bar.Close) self.Data[bar.Symbol.Value].Bars.Add(bar) def OnData(self,data): # loop through each symbol in our structure for symbol in self.Data.keys(): symbolData = self.Data[symbol] if symbolData.IsReady() : ## This works and shows all data points are accessible self.Debug(str(symbol) + str(symbolData.MACD.Slow.Current.Value)) self.Debug(str(symbol) + str(symbolData.MACD.Fast.Current.Value)) ## This does not work.. what is the correct way to access the indexed MACD values? #self.Debug(str(symbol) + str(symbolData.Bars[0].MACD.Fast)) class SymbolData(object): def __init__(self, symbol, windowSize): self.Symbol = symbol self.Bars = RollingWindow[IBaseDataBar](windowSize) # The MACD indicator for our symbol self.MACD = None # Returns true if all the data in this instance is ready (indicators, rolling windows, ect...) def IsReady(self): return self.Bars.IsReady and self.MACD.IsReady
Â
Hal Trade
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!