gabrsafwat
gabrsafwat

Reputation: 128

Python TypeError: list indices must be integers or slices, not Bar when downloading stock prices in "Chunks" using Alpaca API

I am trying to download prices for chunks of tickers using Alpaca Markets API.

    chunk_size = 200
for i in range(0, len(symbols), chunk_size):
    symbol_chunk = symbols[i:i+chunk_size]
    barsets = api.get_bars(symbol_chunk, TimeFrame.Day, start="2019-10-01", end=None, adjustment='raw')

for symbol in tqdm(barsets):
    for bar in barsets[symbol]:
        stock_id = symbol_dic[symbol]
        cursor.execute("""
            INSERT INTO stock_price (stock_id, date, open, high, low, close, volume) VALUES (?, ?, ?, ?, ?, ?, ?)
            """, (stock_id, bar.t.date(), bar.o, bar.h, bar.l, bar.c, bar.v))

connection.commit()

on the line "for bar in barsets[symbol]:" I get a TypeError:

TypeError: list indices must be integers or slices, not Bar

How to fix that?!

Upvotes: 0

Views: 108

Answers (1)

gabrsafwat
gabrsafwat

Reputation: 128

This is how I fixed it. apparently, I was writing something wrong.

chunk_size = 200
for i in tqdm(range(0, len(symbols), chunk_size)):
    symbol_chunk = symbols[i:i+chunk_size]
    # If you are going to use a start/end dates, make sure to use the format (start="2019-10-01", end="2022-10-30")
    daily_bars = api.get_bars(symbol_chunk, TimeFrame.Day, start="2019-10-01", end=None, adjustment='raw')
    for bar in daily_bars:
        stock_id = symbol_dic[bar.S]
        cursor.execute("""
            INSERT INTO stock_price (stock_id, date, open, high, low, close, volume) VALUES (?, ?, ?, ?, ?, ?, ?)
            """, (stock_id, bar.t.date(), bar.o, bar.h, bar.l, bar.c, bar.v))

connection.commit()

Upvotes: 0

Related Questions