0

I'm trying to use the alpaca API to retrieve some stock prices and I get this error:

for bar in bars[symbol]:
TypeError: list indices must be integers or slices, not Bar

My code:

api = tradeapi.REST(config.API_KEY, config.SECRET_KEY,
                    base_url=config.BASE_URL)

chunk_size = 200
for i in range(0, len(symbols), chunk_size):

    symbol_chunk = symbols[i:i+chunk_size]
    bars = api.get_bars(symbol_chunk, TimeFrame.Day,
                        "2022-01-01", "2022-08-08")

    for symbol in bars:
        print(f"processing symbol {symbol}")
        for bar in bars[symbol]:
            stock_id = stock_dict[symbol]
            cursor.execute("""
                INSERT INTO stock Price (stock id, datetime, open, high, low, close, volume)
                VALUES (?,?,?,?,?,?,?)
            """, (stock_id, bar.t.date(), bar.o, bar.h, bar.l, bar.c, bar.v))
Michael M.
  • 10,486
  • 9
  • 18
  • 34
tommy
  • 1
  • 1
  • if you need all the code just let me know its about 40 lines only thank youuu all – tommy Oct 05 '22 at 18:52
  • I can't see where the changes were made can you clarify plz – tommy Oct 05 '22 at 20:02
  • 2
    We don't want _all_ your code, but we do very much want a [mre] -- the shortest possible code that can be run **without any changes** to see the same problem. – Charles Duffy Oct 05 '22 at 20:02
  • 1
    Needing to perform `import tradeapi` for example, _is a change_; and if that API can't be used without credentials you can't share, then code that uses it can't be a [mre] anyhow. Can you build a Python object that behaves _like_ `bars` does in the relevant ways, such that if we fix the problem with the class you provide, it'll also be fixed for your real-world code? – Charles Duffy Oct 05 '22 at 20:02
  • Well, api.bars returns Bar objects, so symbol is a Bar on each iteration. By using symbol to index into bars, you basically use the elements of bars itself to index bars, while from the error message, it looks like bars is a collection with numeric indices. Basically, it looks like the inner for loop is completely redundant, since "symbol" is already what you want "bar" to be. – Larry Oct 05 '22 at 23:25

0 Answers0