Hi guys,
I was trying to use Rollingwindow to store the past daily trade bars for futures contract, but got an error when I try to add futures symbol object to the rolling window. What's weird is that the exact same code works perfectly fine for Equities, but not for Futures object for some reason. I would really appreciate if someone could help me take a look.
Thanks!
Here's the error message:
Runtime Error: Trying to dynamically access a method that does not exist throws a TypeError exception. To prevent the exception, ensure each parameter type matches those required by the 'QuantConnect.Data.Market.QuoteBar'>) method. Please checkout the API documentation.
at OnData
self.window.Add(data[self.contract.Symbol])
at Python.Runtime.PythonException.ThrowLastAsClrException()
at Python.Runtime.PyObject.Invoke(PyTuple args in main.py: line 66
Here's my code:
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from AlgorithmImports import *
### <summary>
### Using rolling windows for efficient storage of historical data; which automatically clears after a period of time.
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="history and warm up" />
### <meta name="tag" content="history" />
### <meta name="tag" content="warm up" />
### <meta name="tag" content="indicators" />
### <meta name="tag" content="rolling windows" />
class RollingWindowAlgorithm(QCAlgorithm):
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.SetStartDate(2013,10,1) #Set Start Date
self.SetEndDate(2013,11,1) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.contract = self.AddFuture(Futures.Indices.SP500EMini,
resolution = Resolution.Daily,
dataNormalizationMode = DataNormalizationMode.BackwardsRatio,
dataMappingMode = DataMappingMode.LastTradingDay,
contractDepthOffset= 0)
# self.contract = self.AddEquity("SPY", Resolution.Daily)
# Creates a Rolling Window indicator to keep the 2 TradeBar
self.window = RollingWindow[TradeBar](20) # For other security types, use QuoteBar
# Creates an indicator and adds to a rolling window when it is updated
self.sma = self.SMA(self.contract.Symbol, 5)
self.sma.Updated += self.SmaUpdated
self.smaWin = RollingWindow[IndicatorDataPoint](5)
history_trade_bar = self.History[TradeBar](self.contract.Symbol, 20, Resolution.Daily)
for trade_bar in history_trade_bar:
self.window.Add(trade_bar)
def SmaUpdated(self, sender, updated):
'''Adds updated values to rolling window'''
self.smaWin.Add(updated)
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# Add SPY TradeBar in rollling window
self.window.Add(data[self.contract.Symbol])
# Wait for windows to be ready.
if not (self.window.IsReady and self.smaWin.IsReady): return
currBar = self.window[0] # Current bar had index zero.
pastBar = self.window[1] # Past bar has index one.
self.Log("Price: {0} -> {1} ... {2} -> {3}".format(pastBar.Time, pastBar.Close, currBar.Time, currBar.Close))
currSma = self.smaWin[0] # Current SMA had index zero.
pastSma = self.smaWin[self.smaWin.Count-1] # Oldest SMA has index of window count minus 1.
self.Log("SMA: {0} -> {1} ... {2} -> {3}".format(pastSma.Time, pastSma.Value, currSma.Time, currSma.Value))
if not self.Portfolio.Invested and currSma.Value > pastSma.Value:
self.SetHoldings(self.contract.Symbol, 1)
self.Plot('Benchmark', 'Past Bar', pastBar.Close)
Louis Szeto
Hi Kay
The `data` received in OnData handler is a Slice object but not a TradeBar object. Thus, updating a TradeBar RollingWindow with a Slice will receive a TypeError. You could update with TradeBar by:
Another thing is that you'll have to place a trade with the mapped future contract's symbol rather than the contionuous future's canonical symbol:
Best
Louis
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.
Kay Zhou
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!