Convert bar data object to JSON

How do you convert the response that comes back from the Python alpaca_trade_api to JSON?
Here is an example of the response in Python.

{‘GME’: [Bar({‘c’: 133.6, ‘h’: 144.72, ‘l’: 131, ‘o’: 144.72, ‘t’: 1614285000, ‘v’: 61699})]}

By default, the API returns a custom Entity object called BarSet. This object has a _raw property which contains the data as a dict. You can convert that dict to a JSON string. See more here.

barset_entity = api.get_barset(['SPY'], 'day')
# OUTPUT: <class 'alpaca_trade_api.entity.BarSet'>

barset_dict = barset_entity._raw
# OUTPUT: <class 'dict'>

barset_json = json.dumps(barset_dict)
# OUTPUT: <class 'str'>

Peter, Thank you! I completely overlooked this in the docs yesterday.

Follow up question if you don’t mind. Do you know if it is possible to iterate through a barset? It seems like you ought to be able to since a barset is s collection of bars, which you need to be able to access via a loop.

1 Like

Yep! Here’s the structure of the BarSet entity:

	['SPY'] Bars(list)
		[0] Bar(Entity)
		[...] more Bar entities
	[...] more Bars entities

BarSet inherits dict and Bars inherits list. You can iterate over them accordingly:

barset = api.get_barset(['SPY'], 'day')
for symbol in barset:
    bars = barset[symbol]
    for bar in bars:
        print('Volume', bar.v)
1 Like

Peter, Once again, Thank you! I’m not sure what I was doing wrong when I initially attempted this myself, but now it works as it should. Thanks for getting me squared away.