简体   繁体   English

Quantconnect:运行时错误:在切片 object 中找不到“TSLA”,可能是因为此时没有数据

[英]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.我正在尝试制作一个脚本,如果股票价格在过去 5 分钟内下跌 5%,则购买股票。 Actually getting a runtime error when I try to run it on Quantconnect.当我尝试在 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)只需使用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:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 sklearn模型数据转换错误:CountVectorizer - 未安装词汇表 - sklearn model data transform error: CountVectorizer - Vocabulary wasn't fitted 运行时错误:由于无法获取输入,导致GAN的图形断开连接 - Runtime Error: Disconnected graph for GANs because input can't be obtained 为什么我收到这个错误? (QuantConnect 算法) - Why am I getting this error? (QuantConnect Algorithm) 散景未捕获错误:未声明属性 - Bokeh Uncaught Error: property wasn't declared 找不到所需的Django Facebook Python软件包的身份验证后端 - Required auth backend for Django Facebook Python package wasn't found 为什么我会收到此错误? 此错误不是预期的 - Why am I getting this error? This error wasn't expected 由于数据未验证,因此无法创建Django ValueError对象 - Django ValueError Object could not be created because the data didn't validate 为*未*通过 RoundTripLoader 加载的数据结构生成注释? - Generating comments for a data structure that *wasn't* loaded via RoundTripLoader? 如果数据未记录在列中,则使用 python 从 CSV 中删除一行 - Removing a row from CSV with python if data wasn't recorded in a column 错误:: sklearn.exceptions.NotFittedError:CountVectorizer-词汇不正确 - error ::sklearn.exceptions.NotFittedError: CountVectorizer - Vocabulary wasn't fitted
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM