Get_Stock_Bars for multiple assets

Wrote this function which inherits from a class where multiple symbols are passed. However, only one symbol’s bars are returned, and it is always the first symbol alphabetically. I am passing [“GOOG”, “TSLA”, “AAPL”] and getting results only for “AAPL”

 def GetLastXBars(self, NumOfBars:int) -> BarSet: # dict:
    """
    Basic simulation to simulate the success of trades, once the trade entry point was set.
    """
    Request = StockBarsRequest(symbol_or_symbols=self.StockSymbols, limit=NumOfBars, timeframe=self.alpaca_time_frame)
    response = self.stock_client.get_stock_bars(request_params=Request)
    return response

The issue arises because response from Alpaca’s get_stock_bars method returns a dictionary keyed by symbol, not a merged dataset. Your current code just returns this dictionary, and when you try to access bars, you’re likely only using the first symbol alphabetically by default, causing the confusion.

Why the issue occurs:

Alpaca’s API returns something like:

{
“AAPL”: […], # Bars for AAPL
“GOOG”: […], # Bars for GOOG
“TSLA”: […], # Bars for TSLA
}

When you call methods expecting a flat structure or iterate incorrectly, only the first symbol (alphabetically) will appear.

You must explicitly access each symbol’s bars within the returned dictionary. Here’s the correct way to handle it:

def GetLastXBars(self, NumOfBars:int) → dict:
“”"
Returns a dictionary of Bar objects keyed by each symbol.
“”"
request = StockBarsRequest(
symbol_or_symbols=self.StockSymbols,
limit=NumOfBars,
timeframe=self.alpaca_time_frame
)
response = self.stock_client.get_stock_bars(request_params=request)

# Access the `.data` attribute explicitly if you're using the newer Alpaca SDK.
bars_dict = response.data

return bars_dict

Example of how to correctly access results after calling the function:

bars = instance.GetLastXBars(5)

for symbol in bars:
print(f"Bars for {symbol}:")
for bar in bars[symbol]:
print(bar)

You might have done something like this inadvertently:

bars = instance.GetLastXBars(5)
for bar in bars:
print(bar) # This just iterates the dictionary keys, i.e., symbols, or only one symbol’s bars.

Correction: Always iterate explicitly:

bars = instance.GetLastXBars(5)
for symbol, bar_list in bars.items():
print(f"Symbol: {symbol}")
for bar in bar_list:
print(bar)

Thank you for your support and very detailed answer, but I still get only the results for AAPL.
I am calling my function like so:
xbars = BaseTradeUtil([‘TSLA’, ‘GOOG’, ‘AAPL’])
xdict = xbars.GetLastXBars(2)
for symbol, bar_list in xdict.items():
print(f"Symbol: {symbol}")
for bar in bar_list:
print(bar)

and the result is below:
Symbol: AAPL
symbol=‘AAPL’ timestamp=datetime.datetime(2025, 4, 1, 7, 51, tzinfo=TzInfo(UTC)) open=221.42 high=221.46 low=221.41 close=221.46 volume=2308.0 trade_count=81.0 vwap=221.417122
symbol=‘AAPL’ timestamp=datetime.datetime(2025, 4, 1, 8, 2, tzinfo=TzInfo(UTC)) open=221.2 high=221.2 low=220.74 close=220.74 volume=9125.0 trade_count=344.0 vwap=221.039978

Any thoughts?

ok. I finally figured it out. I used limit in the request passing limit = 3 expecting that it would retrieve 3 candles for each symbol.
Turns out using limit, limits the total number of candles retrieved, not related to the number of symbols. so if I limit the timeframe to 3 days, and specify limit=7, it would retrieve 3 candles from AAPL, 3 from GOOG and only 1 from TSLA. Totaling 7 records.
So now I need to specify the correct timeframe and this will solve my problem.
Thank you !