
Sponsored
Sponsored
1def calculate_capital_gain_loss(stocks):
2 gains = {}
3
4 for stock in stocks:
5 name = stock['stock_name']
6 operation = stock['operation']
7 price = stock['price']
8
9 if operation == 'Buy':
10 if name not in gains:
11 gains[name] = {'prices': [], 'net': 0}
12 gains[name]['prices'].append(price)
13 elif operation == 'Sell':
14 buy_price = gains[name]['prices'].pop(0)
15 gain_loss = price - buy_price
16 gains[name]['net'] += gain_loss
17
18 result = [{'stock_name': k, 'capital_gain_loss': v['net']} for k, v in gains.items()]
19 return result1function calculateCapitalGainLoss(stocks)