Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a Python class StockTracker to implement this queue-like structure. Here

ID: 3678112 • Letter: C

Question

Create a Python class StockTracker to implement this queue-like structure.

Here is a description of the constructor and methods:
The constructor "StockTracker ()" creates an initially empty StockTracker object. The "buy (quantity, price)" method performs a purchase transaction. Quantity should be a positive integer and price should be a positive floating point value. A ValueError will be raised if any of these conditions is not satisfied. The "sell (quantity, price)" method performs a sell transaction. Quantity should be a positive integer and price should be a positive floating point value. Also the quantity to sell must be equal to or less than the total number of shares on hand. A ValueError will be raised if any of these conditions is not satisfied. It returns the gain (or loss) for this particular transaction. The "getProfit ()" method returns the total gain (or loss) since the creation of the object. The "getQuantityOnHand ()" method the quantity of shares on hand.

Explanation / Answer

class StockTracker:
  
def __init__(self):
self.queue = []
self.quantity_shares_on_hand = 0
self.gain_or_loss = 0
  
def buy(self, q, p):
try:
quantity = int(q)
price = float(p)
except ValueError:
raise (ValueError, "Enter quantity integer and price float and positives")
return
  
if ((quantity < 1) or (price < 1)):
raise (ValueError, "Enter quantity and price integers and positives")
return
  
self.queue.append(["buy", quantity, price])
self.quantity_shares_on_hand = self.quantity_shares_on_hand+quantity
self.gain_or_loss = self.gain_or_loss + quantity * price
  
def sell(self, q, p):
try:
quantity = int(q)
price = float(p)
except ValueError:
raise (ValueError, "Enter quantity integer and price float and positives")
return
  
if ((quantity < 1) or (price < 1)):
raise (ValueError, "Enter quantity and price integers and positives")
return
  
if (quantity > self.quantity_shares_on_hand):
raise (ValueError, "Enter quantity <= ",self.quantity_shares_on_hand)
return
  
self.queue.append(["sell", quantity, price])
self.quantity_shares_on_hand = self.quantity_shares_on_hand-quantity
self.gain_or_loss = self.gain_or_loss + quantity * price
return quantity * price
  
def getProfit(self):
return self.gain_or_loss
  
def getQuantityOnHand(self):
return self.quantity_shares_on_hand
  

def main():

ST = StockTracker()
ST.buy(12,34.5)
ST.buy(100,25.5)
ST.sell(101, 35.8)
  
print ("Quantity Shares On Hand ->", ST.getQuantityOnHand())
print ("Gain or Loss ->", ST.getProfit())

main()