source code:
class MACDTrendAlgorithm(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(2022, 1, 1)
self.SetEndDate(2024, 1, 1)
self.SetCash(1000) # Find more symbols here: http://quantconnect.com/data
self.symbol=self.AddEquity("SPY", Resolution.Hour)
# define our daily macd(12,26) with a 9 day signal
self.__macd = self.MACD("SPY", 12, 26, 9, MovingAverageType.Exponential, Resolution.Hour)
self.__previous = datetime.min
self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
self.PlotIndicator("SPY", self.__macd.Fast, self.__macd.Slow)
#self.Plot("Trade Plot", "Price", self.Securities[self.symbol].Price)
#self.Plot("Trade Plot", "ema_slow", self.ema_slow.Current.Value)
self.crossupTOLERANCE = 0.0025;
self.crossDownTOLERANCE=0.0025
stockPlot = Chart('Trade Plot')
# Import the necessary module before using Custom color
from System.Drawing import Color
stockPlot.AddSeries(Series('Price', SeriesType.Line, '$', Color.Green))
stockPlot.AddSeries(Series('Buy', SeriesType.Scatter, '$', Color.Red, ScatterMarkerSymbol.Triangle))
stockPlot.AddSeries(Series('Sell', SeriesType.Scatter, '$', Color.Blue, ScatterMarkerSymbol.TriangleDown))
self.AddChart(stockPlot)
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# wait for our macd to fully initialize
if not self.__macd.IsReady: return
# only once per day per hour
#if self.__previous.date() == self.Time.date() and (self.__previous.hour() == self.Time.hour()): return
#if not data.Bars.ContainsKey("SPY"):
# print("missing symbol quote")
# return
# define a small tolerance on our checks to avoid bouncing
tolerance = 0.0025
holdings = self.Portfolio["SPY"].Quantity
#price=self.Securities[self.symbol].Price
price=data["SPY"].Close
signalDeltaPercent = (self.__macd.Current.Value - self.__macd.Signal.Current.Value)/self.__macd.Fast.Current.Value
# if our macd is greater than our signal, then let's go long
if holdings <= 0 and signalDeltaPercent > self.crossupTOLERANCE: # 0.01%
# longterm says buy as well
self.SetHoldings("SPY", 1.0)
self.Plot("SPY", "Buy", price)
# of our macd is less than our signal, then let's go short
elif holdings >= 0 and signalDeltaPercent < -self.crossDownTOLERANCE:
self.Liquidate("SPY")
self.Plot("SPY", "Sell", price)
self.__previous = self.Time
the error happens in march 2022.
Mia Alissi
Based on the information provided in the extracts, it's not clear what the specific error is that 'Replyxf' is encountering in March 2022. Without more specific information about the error message or the behavior of the algorithm, it's challenging to provide a definitive solution.
However, there are a few general suggestions that might help:
Ensure that all data needed for the algorithm is available and correctly initialized. For example, the MACD indicator requires a certain amount of data to "warm up" before it can provide accurate signals.
Check for any logical errors in the algorithm. For example, make sure that the conditions for entering and exiting trades are correctly specified.
Use the Debug function to print out values at different points in the algorithm. This can help identify where things are going wrong.
If 'Replyxf' continues to have issues, they might find it helpful to post a more detailed question on the QuantConnect forum, including the specific error message and any relevant details about the algorithm's behavior.
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.
Replyxf
the error is from the line price=data["SPY"].Close. it seems that hourly data of spy is missing some data. what could cause this problem?
Mia Alissi
The error you're encountering is likely due to the fact that there may not always be a data point for every hour for "SPY". This could be due to market holidays, early market closures, or other factors.
When you try to access
data["SPY"].Close
, if there's no data for "SPY" at that specific hour, it will cause an error.To prevent this, you can check if "SPY" is in the data before trying to access it. Here's how you can do it:
This code will check if "SPY" is a key in the data dictionary before trying to access it. If "SPY" is not in the data, it will simply skip over this part of the code, preventing the error.
This approach is suggested in the extract from the QuantConnect forum discussion where it's recommended to change
if data["TSLA"] is not None
toif "TSLA" in data
. The same logic applies to your case with "SPY".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.
Replyxf
thanks, i added filter, but no trade from 2023 is data missing?
Mia Alissi
Based on the information provided in the extracts, it's not clear why there are no trades from 2023. However, there are a few possibilities:
There might be an issue with the data for "SPY" in 2023. It's possible that there are gaps in the data, or the data might not be available for some reason.
The conditions for entering or exiting trades as defined in your algorithm might not be met during this period. This could be due to market conditions, the specific parameters you've set for your indicators, or other factors.
There might be an issue with the way your algorithm is implemented. For example, there might be a logical error that's preventing trades from being executed.
To investigate further, you could add some debug statements to your code to print out the values of your indicators and other relevant information. This might help you identify where the issue is.
If you continue to have issues, you might find it helpful to post a more detailed question on the QuantConnect forum, including your code and any relevant details about the behavior of your algorithm.
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.
Replyxf
there is no order after 05/24/2023
next order
my source code:
from AlgorithmImports import *
### <summary>
### Simple indicator demonstration algorithm of MACD
### </summary>
### <meta name="tag" content="indicators" />
### <meta name="tag" content="indicator classes" />
### <meta name="tag" content="plotting indicators" />
class MACDTrendAlgorithm(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(2022, 1, 1)
self.SetEndDate(2024, 1, 1)
self.SetCash(1000) # Find more symbols here: http://quantconnect.com/data
self.symbol=self.AddEquity("SPY", Resolution.Hour)
# define our daily macd(12,26) with a 9 day signal
self.__macd = self.MACD("SPY", 12, 26, 9, MovingAverageType.Exponential, Resolution.Hour)
self.__previous = datetime.min
self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
self.PlotIndicator("SPY", self.__macd.Fast, self.__macd.Slow)
#self.Plot("Trade Plot", "Price", self.Securities[self.symbol].Price)
#self.Plot("Trade Plot", "ema_slow", self.ema_slow.Current.Value)
self.crossupTOLERANCE = 0.0025;
self.crossDownTOLERANCE=0.0025
stockPlot = Chart('Trade Plot')
# Import the necessary module before using Custom color
from System.Drawing import Color
stockPlot.AddSeries(Series('Price', SeriesType.Line, '$', Color.Green))
stockPlot.AddSeries(Series('Buy', SeriesType.Scatter, '$', Color.Red, ScatterMarkerSymbol.Triangle))
stockPlot.AddSeries(Series('Sell', SeriesType.Scatter, '$', Color.Blue, ScatterMarkerSymbol.TriangleDown))
self.AddChart(stockPlot)
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# wait for our macd to fully initialize
if not self.__macd.IsReady: return
# only once per day per hour
#if self.__previous.date() == self.Time.date() and (self.__previous.hour() == self.Time.hour()): return
if not data.Bars.ContainsKey("SPY"):
#self.log("missing symbol quote")
return
#if 'SPY' not in data:
# self.log('no spy data')
# return
# define a small tolerance on our checks to avoid bouncing
tolerance = 0.0025
holdings = self.Portfolio["SPY"].Quantity
#price=self.Securities[self.symbol].Price
price=data["SPY"].Close
signalDeltaPercent = (self.__macd.Current.Value - self.__macd.Signal.Current.Value)/self.__macd.Fast.Current.Value
# if our macd is greater than our signal, then let's go long
if holdings <= 0 and signalDeltaPercent > self.crossupTOLERANCE: # 0.01%
# longterm says buy as well
self.SetHoldings("SPY", 1.0)
self.Plot("SPY", "Buy", price)
# of our macd is less than our signal, then let's go short
elif holdings >= 0 and signalDeltaPercent < -self.crossDownTOLERANCE:
self.Liquidate("SPY")
self.Plot("SPY", "Sell", price)
self.__previous = self.Time
how can I add log, print, self.log doesn't work
can you please fix your hourly quote, so that I don't need to add following code. The following code mask your price quote error.
if not data.Bars.ContainsKey("SPY"):
#self.log("missing symbol quote")
return
Ashutosh
Hi replyxf
Thank you for the report. I backtested the code to check for potential issues.
We do have data for SPY for the mentioned period.
There were no trades between the timeframe because of the trade logic that you have set. I added some additional logs and tweaked the up, and down resistances and were able to get the trades.
QuantConnect provides informative charts that indicate order levels on the price chart which you can reference for debugging.
Your code liquidated SPY on 2023/05/04 and then the logic only triggered a buy on 2023/11/02. Which is why you see a straight line on the strategy equity chart.
Logs indicating no trigger points for trades as per the logic:
I have attached a sample code that liquidates and takes an opposite position in SPY as a reference.
Best,
Ashutosh
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.
Replyxf
awesome, I will take a look at it. thank you so much!
Replyxf
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!