Hello everyone,
As mentioned in the title I'm a complete beginner at developing algorithms. To get my feet wet I started of with a simple algorithm which can be found here: Dual Thrust Trading Algorithm. It's a strategy from the Strategy Library and I want to test some indicators to adjust the value of the two parameters dynamically. Unfortunately, I get an error on Line 86: TypeError : '>=' not supported between instances of 'decimal.Decimal' and 'NoneType'.
The code looks like this:
from clr import AddReference
AddReference('System')
AddReference('QuantConnect.Algorithm')
AddReference('QuantConnect.Common')
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from datetime import datetime
import decimal
class DualThrustAlgorithm(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, 1, 1)
self.SetEndDate(2015, 12, 31)
self.SetCash(10000)
equity = self.AddEquity('SPY', Resolution.Hour)
self.syl = equity.Symbol
self.__adx = self.ADX(self.syl, 30, Resolution.Hour)
self.__macd = self.MACD(self.syl, 12, 26, 30, MovingAverageType.Exponential, Resolution.Hour)
self.Schedule.On(self.DateRules.EveryDay(self.syl),self.TimeRules.AfterMarketOpen(self.syl,0),Action(self.SetSignal))
self.selltrig = None
self.buytrig = None
self.currentopen = None
def SetSignal(self):
history = self.History([self.syl.Value], 4, Resolution.Daily)
if not self.__adx.IsReady:
return
if not self.__macd.IsReady:
return
if self.__adx > 75 and self.__macd.Current.Value > self.__macd.Signal.Current.Value:
k1 = 0.1
k2 = 0.9
elif self.__adx > 50 and self.__macd.Current.Value > self.__macd.Signal.Current.Value:
k1 = 0.3
k2 = 0.7
elif self.__adx > 25 and self.__macd.Current.Value > self.__macd.Signal.Current.Value:
k1 = 0.4
k2 = 0.6
elif self.__adx > 75 and self.__macd.Current.Value < self.__macd.Signal.Current.Value:
k1 = 0.9
k2 = 0.1
elif self.__adx > 50 and self.__macd.Current.Value < self.__macd.Signal.Current.Value:
k1 = 0.3
k2 = 0.7
elif self.__adx > 25 and self.__macd.Current.Value < self.__macd.Signal.Current.Value:
k1 = 0.6
k2 = 0.4
else:
k1 = 0.5
k2 = 0.5
self.high = history.loc[self.syl.Value]['high']
self.low = history.loc[self.syl.Value]['low']
self.close = history.loc[self.syl.Value]['close']
self.currentopen = self.Portfolio[self.syl].Price
HH, HC, LC, LL = max(self.high), max(self.close), min(self.close), min(self.low)
if HH - LC >= HC - LL:
signalrange = HH - LC
else:
signalrange = HC - LL
self.selltrig = float(self.currentopen) - float(k1) * signalrange
self.buytrig = float(self.currentopen) + float(k2) * signalrange
def OnData(self,data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
holdings = self.Portfolio[self.syl].Quantity
if self.Portfolio[self.syl].Price >= self.selltrig:
if holdings >= 0:
self.SetHoldings(self.syl, 0.8)
else:
self.Liquidate(self.syl)
self.SetHoldings(self.syl, 0.8)
elif self.Portfolio[self.syl].Price < self.selltrig:
if holdings >= 0:
self.Liquidate(self.syl)
self.SetHoldings(self.syl, -0.8)
else:
self.SetHoldings(self.syl, -0.8)
self.Log("open: "+ str(self.currentopen)+" buy: "+str(self.buytrig)+" sell: "+str(self.selltrig))
Your help is much appreciated. Bear with me, I just learned a couple of fundamentals in Python weeks ago. I'm new to this hole thing.
Best,
JD
JDMar
Ok. I found the solution to my problem myself. But another error message shows up right when the backtest waits to receive the data. It says:
BacktestingRealTimeHandler.Run(): There was an error in a scheduled event SPY: EveryDay: SPY: 0 min after MarketOpen. The error was TypeError : float() argument must be a string or a number, not 'NoneType'
The updated code looks like this:
from clr import AddReference AddReference('System') AddReference('QuantConnect.Algorithm') AddReference('QuantConnect.Common') from System import * from QuantConnect import * from QuantConnect. Orders import * from QuantConnect.Algorithm import QCAlgorithm from datetime import datetime import decimal class DualThrustAlgorithm(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, 1, 1) self.SetEndDate(2015, 12, 31) self.SetCash(10000) equity = self.AddEquity('SPY', Resolution.Hour) self.syl = equity.Symbol self.adx = self.ADX(self.syl, 30, Resolution.Hour) self.macd = self.MACD(self.syl, 12, 26, 30, MovingAverageType.Exponential, Resolution.Hour) self.Schedule.On(self.DateRules.EveryDay(self.syl), self.TimeRules.AfterMarketOpen(self.syl, 0), Action(self.SetSignal)) self.k1 = None self.k2 = None self.selltrig = None self.buytrig = None self.currentopen = None def SetSignal(self): history = self.History([self.syl.Value], 4, Resolution.Daily) if self.adx.IsReady and self.macd.IsReady: if self.adx.Current.Value > 75 and self.macd.Current.Value > self.macd.Signal.Current.Value: self.k1 = 0.1 self.k2 = 0.9 elif self.adx.Current.Value > 50 and self.macd.Current.Value > self.macd.Signal.Current.Value: self.k1 = 0.3 self.k2 = 0.7 elif self.adx.Current.Value > 25 and self.macd.Current.Value > self.macd.Signal.Current.Value: self.k1 = 0.4 self.k2 = 0.6 elif self.adx.Current.Value > 75 and self.macd.Current.Value < self.macd.Signal.Current.Value: self.k1 = 0.9 self.k2 = 0.1 elif self.adx.Current.Value > 50 and self.macd.Current.Value < self.macd.Signal.Current.Value: self.k1 = 0.3 self.k2 = 0.7 elif self.adx.Current.Value > 25 and self.macd.Current.Value < self.macd.Signal.Current.Value: self.k1 = 0.6 self.k2 = 0.4 else: self.k1 = 0.5 self.k2 = 0.5 self.high = history.loc[self.syl.Value]['high'] self.low = history.loc[self.syl.Value]['low'] self.close = history.loc[self.syl.Value]['close'] self.currentopen = self.Portfolio[self.syl].Price HH, HC, LC, LL = max(self.high), max(self.close), min(self.close), min(self.low) if HH - LC >= HC - LL: signalrange = HH - LC else: signalrange = HC - LL self.selltrig = float(self.currentopen) - float(self.k1) * signalrange self.buytrig = float(self.currentopen) + float(self.k2) * signalrange def OnData(self,data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' holdings = self.Portfolio[self.syl].Quantity if self.Portfolio[self.syl].Price >= self.selltrig: if holdings >= 0: self.SetHoldings(self.syl, 0.8) else: self.Liquidate(self.syl) self.SetHoldings(self.syl, 0.8) elif self.Portfolio[self.syl].Price < self.selltrig: if holdings >= 0: self.Liquidate(self.syl) self.SetHoldings(self.syl, -0.8) else: self.SetHoldings(self.syl, -0.8) self.Log("open: "+ str(self.currentopen)+" buy: "+str(self.buytrig)+" sell: "+str(self.selltrig))
Any thoughts on that one?
Best
JD
Gurumeher Sawhney
Thanks for attaching the code! The reason why you're receiving a NoneType error is because of lines 75 and 76, If the indicators are not ready, then self.k1 and self.k2 never get assigned but they are still called upon for calculations.
self.selltrig = float(self.currentopen) - float(self.k1) * signalrange self.buytrig = float(self.currentopen) + float(self.k2) * signalrange
I was able to figure this out by tracing the error and creating self.Debug() statements which checked the current status of the values. Errors like these can be avoided with conditional statements.
JDMar
Thank you for your help! But I still have some questions regarding conditional statements and the usage of self.Debug().
First, I added "if not self.adx.IsReady or self.macd.IsReady" in front of my code for calculating the values of self.k1 and self.k2. Is this the right way to do it, or do I have to build conditional statements in another way?
Second, can you give my an example of how to use self.Debug()? I tried to use it on my own with guidance by the documentation but I didn't manage to use it successfully.
Current status of my code is that I get the same error on line 87 as in the very first post in this discussion: TypeError: '>=' not supported between instances of 'decimal.Decimal' and 'NoneType'. The new code including the conditional statements looks like this:
if not self.adx.IsReady or self.macd.IsReady: return elif self.adx.Current.Value > 75 and self.macd.Current.Value > self.macd.Signal.Current.Value: self.k1 = 0.1 self.k2 = 0.9 elif self.adx.Current.Value > 50 and self.macd.Current.Value > self.macd.Signal.Current.Value: self.k1 = 0.3 self.k2 = 0.7 elif self.adx.Current.Value > 25 and self.macd.Current.Value > self.macd.Signal.Current.Value: self.k1 = 0.4 self.k2 = 0.6 elif self.adx.Current.Value > 75 and self.macd.Current.Value < self.macd.Signal.Current.Value: self.k1 = 0.9 self.k2 = 0.1 elif self.adx.Current.Value > 50 and self.macd.Current.Value < self.macd.Signal.Current.Value: self.k1 = 0.3 self.k2 = 0.7 elif self.adx.Current.Value > 25 and self.macd.Current.Value < self.macd.Signal.Current.Value: self.k1 = 0.6 self.k2 = 0.4 else: self.k1 = 0.5 self.k2 = 0.5
JDMar
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!