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})]}
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')
print(type(barset_entity))
# OUTPUT: <class 'alpaca_trade_api.entity.BarSet'>
barset_dict = barset_entity._raw
print(type(barset_dict))
# OUTPUT: <class 'dict'>
barset_json = json.dumps(barset_dict)
print(type(barset_json))
# 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.
Yep! Here’s the structure of the BarSet entity:
BarSet(dict)
['SPY'] Bars(list)
[0] Bar(Entity)
bar.t
bar.o
bar.h
bar.l
bar.c
bar.v
[...] 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)
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.