Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def calculate_profit_loss_updated(events):
- holdings = {} # Stores the quantity and total cost of each stock
- market_prices = {} # Stores the current market price of each stock
- profits = [] # Stores the profits for each QUERY event
- for event in events:
- details = event.split()
- action = details[0]
- stock = details[1] if len(details) > 1 else None
- if action == "BUY":
- quantity = int(details[2])
- # Initialize stock in holdings and market_prices if not present
- if stock not in holdings:
- holdings[stock] = [0, 0] # [quantity, total cost]
- market_prices[stock] = 0
- # Update holdings
- holdings[stock][0] += quantity
- holdings[stock][1] += quantity * market_prices[stock]
- elif action == "SELL":
- quantity = int(details[2])
- # Calculate profit/loss from selling
- sell_value = quantity * market_prices[stock]
- original_cost = (holdings[stock][1] / holdings[stock][0]) * quantity
- # Update holdings
- holdings[stock][0] -= quantity
- holdings[stock][1] -= original_cost
- elif action == "CHANGE":
- price_change = int(details[2])
- # Update market price
- market_prices[stock] += price_change
- elif action == "QUERY":
- # Calculate current net profit/loss
- current_profit = 0
- for stock, (quantity, total_cost) in holdings.items():
- current_value = quantity * market_prices[stock]
- current_profit += current_value - total_cost
- profits.append(current_profit)
- return profits
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement