Reputation: 15
I am trying to get the asset/free/locked fields along with the corresponding data to populate into columns. Currently, I can only get the balances column where these fields fall.
Here is the data format. I don't need anything before 'balances'. Thinking if I could remove this part of the string maybe then the columns would be created? Or if there is a another way to do this?
'{'makerCommission': 10, 'takerCommission': 10, 'buyerCommission': 0, 'sellerCommission': 0, 'canTrade': True, 'canWithdraw': True, 'canDeposit': True, 'updateTime': 1595872633345, 'accountType': 'MARGIN', 'balances': [{'asset': 'BTC', 'free': '0.00000000', 'locked': '0.00000000'}, {'asset': 'LTC', 'free': '0.00000000', 'locked': '0.00000000'}, {'asset': 'ETH', 'free': '0.00000000', 'locked': '0.00000000'}...'
The code so far to get the balances is:
account = client.get_account()
assets = pd.DataFrame(account, columns = ['balances'])
Any help appreciated. Got me stumped.
Upvotes: 0
Views: 141
Reputation: 62453
account
is a string
, it must be converted to a dict
with ast.literal_eval
.account
as a dict
, use pandas.json_normalize
to extract the nested keys
and values
from ast import literal_eval
import pandas as pd
# if account is a string
assets = pd.json_normalize(literal_eval(account), 'balances')
# if account is a dict
assets = pd.json_normalize(account, 'balances')
# display(assets)
asset free locked
0 BTC 0.00000000 0.00000000
1 LTC 0.00000000 0.00000000
2 ETH 0.00000000 0.00000000
str
data = "{'makerCommission': 10, 'takerCommission': 10, 'buyerCommission': 0, 'sellerCommission': 0, 'canTrade': True, 'canWithdraw': True, 'canDeposit': True, 'updateTime': 1595872633345, 'accountType': 'MARGIN', 'balances': [{'asset': 'BTC', 'free': '0.00000000', 'locked': '0.00000000'}, {'asset': 'LTC', 'free': '0.00000000', 'locked': '0.00000000'}, {'asset': 'ETH', 'free': '0.00000000', 'locked': '0.00000000'}]}"
Upvotes: 2