Quant League is evolving into Strategies, our new home for sharing, discovering, and exploring trading strategies, with improved organization and a better overall experience. Q4-2025 will be the final Quant League.
LEAN is the open-source algorithmic trading engine powering QuantConnect.
Founded in 2012 LEAN has been built by a global community of 180+ engineers and powers more than 300+ hedge funds today.
Join Our Discord Channel
Join QuantConnect's Discord server for real-time support, where a vibrant community of traders and developers awaits to help you with any of your QuantConnect needs.
This research is under review. To publish this research attract three community upvotes.
This research is under review. To publish this research attract three community upvotes.
This discussion is a draft. Click here to publish this discusison.
Type Error
Hi there, I am getting an error which says: 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 Add method. Please checkout the API documentation. at OnData in main.py:line 55 TypeError : No method matches given arguments for Add (Open Stacktrace).
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.
Alex Haseldine
412
,
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Brokerages import *
from QuantConnect.Orders import *
import numpy as np
class RollingWindowAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2004, 1, 1) #Set Start Date
self.SetEndDate(2017, 12, 12) #Set End Date
self.SetCash(100000) #Set Strategy Cash
self.SetBrokerageModel(BrokerageName.FxcmBrokerage)
self.AddEquity("SPY", Resolution.Daily)
self.window = RollingWindow[TradeBar](2)
# create a bollinger band
self.Bolband = self.BB("SPY", 20, 0.7, MovingAverageType.Simple, Resolution.Daily)
self.Bolband.Updated += self.BolbandUpdated
self.BolbandWin = RollingWindow[IndicatorDataPoint](5)
# create a simple moving average
self.sma = self.SMA("SPY", 50, Resolution.Daily)
self.sma.Updated += self.SMAUpdated
self.smaWin = RollingWindow[IndicatorDataPoint](5)
# set warmup period
self.SetWarmUp(50)
self.SetBenchmark("SPY")
def BolbandUpdated(self, sender, updated):
'''Adds updated values to rolling window'''
self.BolbandWin.Add(updated)
def SMAUpdated(self, sender, updated):
self.smaWin.Add(updated)
def OnData(self, data):
self.window.Add(data["SPY"].Close)
if not (self.window.IsReady and self.BolbandWin.IsReady): return
holdings = self.Portfolio["SPY"].Quantity
price = self.window[0].Close
previousPrice = self.window[1].Close
Buy_below_lowerband = (previousPrice <= self.Bolband.LowerBand.Current.Value) and (price > self.Bolband.LowerBand.Current.Value)
Liquidate_at_middleband_from_lowerband = (previousPrice > self.Bolband.MiddleBand.Current.Value and price == self.Bolband.MiddleBand.Current.Value)
Go_Long = (previousPrice < self.sma.Current.Value and price == self.sma.Current.Value)
Go_Short = (previousPrice > self.sma.Current.Value and price == self.sma.Current.Value)
if holdings <= 0:
if Buy_below_lowerband:
self.SetHoldings("SPY", 1.0)
if previousPrice == self.sma.Current.Value and price < self.sma.Current.Value:
self.Liquidate()
self.SetHoldings("SPY", -1.0)
if Go_Long:
self.Liquidate()
elif Liquidate_at_middleband_from_lowerband:
self.Liquidate()
if previousPrice >= self.Bolband.UpperBand.Current.Value and price < self.Bolband.UpperBand.Current.Value:
self.SetHoldings("SPY", -1.0)
if previousPrice == self.sma.Current.Value and price > self.sma.Current.Value:
self.Liquidate()
self.SetHoldings("SPY", 1.0)
if Go_Short:
self.Liquidate
elif Liquidate_at_middleband_from_lowerband:
self.Liquidate()
if holdings > 0:
if previousPrice >= self.Bolband.UpperBand.Current.Value and price < self.Bolband.UpperBand.Current.Value:
self.SetHoldings("SPY", -1.0)
if previousPrice == self.sma.Current.Value and price > self.sma.Current.Value:
self.Liquidate()
self.SetHoldings("SPY", 1.0)
if Go_Short:
self.Liquidate
elif Liquidate_at_middleband_from_lowerband:
self.Liquidate()
if Buy_below_lowerband:
self.SetHoldings("SPY", 1.0)
if previousPrice == self.sma.Current.Value and price < self.sma.Current.Value:
self.Liquidate()
self.SetHoldings("SPY", -1.0)
if Go_Long:
self.Liquidate
elif Liquidate_at_middleband_from_lowerband:
self.Liquidate()
Alex Haseldine
412
,
Sorry I couldn't work out how to attactch a code in the normal way because the back test didn't work.
Jing Wu
242.2k
,
The rolling window is set to be the TradeBar type in the definition "self.window = RollingWindow[TradeBar](2)". You should add the TradeBar to self.window. While the type of "data["SPY"].Close" is Decimal. You should use "self.window.Add(data["SPY"])". To make sure the slice data contains the key "SPY", please add the check
if data.Bars.ContainsKey("SPY"):
self.window.Add(data["SPY"])
Another issue is the brokerage model. FXCM brokerage is used for Forex trading. For equity, please use the InteractiveBrokersBrokerage model.
To attach the backtest, you'll find the button "Attach Backtest" when you edit the comment. You can choose the project and the backtest to add in the comment.
Alex Haseldine
412
,
Thank you for your help,
what do you mean by 'You should add the TradeBar to self.window.'?
TradeBar is one of the data types that is to OnData(self, data). OnData provides a Slice object that contains all the data for a given moment of time. TradeBars and QuoteBars are symbol/string indexed dictionaries so you can easily access the data. When Jing is saying add the TradeBar to self.window, she means take that object and save it in the RollingWindow for later use. TradeBar data gives access to the OHLCV data for the specific symbol.
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!
Allocate to this Strategy
Institutional clients can contact the author and allocate capital to this strategy.
Alex Haseldine
from clr import AddReference AddReference("System") AddReference("QuantConnect.Algorithm") AddReference("QuantConnect.Common") from System import * from QuantConnect import * from QuantConnect.Algorithm import * from QuantConnect.Brokerages import * from QuantConnect.Orders import * import numpy as np class RollingWindowAlgorithm(QCAlgorithm): def Initialize(self): self.SetStartDate(2004, 1, 1) #Set Start Date self.SetEndDate(2017, 12, 12) #Set End Date self.SetCash(100000) #Set Strategy Cash self.SetBrokerageModel(BrokerageName.FxcmBrokerage) self.AddEquity("SPY", Resolution.Daily) self.window = RollingWindow[TradeBar](2) # create a bollinger band self.Bolband = self.BB("SPY", 20, 0.7, MovingAverageType.Simple, Resolution.Daily) self.Bolband.Updated += self.BolbandUpdated self.BolbandWin = RollingWindow[IndicatorDataPoint](5) # create a simple moving average self.sma = self.SMA("SPY", 50, Resolution.Daily) self.sma.Updated += self.SMAUpdated self.smaWin = RollingWindow[IndicatorDataPoint](5) # set warmup period self.SetWarmUp(50) self.SetBenchmark("SPY") def BolbandUpdated(self, sender, updated): '''Adds updated values to rolling window''' self.BolbandWin.Add(updated) def SMAUpdated(self, sender, updated): self.smaWin.Add(updated) def OnData(self, data): self.window.Add(data["SPY"].Close) if not (self.window.IsReady and self.BolbandWin.IsReady): return holdings = self.Portfolio["SPY"].Quantity price = self.window[0].Close previousPrice = self.window[1].Close Buy_below_lowerband = (previousPrice <= self.Bolband.LowerBand.Current.Value) and (price > self.Bolband.LowerBand.Current.Value) Liquidate_at_middleband_from_lowerband = (previousPrice > self.Bolband.MiddleBand.Current.Value and price == self.Bolband.MiddleBand.Current.Value) Go_Long = (previousPrice < self.sma.Current.Value and price == self.sma.Current.Value) Go_Short = (previousPrice > self.sma.Current.Value and price == self.sma.Current.Value) if holdings <= 0: if Buy_below_lowerband: self.SetHoldings("SPY", 1.0) if previousPrice == self.sma.Current.Value and price < self.sma.Current.Value: self.Liquidate() self.SetHoldings("SPY", -1.0) if Go_Long: self.Liquidate() elif Liquidate_at_middleband_from_lowerband: self.Liquidate() if previousPrice >= self.Bolband.UpperBand.Current.Value and price < self.Bolband.UpperBand.Current.Value: self.SetHoldings("SPY", -1.0) if previousPrice == self.sma.Current.Value and price > self.sma.Current.Value: self.Liquidate() self.SetHoldings("SPY", 1.0) if Go_Short: self.Liquidate elif Liquidate_at_middleband_from_lowerband: self.Liquidate() if holdings > 0: if previousPrice >= self.Bolband.UpperBand.Current.Value and price < self.Bolband.UpperBand.Current.Value: self.SetHoldings("SPY", -1.0) if previousPrice == self.sma.Current.Value and price > self.sma.Current.Value: self.Liquidate() self.SetHoldings("SPY", 1.0) if Go_Short: self.Liquidate elif Liquidate_at_middleband_from_lowerband: self.Liquidate() if Buy_below_lowerband: self.SetHoldings("SPY", 1.0) if previousPrice == self.sma.Current.Value and price < self.sma.Current.Value: self.Liquidate() self.SetHoldings("SPY", -1.0) if Go_Long: self.Liquidate elif Liquidate_at_middleband_from_lowerband: self.Liquidate()Alex Haseldine
Sorry I couldn't work out how to attactch a code in the normal way because the back test didn't work.
Jing Wu
The rolling window is set to be the TradeBar type in the definition "self.window = RollingWindow[TradeBar](2)". You should add the TradeBar to self.window. While the type of "data["SPY"].Close" is Decimal. You should use "self.window.Add(data["SPY"])". To make sure the slice data contains the key "SPY", please add the check
if data.Bars.ContainsKey("SPY"): self.window.Add(data["SPY"])Another issue is the brokerage model. FXCM brokerage is used for Forex trading. For equity, please use the InteractiveBrokersBrokerage model.
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage)To attach the backtest, you'll find the button "Attach Backtest" when you edit the comment. You can choose the project and the backtest to add in the comment.
Alex Haseldine
Thank you for your help,
what do you mean by 'You should add the TradeBar to self.window.'?
Gurumeher Sawhney
In Jing's example, there is a RollingWindow that takes in the type TradeBar.
self.window = RollingWindow[TradeBar](2)TradeBar is one of the data types that is to OnData(self, data). OnData provides a Slice object that contains all the data for a given moment of time. TradeBars and QuoteBars are symbol/string indexed dictionaries so you can easily access the data. When Jing is saying add the TradeBar to self.window, she means take that object and save it in the RollingWindow for later use. TradeBar data gives access to the OHLCV data for the specific symbol.
Alex Haseldine
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!