Hi there,
Can't understand why this code generates a fatal error
from AlgorithmImports import *
class LongOnlyEquityTradingAlgorithm(QCAlgorithm):
def Initialize(self):
# Set the starting and ending dates for the backtest
self.SetStartDate(2024, 1, 1)
self.SetEndDate(2024, 12, 31)
# Set the initial cash for the backtest
self.SetCash(100000)
# Define the universe selection parameters
self.num_stocks = 300
self.price_threshold = 1.0
# Initialize dictionaries to hold stock data
self.Myuniverse = []
self.selected_stocks = []
self.stock_data = {}
# Schedule the universe selection function to run at the market open
self.AddUniverse(self.CoarseSelectionFilter)
# Schedule the stock selection function to run at 9:35 AM
try:
self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen("SPY", 5), self.SelectStocks)
except Exception as e:
self.Debug(f"Error scheduling SelectStocks: {e}")
def CoarseSelectionFilter(self, coarse):
# Filter the universe to the most liquid small and mid-cap stocks above $1 in price
filtered = [x for x in coarse if x.Price > self.price_threshold]
sorted_by_liquid = sorted(filtered, key=lambda x: x.DollarVolume, reverse=True)
self.Myuniverse = [x.Symbol for x in sorted_by_liquid[:self.num_stocks]]
return self.Myuniverse
def SelectStocks(self):
# Filter the universe based on the previous day's closing price and Bollinger Bands
self.selected_stocks = []
for symbol in self.Myuniverse:
history = self.History(symbol, 21, Resolution.Daily)
if not history.empty:
close_prices = history['close']
if len(close_prices) == 21:
upper_band = close_prices.rolling(20).mean() + 2 * close_prices.rolling(20).std()
if close_prices[-2] > upper_band[-2]:
self.selected_stocks.append(symbol)
# Further narrow down the universe based on the best 5-minute returns
five_minute_returns = {}
for symbol in self.selected_stocks:
history = self.History(symbol, 5, Resolution.Minute)
if not history.empty:
open_price = history['open'][0]
close_price = history['close'][-1]
five_minute_returns[symbol] = (close_price - open_price) / open_price
sorted_by_returns = sorted(five_minute_returns.items(), key=lambda x: x[1], reverse=True)
self.selected_stocks = [x[0] for x in sorted_by_returns[:20]]
# Initialize stock data for monitoring and add consolidators
for symbol in self.selected_stocks:
self.stock_data[symbol] = {
'entry_price': None,
'trailing_stop': None
}
# Create a consolidator for 5-minute bars
consolidator = TradeBarConsolidator(timedelta(minutes=5))
consolidator.DataConsolidated += self.OnDataConsolidated
self.SubscriptionManager.AddConsolidator(symbol, consolidator)
def OnDataConsolidated(self, sender, bar):
symbol = bar.Symbol
history = self.History(symbol, 21, Resolution.Minute)
if not history.empty:
close_prices = history['close']
volumes = history['volume']
upper_band = close_prices.rolling(20).mean() + 2 * close_prices.rolling(20).std()
if close_prices[-1] > upper_band[-1] and volumes[-1] > 2 * volumes[0]:
if not self.Portfolio[symbol].Invested:
self.SetHoldings(symbol, 1.0 / len(self.selected_stocks))
self.stock_data[symbol]['entry_price'] = close_prices[-1]
self.stock_data[symbol]['trailing_stop'] = close_prices[-1] * 0.98
def OnData(self, data):
for symbol in self.selected_stocks:
if symbol in self.Portfolio:
if symbol in data:
current_price = data[symbol].Close
entry_price = self.stock_data[symbol]['entry_price']
trailing_stop = self.stock_data[symbol]['trailing_stop']
# Update trailing stop
if current_price > entry_price * 1.10:
self.Liquidate(symbol)
elif current_price > trailing_stop:
self.stock_data[symbol]['trailing_stop'] = current_price * 0.98
elif current_price > trailing_stop:
self.Liquidate(symbol)
else:
self.Debug(f"Data for {symbol} is not available in the current slice.")
Sebastien M. Laignel
Any hint would be welcome, Mia where are you ?
Thanks
SL
Mia Alissi
Hello Sebastien,
I'm here to help! However, I need more information about your question or the issue you're facing. Could you please provide more details? This could include the specific problem you're encountering, any error messages you're seeing, or the context of the task you're trying to accomplish.
If you're looking for assistance with QuantConnect's LEAN engine or any other aspect of the platform, you might find the QuantConnect Documentation helpful. It provides comprehensive information about the platform's features and how to use them.
If you're working with Python, remember that QuantConnect supports both Python and C# for algorithmic trading. You can find numerous examples in the Algorithm Framework section of the documentation.
If you're referring to "Mia", it's an AI Quant Support Agent introduced by QuantConnect to assist users in navigating the platform's extensive documentation and resources. You can ask Mia questions directly in the Algorithm Lab for quick code fix suggestions or explanations of runtime errors. However, please note that the number of questions you can ask Mia per month depends on your user type (source).
Please provide more details so I can give you a more specific answer.
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.
Sebastien M. Laignel
Hi Mia
Here is the error I got: [ERROR] FATAL UNHANDLED EXCEPTION:Engine.Run(): Error running algorithm System.ArgumentException: Unable to locate next market open within two weeks., at QuantConnect.Securities.SecurityExchangeHours.GetNextMarketOpen(DateTime localDateTime, Boolean extendedMarketHours) in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/LeanEnterprise/Common/Securities/SecurityExchangeHours.cs:line 320, at QuantConnect.Scheduling.TimeRules.<>c__DisplayClass14_0.b__1(DateTime date) in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/LeanEnterprise/Common/Scheduling/TimeRules.cs:line 172, at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext(), at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext(), at QuantConnect.Scheduling.ScheduledEvent.get_NextEventUtcTime() in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/LeanEnterprise/Common/Scheduling/ScheduledEvent.cs:line 80, at QuantConnect.Lean.Engine.RealTime.BacktestingRealTimeHandler.<>c.b__11_0(KeyValuePair`2 x) in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/LeanEnterprise/Engine/RealTime/BacktestingRealTimeHandler.cs:line 158, at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count), at System.Linq.EnumerableSorter`1.ComputeMap(TElement[] elements, Int32 count), at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count), at System.Linq.OrderedEnumerable`1.GetEnumerator()+MoveNext(), at System.Linq.Enumerable.SelectIPartitionIterator`2.ToList(), at QuantConnect.Lean.Engine.RealTime.BacktestingRealTimeHandler.GetScheduledEventsSortedByTime() in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/LeanEnterprise/Engine/RealTime/BacktestingRealTimeHandler.cs:line 156, at QuantConnect.Lean.Engine.RealTime.BacktestingRealTimeHandler.Setup(IAlgorithm algorithm, AlgorithmNodePacket job, IResultHandler resultHandler, IApi api, IIsolatorLimitResultProvider isolatorLimitProvider) in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/LeanEnterprise/Engine/RealTime/BacktestingRealTimeHandler.cs:line 52, at QuantConnect.Lean.Engine.Engine.Run(AlgorithmNodePacket job, AlgorithmManager manager, String assemblyPath, WorkerThread workerThread) in /LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/LeanEnterprise/Engine/Engine.cs:line 295
Mia Alissi
Hello Sebastien,
The error message you're seeing is related to the algorithm trying to find the next market open time within two weeks and failing to do so. This error often occurs when you're trying to use 'TimeRules.AfterMarketOpen' or 'TimeRules.BeforeMarketClose' for markets that do not close, like crypto or custom data.
Instead of using 'TimeRules.AfterMarketOpen' or 'TimeRules.BeforeMarketClose', you can use 'TimeRules.At(9, 30)' for example. Also, note that it's not possible to place 'MarketOnOpen' and 'MarketOnClose' type of orders for these assets for the same reason.
Here is the relevant discussion on the QuantConnect forum that explains this issue: Forum Discussion
If you're still encountering issues, please provide more details about your algorithm, such as the assets you're trading and the scheduling rules you're using. This will help in providing a more specific solution.
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.
Sebastien M. Laignel
Correct, thanks
Sebastien M. Laignel
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!