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
)
""")
I used to have the same issue and I fixed it using the following code: