Advertisement
rajeshinternshala

Untitled

Nov 18th, 2023
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. def calculate_profit_loss_updated(events):
  2.     holdings = {}  # Stores the quantity and total cost of each stock
  3.     market_prices = {}  # Stores the current market price of each stock
  4.     profits = []  # Stores the profits for each QUERY event
  5.  
  6.     for event in events:
  7.         details = event.split()
  8.         action = details[0]
  9.         stock = details[1] if len(details) > 1 else None
  10.  
  11.         if action == "BUY":
  12.             quantity = int(details[2])
  13.             # Initialize stock in holdings and market_prices if not present
  14.             if stock not in holdings:
  15.                 holdings[stock] = [0, 0]  # [quantity, total cost]
  16.                 market_prices[stock] = 0
  17.             # Update holdings
  18.             holdings[stock][0] += quantity
  19.             holdings[stock][1] += quantity * market_prices[stock]
  20.  
  21.         elif action == "SELL":
  22.             quantity = int(details[2])
  23.             # Calculate profit/loss from selling
  24.             sell_value = quantity * market_prices[stock]
  25.             original_cost = (holdings[stock][1] / holdings[stock][0]) * quantity
  26.             # Update holdings
  27.             holdings[stock][0] -= quantity
  28.             holdings[stock][1] -= original_cost
  29.  
  30.         elif action == "CHANGE":
  31.             price_change = int(details[2])
  32.             # Update market price
  33.             market_prices[stock] += price_change
  34.  
  35.         elif action == "QUERY":
  36.             # Calculate current net profit/loss
  37.             current_profit = 0
  38.             for stock, (quantity, total_cost) in holdings.items():
  39.                 current_value = quantity * market_prices[stock]
  40.                 current_profit += current_value - total_cost
  41.             profits.append(current_profit)
  42.  
  43.     return profits
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement