简体   繁体   中英

Quantconnect: Runtime Error: 'TSLA' wasn't found in the Slice object, likely because there was no-data at this moment

I'm trying to make a script that buy stocks if their price dip 5% in the last 5 minutes. Actually getting a runtime error when I try to run it on Quantconnect.

from AlgorithmImports import *
# endregion


class buyAlgorithm(QCAlgorithm):
    def Initialize(self):
        # Set the portfolio cash and leverage
        self.SetCash(100000)
        

        # Set the ticker symbols for TSLA, AMZN, GOOGL, AAPL, and MRNA
        self.ticker_symbols = ["TSLA", "AMZN", "GOOGL", "AAPL", "MRNA"]

        # Set the time frame to 5 minutes
        self.time_frame = 5

        # Subscribe to the TradeBar data for TSLA, AMZN, GOOGL, AAPL, and MRNA
        self.AddEquity(self.ticker_symbols[0], Resolution.Minute)
        self.AddEquity(self.ticker_symbols[1], Resolution.Minute)
        self.AddEquity(self.ticker_symbols[2], Resolution.Minute)
        self.AddEquity(self.ticker_symbols[3], Resolution.Minute)
        self.AddEquity(self.ticker_symbols[4], Resolution.Minute)

    def OnData(self, data: TradeBar):
        # Loop through each ticker symbol
        for ticker_symbol in self.ticker_symbols:
            # Check if we have enough data to calculate the 5 minute return
            if self.Time - data[ticker_symbol].Time > datetime.timedelta(minutes=self.time_frame):
                # Calculate the 5 minute return
                price_change = (data[ticker_symbol].Close - data[ticker_symbol].Open) / data[ticker_symbol].Open
                # Check if the 5 minute return is lower than -5%
                if price_change < -0.05:
                    # Calculate the number of shares to buy based on 30% of the portfolio cash
                    shares = int(self.Portfolio.Cash * 0.3 / data[ticker_symbol].Close)
                    # buy the stock
                    self.buy(ticker_symbol, shares)
                    # Set a timer to close the position after 5 minutes
                    self.Schedule.On(self.DateRules.AfterMarketOpen(ticker_symbol, self.time_frame), 
                                    self.TimeRules.AfterMarketOpen(ticker_symbol, self.time_frame), 
                                    self.ClosePosition)

    def ClosePosition(self):
        # Loop through each ticker symbol
        for ticker_symbol in self.ticker_symbols:
            # Check if we have a long position in the stock
            if self.Portfolio[ticker_symbol].IsLong:
                # Close the long position
                self.Liquidate(ticker_symbol)

Stack Trace:

'TSLA' wasn't found in the Slice object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey("TSLA") in Slice.cs:line 315

Any idea on how to possibly fix it?

Just check if the data for the specified symbol exists in the slice/data using data.Bars.ContainsKey(symbol)

def OnData(self, data: TradeBar):
    # Loop through each ticker symbol
    for ticker_symbol in self.ticker_symbols:
    # check if symbol is present in slice else continue to the next iteration
        if not(data.Bars.ContainsKey(ticker_symbol)):
            self.Debug(f"{self.Time} | {ticker_symbol} not present in slice.")
            continue
        # Check if we have enough data to calculate the 5 minute return
        if self.Time - data[ticker_symbol].Time > datetime.timedelta(minutes=self.time_frame):
            # Calculate the 5 minute return
            price_change = (data[ticker_symbol].Close - data[ticker_symbol].Open) / data[ticker_symbol].Open
            # Check if the 5 minute return is lower than -5%
            if price_change < -0.05:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM