I have a list of stocks and positions as tuples. Positive for buy, negative for sell. Example:
p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)]
How can I sum the positions of stocks, to get the current holdings?
result = [('AAPL', 0), ('RY', 57)]
I would do this using collections.Counter
:
In [2]: from collections import Counter
In [3]: c = Counter()
In [4]: for k, v in p:
...: c[k] += v
...:
In [5]: c
Out[5]: Counter({'AAPL': 0, 'RY': 57})
Then you can call the most_common
method of Counter
objects to get a list of tuples sorted by the values in descending order.
In [5]: c.most_common()
Out[5]: [('RY', 57), ('AAPL', 0)]
In case you need to sort tuples by their first elements, use sorted(c.items())
:
In [6]: sorted(c.items())
Out[6]: [('AAPL', 0), ('RY', 57)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With