AttributeError: 'tuple' object has no attribute 'symbol' when downloading stock prices in chunks using "alpaca-py" library into SQLite table

huangapple go评论103阅读模式
英文:

AttributeError: 'tuple' object has no attribute 'symbol' when downloading stock prices in chunks using "alpaca-py" library into SQLite table

问题

我正在尝试使用alpaca-py库从Alpaca下载历史股票价格,并将这些数据存储到SQLite表中。当逐个符号下载历史数据时,一切正常。但当我尝试一次下载200个符号的数据时,我收到以下错误消息:

AttributeError: 'tuple' object has no attribute 'symbol'

这是导致错误的代码部分:

# 定义每次服务器调用下载的符号块。
symbols = ['AMD', 'MSFT', 'NVDA', 'TOVX']
chunk_size = 2
for i in tqdm(range(0, len(symbols), chunk_size), desc='Downloading daily Data'):
    symbol_chunk = symbols[i:i + chunk_size]
    # 下载1D时间框架的数据...
    request_parameters = StockBarsRequest(
                    symbol_or_symbols=symbol_chunk,
                    timeframe=TimeFrame.Day,
                    start=datetime.strptime("2022-01-01", '%Y-%m-%d'),
                    end=None,
                    adjustment='raw'
             )
    daily_bars = client.get_stock_bars(request_parameters)
    for bar in daily_bars:
        stock_id = symbol_dic[bar.symbol]
        cursor.execute("""INSERT INTO alpaca_stock_prices_1D (stock_id, date, open, high, low, close, volume)
            VALUES (?, ?, ?, ?, ?, ?, ?)""",
                       (stock_id, bar.timestamp.date(), bar.open, bar.high, bar.low, bar.close, bar.volume))

我做错了什么?

下面是从 "daily_bars" 返回的数据示例:

data={'AIU': [{   'close': 3.66,
    'high': 3.75,
    'low': 3.64,
    'open': 3.65,
    'symbol': 'AIU',
    'timestamp': datetime.datetime(2021, 1, 5, 5, 0, tzinfo=datetime.timezone.utc),
    'trade_count': 661.0,
    'volume': 126252.0,
    'vwap': 3.67104}, {   'close': 3.7,
    'high': 3.74,
    'low': 3.6,
    'open': 3.7,
    'symbol': 'AIU',
    'timestamp': datetime.datetime(2021, 1, 6, 5, 0, tzinfo=datetime.timezone.utc),
    'trade_count': 798.0,
    'volume': 120423.0,
    'vwap': 3.653867}, {   'close': 3.61,
    'high': 3.69,
    'low': 3.58,
    'open': 3.62,
    'symbol': 'AIU',
    'timestamp': datetime.datetime(2021, 1, 7, 5, 0, tzinfo=datetime.timezone.utc),
    'trade_count': 1029.0,
    'volume': 164226.0,
    'vwap': 3.628806}, {   'close': 3.67,
    'high': 3.7473,
    'low': 3.6,
    'open': 3.62,
    'symbol': 'AIU',
    'timestamp': datetime.datetime(2021, 1, 8, 5, 0, tzinfo=datetime.timezone.utc),
    'trade_count': 1398.0,
    'volume': 191745.0,
    'vwap': 3.666181},....

创建SQLite价格表的代码如下:

cursor.execute("""
    CREATE TABLE IF NOT EXISTS alpaca_stock_prices_1D (
        id INTEGER PRIMARY KEY,
        stock_id INTEGER,
        date NOT NULL,
        open NOT NULL,
        high NOT NULL,
        low NOT NULL,
        close NOT NULL,
        volume NOT NULL,
        CONSTRAINT fk_alpaca_stocks_list FOREIGN KEY (stock_id) REFERENCES alpaca_stocks_list (id)
        ON DELETE CASCADE
    )
""")

希望这些信息对你有帮助。

英文:

I am trying to download the historical stock prices from alpaca using the alpaca-py library and store this data into a sqlite table. When downloading the historical data symbol by symbol everything works fine. But when I try to download the data in a chunk of 200 symbols at a time, I get the error:

AttributeError: 'tuple' object has no attribute 'symbol'

This is the part of my code which produces the error:

# Define chunk of symbols to download with every server call.
symbols=['AMD', 'MSFT', 'NVDA', 'TOVX']
chunk_size = 2
for i in tqdm(range(0, len(symbols), chunk_size), desc='Downloading daily Data'):
    symbol_chunk = symbols[i:i + chunk_size]
    # Downloading 1D time-frame data...
    request_parameters = StockBarsRequest(
                    symbol_or_symbols=symbol_chunk,
                    timeframe=TimeFrame.Day,
                    start=datetime.strptime("2022-01-01", '%Y-%m-%d'),
                    end=None,
                    adjustment='raw'
             )
    daily_bars = client.get_stock_bars(request_parameters)
    for bar in daily_bars:
        stock_id = symbol_dic[bar.symbol]
        cursor.execute("""INSERT INTO alpaca_stock_prices_1D (stock_id, date, open, high, low, close, volume)
            VALUES (?, ?, ?, ?, ?, ?, ?)""",
                       (stock_id, bar.timestamp.date(), bar.open, bar.high, bar.low, bar.close, bar.volume))

What is it that I am doing wrong?

Below is a sample of the data returned from "daily_bars":

data={'AIU': [{   'close': 3.66,
    'high': 3.75,
    'low': 3.64,
    'open': 3.65,
    'symbol': 'AIU',
    'timestamp': datetime.datetime(2021, 1, 5, 5, 0, tzinfo=datetime.timezone.utc),
    'trade_count': 661.0,
    'volume': 126252.0,
    'vwap': 3.67104}, {   'close': 3.7,
    'high': 3.74,
    'low': 3.6,
    'open': 3.7,
    'symbol': 'AIU',
    'timestamp': datetime.datetime(2021, 1, 6, 5, 0, tzinfo=datetime.timezone.utc),
    'trade_count': 798.0,
    'volume': 120423.0,
    'vwap': 3.653867}, {   'close': 3.61,
    'high': 3.69,
    'low': 3.58,
    'open': 3.62,
    'symbol': 'AIU',
    'timestamp': datetime.datetime(2021, 1, 7, 5, 0, tzinfo=datetime.timezone.utc),
    'trade_count': 1029.0,
    'volume': 164226.0,
    'vwap': 3.628806}, {   'close': 3.67,
    'high': 3.7473,
    'low': 3.6,
    'open': 3.62,
    'symbol': 'AIU',
    'timestamp': datetime.datetime(2021, 1, 8, 5, 0, tzinfo=datetime.timezone.utc),
    'trade_count': 1398.0,
    'volume': 191745.0,
    'vwap': 3.666181},....

Code to create the sqlite prices table:

cursor.execute("""
    CREATE TABLE IF NOT EXISTS alpaca_stock_prices_1D (
        id INTEGER PRIMARY KEY,
        stock_id INTEGER,
        date NOT NULL,
        open NOT NULL,
        high NOT NULL,
        low NOT NULL,
        close NOT NULL,
        volume NOT NULL,
        CONSTRAINT fk_alpaca_stocks_list FOREIGN KEY (stock_id) REFERENCES alpaca_stocks_list (id)
        ON DELETE CASCADE
    )
""")

答案1

得分: 0

I used to have the same issue and I fixed it using the following code:

daily_bars = client.get_stock_bars(request_parameters)
for bar in daily_bars:
data = bar[1]
for symbol_data in data.values():
for data_point in symbol_data:
try:
stock_id = symbol_dic[data_point.symbol]
cursor.execute("INSERT INTO alpaca_stock_prices_1D (stock_id, date, open, high, low, close, volume) VALUES (?, ?, ?, ?, ?, ?, ?)",
(stock_id, data_point.timestamp.date(), data_point.open, data_point.high, data_point.low, data_point.close, data_point.volume))
except AttributeError:
print("The 'data_point' object does not have a 'symbol' or 'timestamp' attribute: {data_point}")
except KeyError:
print(f"The symbol '{data_point.symbol}' is not present in the symbol_dic dictionary")

英文:

I used to have the same issue and I fixed it using the following code:

    daily_bars = client.get_stock_bars(request_parameters)
    for bar in daily_bars:
        data = bar[1]
        for symbol_data in data.values():
            for data_point in symbol_data:
                try:
                    stock_id = symbol_dic[data_point.symbol]
                    cursor.execute("""INSERT INTO alpaca_stock_prices_1D (stock_id, date, open, high, low, close,
                                    volume) VALUES (?, ?, ?, ?, ?, ?, ?)""",
                                   (stock_id, data_point.timestamp.date(),
                                    data_point.open, data_point.high, data_point.low, data_point.close,
                                    data_point.volume))
                except AttributeError:
                    print(
                        f"The 'data_point' object does not have a 'symbol' or 'timestamp' attribute: {data_point}")
                except KeyError:
                    print(f"The symbol '{data_point.symbol}' is not present in the symbol_dic dictionary")

huangapple
  • 本文由 发表于 2023年1月6日 12:03:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定