Hi guys, I have written a backtest for an Algorithm that tries to trade inside bars once the trend is in it's direction. However I get no trades being executed. The code is structured well and Ask Mia could not seem to find an issue with the code. Can anyone figure out where I might be going wrong with my code?
Mia Alissi
Sure, I'd be happy to help. However, I'll need to see the code you're working with to provide specific guidance. Could you please share the code you're using for 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.
Akira
from AlgorithmImports import * class MultiTimeframeTrendStrategy(QCAlgorithm):   def Initialize(self):     # Initialize algorithm parameters     self.SetStartDate(2010, 1, 1)     # self.SetEndDate(2015, 1, 1)     self.SetCash(100000)     # Add SPY Equity with hourly resolution     spy = self.AddEquity("SPY", Resolution.Hour)     spy.SetDataNormalizationMode(DataNormalizationMode.Raw)     self.spySymbol = spy.Symbol     # Set Benchmark     self.SetBenchmark("SPY")     self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)     # Initialize opening and previous bar prices for multiple time frames     self.weeklyOpenPrice = None     self.dailyOpenPrice = None     self.hourlyOpenPrice = None     self.lastDailyHigh = None     self.lastDailyLow = None     self.lastHourlyHigh = None     self.lastHourlyLow = None     # Schedule functions to update weekly, daily, and hourly opening prices     self.lastTradeWeek = -1  # Initialize to an invalid week number     self.Schedule.On(self.DateRules.EveryDay(self.spySymbol), self.TimeRules.AfterMarketOpen(self.spySymbol, 1), self.CheckIfNewWeek)     self.Schedule.On(self.DateRules.EveryDay(self.spySymbol), self.TimeRules.At(9, 30), self.DailyOpen)     # Initialize last hour     self.lastHour = self.Time.hour   def OnData(self, data):     # Ensure the algorithm isn't warming up and that SPY data is available.     if self.IsWarmingUp or self.spySymbol not in data or data[self.spySymbol] is None:       return     # Update hourly price data and track high/low for Inside Bar detection.     if self.Time.hour != self.lastHour:       if data.Bars.ContainsKey(self.spySymbol):         bar = data.Bars[self.spySymbol]         self.hourlyOpenPrice = bar.Open         self.lastHourlyHigh = bar.High         self.lastHourlyLow = bar.Low         self.lastHour = self.Time.hour         self.insideBarDetected = False  # Reset inside bar detection for the new hour     # Detect an Inside Bar based on the last hourly high and low.     if self.lastHourlyHigh is not None and self.lastHourlyLow is not None:       if self.hourlyOpenPrice < self.lastHourlyHigh and self.hourlyOpenPrice > self.lastHourlyLow:         self.Debug("Detected an Inside Bar at the hourly time frame")         self.insideBarDetected = True     # Ensure all necessary prices are set before proceeding.     if None in [self.weeklyOpenPrice, self.dailyOpenPrice, self.hourlyOpenPrice]:       return     # Current price from the data.     price = data[self.spySymbol].Price     # Execute trades based on Inside Bar breakout and trend continuity.     if self.insideBarDetected:       # Entry condition for a long position when current price breaks above the Inside Bar's high       if price > self.lastHourlyHigh and price > self.weeklyOpenPrice and price > self.dailyOpenPrice and price > self.hourlyOpenPrice:         if not self.Portfolio[self.spySymbol].Invested:           self.Log("Inside Bar broken upwards, aligning with TFC for a long position")           self.SetHoldings(self.spySymbol, 1)       # Exit condition if the price breaks below the Inside Bar's low       elif price < self.lastHourlyLow:         if self.Portfolio[self.spySymbol].Invested:           self.Log("Inside Bar broken downwards, exiting position.")           self.Liquidate(self.spySymbol)   def CheckIfNewWeek(self):     currentWeek = self.Time.isocalendar()[1]     if currentWeek != self.lastTradeWeek:       self.lastTradeWeek = currentWeek       self.WeeklyOpen()   def WeeklyOpen(self):     self.weeklyOpenPrice = self.Securities[self.spySymbol].Price     self.Log(f"Weekly open price updated on {self.Time.strftime('%Y-%m-%d')}: {self.weeklyOpenPrice}")   def DailyOpen(self):     bar = self.Securities[self.spySymbol]     self.dailyOpenPrice = bar.Price     self.lastDailyHigh = bar.High     self.lastDailyLow = bar.Low     self.Log(f"Daily open price updated on {self.Time.strftime('%Y-%m-%d')}: {self.dailyOpenPrice}")
Marc Daoust
Akira;
I found that Price > LastHigh never happens. Replacing it with Price >= LastHigh works.
Marc Daoust
Here is the backtest - with some logging of various values (with formatting).
Akira
I appreciate your response Marc, thank you. I will review your recommendation.
Marc Daoust
You're welcome Akira.
Note that although your algo now buys, it never sells.Â
The sell criteria requires the Price to fall BELOW the Last Low. Here again, the fix is  to use <=.
To better visualize the interactions of your algo's rules, I would recommend to use the Plot() feature. It helps especially when using various indicators like SMA, EMA, VWAP, etc.
Happy trails;
Marc
Akira
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!