コード例 #1
0
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")
コード例 #2
0
#VIEWS
if option == '1':
    holdings = helpers.queryHoldings(user)
    hold_dict = defaultdict(list)
    for tkr, amt, num in holdings:
        hold_dict[tkr].append(amt)
        hold_dict[tkr].append(num)
        hold_dict[tkr].append(amt*num)
        hold_dict[tkr].append(price(tkr)*num)
    print(hold_dict)

#option BUY
if option == '2':
    stock_options = ['GOOG','AAPL','IBM','VTI','VNQ','TSLA']
    cash = helpers.queryCash(user)
    print("You have $",cash," to spend")
    print("You can buy the following stocks: ",stock_options)
    while True:
        ticker = input("Enter ticker symbol: ").strip().upper()
        if ticker in stock_options:
            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: