This code produces a list of dictionaries.
watchlist = r.get_open_option_positions()
for x in watchlist:
print('Symbol: {}, Average Price: {}, Quantity: {}'.format(x['chain_symbol'],
x['average_price'], x['quantity']))
Output:
Symbol: PG, Average Price: -46.5714, Quantity: 35.0000
Symbol: PG, Average Price: 33.7142, Quantity: 35.0000
Symbol: MSFT, Average Price: -80.0000, Quantity: 6.0000
Symbol: MSFT, Average Price: 53.0000, Quantity: 6.0000
How do I code the following criteria:
if symbol is the same and quantity of both symbols is the same, then subtract average prices and multiply by quantity
So for example the result should look like:
Symbol: PG, Average Price: (-12.8572 * 35), Quantity: 35.000
Symbol: MSFT, Average Price: (-27 * 6), Quantity: 6.000
groups = collections.defaultdict(list)
watchlist
add each x
to a group:
for x in watchlist:
groups[(x["chain_symbol"], x["quantity"])].append(x)
for group_key, group in groups.items():
final_price = sum(x["average_price"] for x in group)
print(group_key, final_price)