JstSomeGuy
JstSomeGuy

Reputation: 111

Sum Values in List of Dictionaries

I have code that is returning a list of dicts, which looks like this:

[{'id': 3605917, 'qty': 66640, 'side': 'Buy', 'time': 1609395938896, 'symbol': 'BTCUSD', 'price': 28901.5}, {'id': 3605914, 'qty': 500, 'side': 'Buy', 'time': 1609395936891, 'symbol': 'BTCUSD', 'price': 28907.5}, {'id': 3605911, 'qty': 1, 'side': 'Buy', 'time': 1609395874764, 'symbol': 'BTCUSD', 'price': 28942}, {'id': 3605449, 'qty': 70000, 'side': 'Sell', 'time': 1609384815688, 'symbol': 'BTCUSD', 'price': 28956}, {'id': 3605440, 'qty': 40, 'side': 'Sell', 'time': 1609384671382, 'symbol': 'BTCUSD', 'price': 28940}]

Reading through some previous questions, I was able to get some code to allow me to sum the total quantity for each side, where stream is the list above.

from collections import defaultdict

    b = defaultdict(int)
    for q in stream:
        b[q['side']] += q['qty']

    print(b)

This returns something that looks like this. I truncated the list above, so the numbers below won't match the example list:

defaultdict(<class 'int'>, {'Buy': 8106603, 'Sell': 1482687})

I'd like to modify the code above to show both the sum of the quantity, but also the average price. Weighted average by qty would be ideal, but would also be ok with a simple average.

Upvotes: 1

Views: 48

Answers (1)

Jarvis
Jarvis

Reputation: 8564

For printing sum of quantities, one-liners:

a = [{'id': 3605917, 'qty': 66640, 'side': 'Buy', 'time': 1609395938896, 'symbol': 'BTCUSD', 'price': 28901.5}, {'id': 3605914, 'qty': 500, 'side': 'Buy', 'time': 1609395936891, 'symbol': 'BTCUSD', 'price': 28907.5}, {'id': 3605911, 'qty': 1, 'side': 'Buy', 'time': 1609395874764, 'symbol': 'BTCUSD', 'price': 28942}, {'id': 3605449, 'qty': 70000, 'side': 'Sell', 'time': 1609384815688, 'symbol': 'BTCUSD', 'price': 28956}, {'id': 3605440, 'qty': 40, 'side': 'Sell', 'time': 1609384671382, 'symbol': 'BTCUSD', 'price': 28940}]

print('Buy', sum(i['qty'] for i in a if i['side'] == 'Buy'))
print('Sell', sum(i['qty'] for i in a if i['side'] == 'Sell'))

For average of prices:

print(sum(i['qty']*i['price'] for i in a if i['side'] == 'Buy')/len(list(i for i in a if i['side'] == 'Buy')))
print(sum(i['qty']*i['price'] for i in a if i['side'] == 'Sell')/len(list(i for i in a if i['side'] == 'Sell')))

Upvotes: 1

Related Questions