def buy(user, ticker, sharenum): market_price = price(ticker) userStocks = helpers.queryTickers(user) #update amount of shares and average share price if ticker in userStocks: values = helpers.queryPriorStock(user, ticker) prior_shareprice = float(values[0]) prior_sharenum = int(values[1]) new_sharenum = prior_sharenum + share_num new_shareprice = ((prior_shareprice*prior_sharenum) + (market_price * sharenum)) / (new_sharenum) updateValues = [new_shareprice, new_sharenum, user, ticker] sql = "UPDATE account SET shareprice = ?, sharenum =? WHERE userid = ? and ticker = ?" cursor.execute(sql, updateValues) conn.commit() else: #insert new ticker insertValues = [user, ticker, market_price, sharenum] sql = "INSERT INTO account VALUES (?,?,?,?)" cursor.execute(sql, insertValues) conn.commit() #Deduct total share cost from cash value cash = helpers.queryCash(user) cost = sharenum * market_price new_cash = cash - cost updateValues = [new_cash, user] sql = "UPDATE account SET shareprice = ? WHERE ticker = 'CASH' and userid = ?" cursor.execute(sql, updateValues) conn.commit() print("You successfully purchased "+str(share_num)+" share(s) of " \ +ticker+" @ $"+str(market_price)+" per share") fh.write(user+" bought "+str(share_num)+" share(s) of "+ticker+" @ $"+str(market_price)+"\n")
break # price() returns float market_price = price(ticker) print("Current market value: "+ str(market_price)) #Make sure user has enough cash while True: share_num = int(input("Enter number of shares to purchase: ").strip(' ')) if cash < (share_num * market_price): print("Not enough cash. Buy less shares.") else: break buy(user, ticker, share_num) #option SELL elif option =='3': tickerDB = helpers.queryTickers(user); print("You owe shares of :", tickerDB) while True: ticker = input("Enter ticker symbol: ").strip() #probably should make sure user does not select cash if ticker in tickerDB and ticker: break; sharenumDB = helpers.querySharenum(user,ticker) print("You have: " + str(sharenumDB) + " shares.") while True: share_num = input("Enter number of shares to sell: ").strip(' ') #Make sure user has enough shares to sell if int(share_num) <= sharenumDB: break; print("Current market value: " + str(price(ticker))) sell(user,ticker,share_num)