Search code examples
pythonarraysmultidimensional-arraytradingalgorithmic-trading

How to split 3rd order multidimensional array into different arrays in python?


I'm making a crypto currency analysis script, the exchange api bundles the market spread in one JSON object, which prints this-

{'error': [], 'result': {'XXBTZEUR': {'asks': [['892.00000', '0.067', 
1489866640]], 'bids': [['891.86000', '0.032', 1489866639]]}}}

As you can see, this is a multidimensional array. Let me simplify it's structure for you.

c = {'a':[],'b':{'bsubarray':{'asks':[[x1,y1,z1],[x2,y2,z2],...]
                             {'bids':[[x1,y1,z1],[x2,y2,z2],...]}

I'm trying to get 4 arrays out of this- ask_x and ask_y and bid_x and bid_y

This is literally my third program in python, so any detailed explanation would really help me learn.

Thank you!


Solution

  • To extract ask_x, ask_y, etc. then you just need to zip up the relevant asks, etc, e.g.:

    >>> c = {'a':[],'b':{'bsubarray':{'asks':[['x1','y1','z1'],['x2','y2','z2'],['x3','y3','z3']],
    ...                               'bids':[['x1','y1','z1'],['x2','y2','z2'],['x3','y3','z3']]}}}
    >>> ask_x, ask_y, ask_z = zip(*c['b']['bsubarray']['asks'])
    >>> bid_x, bid_y, bid_z = zip(*c['b']['bsubarray']['bids'])
    >>> ask_x
    ('x1', 'x2', 'x3')
    >>> ask_y
    ('y1', 'y2', 'y3')
    

    Using your actual data:

    >>> c = {'error': [], 'result': {'XXBTZEUR': {'asks': [['892.00000', '0.067', 1489866640]], 
    ...                                           'bids': [['891.86000', '0.032', 1489866639]]}}}
    >>> ask_x, ask_y, ask_z = zip(*c['result']['XXBTZEUR']['asks'])
    >>> bid_x, bid_y, bid_z = zip(*c['result']['XXBTZEUR']['bids'])
    >>> ask_x
    ('892.00000',)
    >>> ask_y
    ('0.067',)