Hi,
I've been tryin to run my algorithms indicators using custom time frames, i've been unsuccessful. Need your help.
i keep getting this error message: "ArgumentException : Unable to create TSLA consolidator because TSLA is registered for Hour data. Consolidators require higher resolution data to produce lower resolution data. "
Here's the code i have created so far. I'd appreciate any and all the help i can get to get this algorithm running on
any custom timeframe.
from datetime import timedelta, datetime
class FocusedYellowLemur(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2015, 12, 1) # Set Start Date
self.SetEndDate(2016, 12, 1)
self.SetCash(100000) # Set Strategy Cash
self.Data = {}
for ticker in ["TSLA","AAPL"]:
symbol = self.AddEquity(ticker, Resolution.Hour, Market.USA).Symbol
self.Data[symbol] = SymbolData(self, symbol)
self.stopLossLevel = -0.05 # stop loss percentage
self.stopProfitLevel = 0.01# stop profit percentage
self.tolerance = 1.01
self.SetWarmUp(100, Resolution.Hour)
def OnData(self, data):
if self.IsWarmingUp:
return
for symbol, symbolData in self.Data.items():
if not (data.ContainsKey(symbol) and data[symbol] is not None and symbolData.IsReady):
continue
fast = symbolData.fast.Current.Value
slow = symbolData.slow.Current.Value
current_price = symbolData.closeWindow[0]
#current_price = data[symbol].Close
self.is_uptrend = fast > slow * self.tolerance
self.is_downtrend = slow > fast * self.tolerance
if self.Portfolio[symbol].Invested:
if self.isLong:
condStopProfit = (current_price - self.buyInPrice)/self.buyInPrice > self.stopProfitLevel
condStopLoss = (current_price - self.buyInPrice)/self.buyInPrice < self.stopLossLevel
if condStopProfit:
self.Liquidate(symbol)
self.Log(f"{self.Time} Long Position Stop Profit at {current_price}")
if condStopLoss:
self.Liquidate(symbol)
self.Log(f"{self.Time} Long Position Stop Loss at {current_price}")
else:
condStopProfit = (self.sellInPrice - current_price)/self.sellInPrice > self.stopProfitLevel
condStopLoss = (self.sellInPrice - current_price)/self.sellInPrice < self.stopLossLevel
if condStopProfit:
self.Liquidate(symbol)
self.Log(f"{self.Time} Short Position Stop Profit at {current_price}")
if condStopLoss:
self.Liquidate(symbol)
self.Log(f"{self.Time} Short Position Stop Profit at {current_price}")
if not self.Portfolio[symbol].Invested:
uptrend = self.is_uptrend
downtrend = self.is_downtrend
if downtrend and current_price < fast:
self.SetHoldings(symbol, 0)
# get buy-in price for trailing stop loss/profit
self.buyInPrice = current_price
# entered long position
self.isLong = True
#Timebought = self.Time
self.Log(f"{self.Time} Entered Long Position at {current_price}")
if uptrend and current_price > fast:
self.SetHoldings(symbol, -1)
# get sell-in price for trailing stop loss/profit
self.sellInPrice = current_price
# entered short position
self.isLong = False
#Timesold = self.Time
self.Log(f"{self.Time} Entered Short Position at {current_price}")
class SymbolData:
def __init__(self, algorithm, symbol):
self.fast = algorithm.SMA(symbol, 5, MovingAverageType.Simple) #Resolution.Hour
self.fastWindow = RollingWindow[IndicatorDataPoint](2)
#Generating 5-period SMA values of 4 hours Resolution
algorithm.RegisterIndicator(symbol, self.fast, timedelta(Hours=4))
self.fast.Updated += self.FastUpdated
self.slow = algorithm.SMA(symbol, 10, MovingAverageType.Simple) #Resolution.Hour
self.slowWindow = RollingWindow[IndicatorDataPoint](2)
#Generating 10-period SMA values of 4 hours Resolution.
algorithm.RegisterIndicator(symbol, self.slow, timedelta(Hours=4))
self.slow.Updated += self.SlowUpdated
self.closeWindow = RollingWindow[float](10)
# Add consolidator to track rolling close prices
self.consolidator = TradeBarConsolidator(4)
self.consolidator.DataConsolidated += self.CloseUpdated
algorithm.SubscriptionManager.AddConsolidator(symbol, self.consolidator)
def FastUpdated(self, sender, updated):
'''Event holder to update the fast SMA Rolling Window values'''
if self.fast.IsReady:
self.fastWindow.Add(updated)
def SlowUpdated(self, sender, updated):
'''Event holder to update the slow SMA Rolling Window values'''
if self.slow.IsReady:
self.slowWindow.Add(updated)
def CloseUpdated(self, sender, bar):
'''Event holder to update the close Rolling Window values'''
self.closeWindow.Add(bar.Close)
@property
def IsReady(self):
return self.fast.IsReady and self.slow.IsReady and self.closeWindow.IsReady
Samwel Kibet
I found the errors i had made in the code. I found a way to make it run.
So in the class Symbol Data the SMA method takes 2 arguments and not 3 as i had done, and the 2 arguments are the symbol and period as shown below.
class SymbolData: def __init__(self, algorithm, symbol): self.fast = algorithm.SMA(symbol, 5)
The next error was i had done was i had started the arguements of timedelta with a capital letter "H" - timedelta(Hour = 4), which is not appropriate, the right arguements that timedelta takes are in small letters "hours". as illustrated below.
#Generating 5-period SMA values of 4 hours Resolution algorithm.RegisterIndicator(symbol, self.fast, timedelta(hours=4))
Incase, you have any advice with regard to my code, feel ease to share.
Derek Melchin
Hi Samwel,
Great start on this algorithm! There are just a couple things we can do to improve it.
First, the indicators in the algorithm above are updated every hour and every 4 hours. See this related thread.
Second, the algorithm above also uses `self.isLong` and `self.isShort`. However, since the algorithm is trading multiple securities, these flags aren't always accurate. We recommend reviewing this related thread for assistance setting up take-profit and stop-loss orders.
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.
Shile Wen
Hi Samwei,
The first issue is that we are creating indicators with algorithm. while registering them as well. If we are going to register an indicator, we should create them from the class name, e.g. SimpleMovingAverage instead of algorithm.SMA. In addition the SimpleMovingAverage already is already computed using Simple Moving Average, so we don't need to specify this Moving Average Type as an argument. Please see these fixes in the attached backtest.
Best,
Shile Wen
Samwel Kibet
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!